text
stringlengths
15
59.8k
meta
dict
Q: cheque (or check) printing with html php web app I am working on a solution that gives all the details for a check like the payment details and the name and address of the person to be paid. I want to use web technologies like html, xml, php etc. to print the check details on a physical check as quick-books does. I've tried it with adjusting the pixels and font size everything as per the ISO check standard, but I believe its not a good solution for the problem. Is there any API or anything available for this purpose with xml/json or any other type of data ?
{ "language": "en", "url": "https://stackoverflow.com/questions/32591838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VBA: Speed efficient deleting rows My solution takes a long time to execute. I have file with 60k rows, and it can be bigger. Can you help me to make this process faster? Sub kary() Dim table As Variant Dim Wb As Workbook Dim liczba, i As Long Application.ScreenUpdating = False Set Wb = Application.ActiveWorkbook table = Wb.Worksheets("raport").Range("A1").CurrentRegion i = 8 While Cells(i, 1) <> "" If Cells(i, 11) <= 0 Or Cells(i, 5) = "FV_K" Or Cells(i, 5) = "KFD" Or Cells(i, 5) = "KR" Then Rows(i).Delete Shift:=xlUp Else i = i + 1 End If Wend Application.ScreenUpdating = True End Sub A: Can try setting calculation to manual and disabling events 'Optimise code performance Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Application.EnableEvents = False . . . Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic Application.EnableEvents = True
{ "language": "en", "url": "https://stackoverflow.com/questions/45209885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON to Database table Example JSON: [{"steward":"EMPL-0102","description":"Elish Guage","emplyear":"2001","emplmonth":"Nov","empl":"HOME","perhour":"50"}, {"steward":"EMPL-9002","description":"Bush Harcourt","emplyear":"1990","emplmonth":"Nov","empl":"HOME","perhour":"50"}, {"steward":"EMPL-0102","description":"John Long","emplyear":"2001","emplmonth":"Nov","empl":"OFFICE","perhour":"50"}, {"steward":"EMPL-9002","description":"Wensel Gold","emplyear":"1990","emplmonth":"Nov","empl":"OFFICE","perhour":"50"}] I need step-by-step workable Delphi snippet to translate JSON data received from PHP website to local database table. I have tried reading some documents but could not understand the proper implementation of my requirement. I received the JSON data from my website and wish to parse this data into my local table. I wish to asses the JSON record fields such as in table format (Column and rows). I will really like to have it similar to FieldByName('field').AsString = JSONFieldByName('steward').AsString then to the next JSON array record. A: It's hard to get too specific without actual code and data to look at, but here's a general idea. This example uses the dwsJSON library from DWS, but the basic principles should work with other JSON implementations. It assumes that you have a JSON array made up of JSON objects, each of which contains only valid name/value pairs for your dataset. procedure JsonToDataset(input: TdwsJSONArray; dataset: TDataset); var i, j: integer; rec: TdwsJSONObject; begin for i := 0 to input.ElementCount - 1 do begin rec := input.Elements[i] as TdwsJSONObject; dataset.Append; for j := 0 to rec.ElementCount - 1 do dataset[rec.names[j]] := rec.Values[j].value.AsVariant; dataset.Post; end; //at this point, do whatever you do to commit data in this particular dataset type end; Proper validation, error handling, etc is left as an exercise to the reader. A: The following code is more specific to your example. You can make use of JSON functionality used in this code, even though your requirement changes. In this array of string list contains (key, value) pairs. each string contains one record in the JSON object. You can refer using array index. procedure ParseJSONObject(jsonObject : TJSONObject); var jsonArray : TJSONArray; jsonArrSize, jsonListSize : Integer; iLoopVar, iInnLoopVar : Integer; recordList : array of TStringList; begin jsonArrSize := jsonObject.Size; SetLength(recordList, jsonArrSize); for iLoopVar := 0 to jsonArrSize - 1 do begin recordList[iLoopVar] := TStringList.Create; jsonArray := (jsonObject.Get(iLoopVar)).JsonValue as TJSONArray; jsonListSize := jsonArray.Size; for iInnLoopVar := 0 to jsonListSize - 1 do begin ParseJSONPair(jsonArray.Get(iInnLoopVar), recordList[iLoopVar]); end; end; end; procedure ParseJSONPair(ancestor: TJSONAncestor; var list : TStringList); var jsonPair : TJSONPair; jsonValue : TJSONValue; jsonNumber : TJSONNumber; keyName : String; keyvalue : String; begin if ancestor is TJSONPair then begin jsonPair := TJSONPair(ancestor); keyName := jsonPair.JsonString.ToString; if jsonPair.JsonValue is TJSONString then keyValue := jsonPair.JsonValue.ToString else if jsonPair.JsonValue is TJSONNumber then begin jsonNumber := jsonPair.JsonValue as TJSONNumber; keyvalue := IntToStr(jsonNumber.AsInt); end else if jsonPair.JsonValue is TJSONTrue then keyvalue := jsonPair.JsonValue.ToString else if jsonPair.JsonValue is TJSONFalse then keyvalue := jsonPair.JsonValue.ToString; end; list.Values[keyName] := keyvalue; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/21760025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Amazon MSK failed to associate 1 secret for cluster. The provided secret has an invalid schema We want to set up Username and password authentication with AWS Secrets Manager as per the documentation. * *We created a cluster in MSK *Created a secret as well with name AmazonMSK_testmsk2 and with key as Password and Value as { "username": "alice", "password": "alice-secret" } Still when we associate the secret with MSK we get the error Amazon MSK failed to associate 1 secret for cluster. The provided secret has an invalid schema The troubleshooting documentation is not of much help either A: Turns out you need to use Plaintext form. A: This error can occur when one or more pre-requisites for creating the secret has not been followed. There are a few pre-requisites when creating the secret. AWS document for reference. Listing them below for quick access. * *Choose Other type of secrets (e.g. API key) for the secret type. *Your secret name must have the prefix AmazonMSK_ *Your user and password data must be in the following format to enter key-value pairs using the Plaintext option. { "username": "alice", "password": "alice-secret" } A: In addition to @Sourabh 's answer, a secret created with the default AWS KMS key cannot be used with an Amazon MSK cluster, so what you need to do is: * *Open the Secrets Manager console. *In Secret name, choose your secret. *Choose Actions, and then choose dropdown list, select the AWS KMS key, select the check box for Create new version of secret with new encryption key, and then choose Save. that should solve this error Amazon MSK failed to associate 1 secret for cluster sasl-cluster. Wait for a few minutes and try again. If the problem persists, see AWS Support Center . API Response : The provided secret is encrypted with the default key. You can't use this secret with Amazon MSK. A: This is happening because at the time of secret creation you had selected the default aws kms option. Frist you have to create the new KMS then you have to update it in secret manager creation time. After following all you will not get this error.
{ "language": "en", "url": "https://stackoverflow.com/questions/71687981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get Generic function of TypeToken? I have the following codes. I want to get a generic solution to get the TypeToken only passing the class reference. Type application = new TypeToken<List<Application>>() { }.getType(); Type bill = new TypeToken<List<Bill>>() { }.getType(); Type payment = new TypeToken<List<Payment>>() { }.getType(); I have tried to get the typeToken from an function only passing the class reference. What I have tried already. private static <T> Type getType(Class<T>classType) { return new TypeToken<List<? extends T>>() { }.getType(); } but when I call the method as getType(Application.class) this doesn't return me the List of Application TypeToken and something went wrong to use the Type. Please help me to fix it. Thanks in advance. A: If I understand what you're looking for, this should do it: static <E> TypeToken<List<E>> listToken(Class<E> elementClass) { return new TypeToken<List<E>>() {} .where(new TypeParameter<E>() {}, elementClass); } See ReflectionExplained for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/63930438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any straightforward way to change part of copied text (with python code) into Markdown and Code cell in Jupyter notebook I copied a long text from a webpage including several Python code sections and text sections into my Jypter notebook. Below what I copied and pasted. Is there any straightforward way to convert the code sections to executable Code cell and leave the rest text as Markdown instead of inserting new cell one by one for the code sections? (codes and texts are in separated paragraphs). Below what I want: Thank you for your time in advance. A: If it is just a few lines as in your example, the manual way is most convenient. Paste everything in one cell, and then split the cell by using a keyboard shortcut for that (Ctr-Shift-Minus) and use another keyboard shortcut (M) to change the types of cells with comments in it to Markdown. If you have lots of material to convert, Jupytext might help. https://github.com/mwouts/jupytext .
{ "language": "en", "url": "https://stackoverflow.com/questions/66391135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open source library for viewing or reading document within an Android app? I'm looking for an open-source library for android (Jar), in which I can open documents or pdf files. I have searched the net and haven't found anything suitable or stable. My main goal is to show some encrypted files, which my application will decrypt and pass the file to the viewer; meaning that the whole procedure should be secured. I cannot pass the decrypted file to google-docs or any 3rd-party application, due to security issue. Any help will be appreciated. Thank you all for your time. A: I'd try Apache POI, the Java API for Microsoft documents. Its based on Java and I've seen it used in Android before. I haven't used it myself though, so I can't accredit to how well it works. A: Check out the source code of APV - it's a PDF viewer based on MuPdf library - both are free. You can probably assemble something quickly.
{ "language": "en", "url": "https://stackoverflow.com/questions/9452029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use ReadableStream with Response to return HTML from fetch event of Service Worker I'm trying to return a stream for the HTML response in a service worker but the browser does not seem to be able to parse it (I'm using chrome for this test). So, this one works (in the fetch event): event.respondWith(new Response("<h1>Yellow!</h1>", { headers: { "Content-Type": "text/html" }})) But when I use a ReadableStream it no longer renders in the browser: const stream = new ReadableStream({ start(controller) { controller.enqueue("<h1>Yellow!</h1>") controller.close() } }) event.respondWith(new Response(stream, { headers: { "Content-Type": "text/html" }})) It seems like maybe the browser doesn't understand that I'm sending it a stream. But I don't know what headers I would need to use so the above works. Resources that I have used: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#Examples https://philipwalton.com/articles/smaller-html-payloads-with-service-workers/ UPDATE My question similar to this one but for asynchronous case. A: For some reason it doesn't work when you don't lock stream with ReadableStream.getReader Also when you pass ReadableStream to Response ctor, the Response.text method doesn't process the stream and it returns toString() of an object instead. const createStream = () => new ReadableStream({ start(controller) { controller.enqueue("<h1 style=\"background: yellow;\">Yellow!</h1>") controller.close() } }) const firstStream = createStream().getReader(); const secondStream = createStream().getReader(); new Response(firstStream, { headers: { "Content-Type": "text/html" } }) .text() .then(text => { console.log(text); }); secondStream.read() .then(({ value }) => { return new Response(value, { headers: { "Content-Type": "text/html" } }); }) .then(response => response.text()) .then(text => { console.log(text); });
{ "language": "en", "url": "https://stackoverflow.com/questions/62457644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom filter in Angular I have some problem with custom filter. I can't include it's in my project. Firstly I used a filter: text. I understand that array initialized asynchronously and used this custom filter. But when i include this filter, i have problem ($injector:unpr). Sorry for my English. <div ng-controller="ProductList as products"> <form ng-submit="addProduct()"> <input type="text" placeholder="Enter product" ng-model="productTitle"> <button>Add</button> </form> <ul class="productList"> <li ng-repeat="product in list track by $index | custom:search"> {{product.title}} </li> </ul> <input type="text" placeholder="Search" ng-model="search"> </div> App is here angular.module('lists', []) .controller('ProductList', function($scope) { $scope.list = []; $scope.addProduct = function() { $scope.list.push({title:$scope.productTitle}); $scope.productTitle = ""; } }); And filter is .filter('custom', function() { return function(input, search) { if (!input) return input; if (!search) return input; var expected = ('' + search).toLowerCase(); var result = {}; angular.forEach(input, function(value, key) { var actual = ('' + value).toLowerCase(); if (actual.indexOf(expected) !== -1) { result[key] = value; } }); return result; } }); A: I checked the code and issue seems to be the place the filter is being applied. Fiddle: http://jsfiddle.net/pfgkna8k/2/. Though I didn't know what you were exactly implementing. please check the code <div ng-app="lists"> <div ng-controller="ProductList as products"> <form ng-submit="addProduct()"> <input type="text" placeholder="Enter product" ng-model="productTitle" /> <button>Add</button> </form> <ul class="productList"> <li ng-repeat="product in list track by $index" ng-bind="filteredtitle = (product.title | custom: searchBox)" ng-show="filteredtitle"> </li> </ul> <input type="text" placeholder="Search" ng-model="searchBox" /> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/31355930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing objects as parameters to ActionResult methods in ASP .Net MVC from desktop client Given the following code: using (var client = new WebClient()) { string url = string.Concat(someUrl, "SomeControllerName/", currentId, "/WriteLogFile"); var toWrite = DateTime.Now /* Code to post object to URL goes here e.g. client.UploadValues(url, someNameValueCollectionObject)*/ } And the controller method signature: public ActionResult WriteLogFile(DateTime date, int id) How can I make the first portion of the code pass the DateTime object to this ActionResult method? A: you can use the format string in for the date string url = string.Format("someUrl/SomeControllerName/WriteLogFile/{0}/{1}", currentId, DateTime.Now.ToString("MM-dd-yyyy")); and add an entry in to the routes table to route it to the appropriate controller and action routes.MapRoute("SomeRoutename", "SomeControllerName/WriteLogFile/{id}/{date}", new { controller = "SomeControllerName", action = "WriteLogFile", date= DateTime.Now}); A: Add a query string parameter: var toWrite = DateTime.Now; string url = string.Concat(someUrl, "SomeControllerName/", currentId, "/WriteLogFile"); url = string.Concat(url, "?date=", toWrite.ToString("s"));
{ "language": "en", "url": "https://stackoverflow.com/questions/714155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PrintDocument just prints some part of my JPG file I created an application that allows users to print multiple jpg files. So I send my print request directly, like this: if (existfile == true) { PrinterSettings a=new PrinterSettings(); PrintDocument pd = new PrintDocument(); IEnumerable<PaperSize> size = a.PaperSizes.Cast<PaperSize>(); PaperSize a4 = size.First<PaperSize>(i => i.Kind == PaperKind.A4); pd.DefaultPageSettings.Landscape = true; pd.DefaultPageSettings.PaperSize = a4; pd.PrintPage += PrintPage; pd.Print(); } And the print function : private void PrintPage(object o, PrintPageEventArgs e) { System.Drawing.Image img = System.Drawing.Image.FromFile(CurrentAddress); Point loc = new Point(100, 100); e.Graphics.DrawImage(img, loc); } But this code just prints some part of my image, not all of it .I want to print them scale to fit. How can I do that? A: This might fix the issue. e.Graphics.DrawImage(img, e.MarginBounds); or e.Graphics.DrawImage(img, e.PageBounds); or ev.Graphics.DrawImage(Image.FromFile("C:\\My Folder\\MyFile.bmp"), ev.Graphics.VisibleClipBounds);
{ "language": "en", "url": "https://stackoverflow.com/questions/40258052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows: Can a GDI handle outlive the process which created it? I am trying to track down the cause of a Windows-only problem in my SWT application, which sometimes runs into the following error: org.eclipse.swt.SWTError: No more handles Tracing the line which throws this error reveals that it's calling the CreateWindowEx Windows API function, which can fail if there is not a GDI handle free. The error occurs periodically when running tests against the application on one of our Windows Server 2008 build servers, over Remote Desktop. I have so far found and fixed a number of leaks of SWT Image and Font objects, some of them resulting in hundreds of GDI handles leaked per invocation of the application. However, I am struggling to verify (using a test application which deliberately uses lots of handles) that I've fixed the problem. My test application hits the per-process limit of 10,000 GDI handles. Running it serially doesn't cause a problem; running two or three of it simultaneously does. So, at last comes my question: Is it possible, under any circumstances, for a GDI handle on Windows to outlive the process which created it? If so, is there a tool I can use to view the count of these 'leaked' GDI handles?
{ "language": "en", "url": "https://stackoverflow.com/questions/14629556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bad Request on AWS ElasticSearch I'm trying to connect to an IAM controlled ElasticSearch domain, I've created a request, and signed it, and everything works fine for method GET, but on method POST I get a 400 Bad Request This clearly has something to do with the payload. If I provide a payload empty string ("") it works apporpriately, but anything else results in a bad request. What am I missing? val url = s"https://$host/TEST/article/_search" val serviceName = "es" val regionName = "us-east-1" val request = new DefaultRequest(serviceName) val payload = """{"1":"1"}""".trim val payloadBytes = payload.getBytes(StandardCharsets.UTF_8) val payloadStream = new ByteArrayInputStream(payloadBytes) request.setContent(payloadStream) val endpointUri = URI.create(url) request.setEndpoint(endpointUri) request.setHttpMethod(HttpMethodName.POST) val credProvider = new EnvironmentVariableCredentialsProvider val credentials = credProvider.getCredentials val signer = new AWS4Signer signer.setRegionName(regionName) signer.setServiceName(serviceName) signer.sign(request, credentials) val context = new ExecutionContext(true) val clientConfiguration = new ClientConfiguration() val client = new AmazonHttpClient(clientConfiguration) val rh = new MyHttpResponseHandler val eh = new MyErrorHandler val response = client.execute(request, rh , eh, context); A: note: if you run into this problem, inspect the actual content of the response, it may be a result of a mismatch between the index and your query. My problem was that the specific query I was using was inappropriate for the specified index, and that resulted in a 400
{ "language": "en", "url": "https://stackoverflow.com/questions/41989172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set variable with REST API data I've never used a REST api and I'm having trouble figuring out how to set a variable with the returned result.data. I'm using Meteor with ReactJs and console.log('countries', countries) is returning undefined while console.log(result.data) is returning the countries data. export default class CountryPage extends React.Component { constructor(props) { super(props); } render() { const countries = HTTP.get('https://restcountries.eu/rest/v2/all', (err, result) => { console.log(result.data); return result.data; }); console.log('countries', countries); return ( <div> <Input type="select" name="countrySelect" id="countrySelect"> {countries.map(country => ( <option>{country.name}</option> ))} </Input> </div> ); } } A: Here, we use lifecycle method componentDidMount this is the best place to make API calls and set up subscriptions export default class CountryPage extends React.Component { constructor(props) { super(props); this.state = { countries: [] } } componentDidMount() { HTTP.get('https://restcountries.eu/rest/v2/all', (err, result) => { this.setState({countries:result.data}) }); } render() { const {countries} = this.state; return ( <div> <Input type="select" name="countrySelect" id="countrySelect"> {countries.map(country => ( <option>{country.name}</option> ))} </Input> </div> ); } } A: HTTP request is an asynchronous task. You have to wait for the API's response so export default class CountryPage extends React.Component { constructor(props) { super(props); } render() { HTTP.get('https://restcountries.eu/rest/v2/all', (err, result) => { const countries = result.data; console.log('countries', countries); return ( <div> <Input type="select" name="countrySelect" id="countrySelect"> {countries.map(country => ( <option>{country.name}</option> ))} </Input> </div> ); }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/52068144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Building docker images inside a Jenkins container I am using a jenkins container to execute a pipeline based on this Jenkinsfile: pipeline { agent any tools { maven 'Maven 3.6.0' jdk 'jdk8' } stages { stage('Pull from git') { steps { checkout scm } } stage('Compile App') { steps { sh "mvn clean install" } } stage('Build da Imagem') { steps { script { docker.withTool("docker") { def readyImage = docker.build("dummy-project/dummy-project-image", "./docker") } } } } } } At the last stage i'm getting this Error when it tries to build the docker image. Is it possible build a docker image inside jenkins container? A: Your pipeline executing agent doesn't communicate with docker daemon, so you need to configure it properly and you have three ways (the ones I know): 1) Provide your agent with a docker installation 2) Add a Docker installation from https:/$JENKINS_URL/configureTools/ 3) If you use Kubernetes as orchestrator you may add a podTemplate definition at the beginning of your pipeline and then use it, here an example: // Name of the application (do not use spaces) def appName = "my-app" // Start of podTemplate def label = "mypod-${UUID.randomUUID().toString()}" podTemplate( label: label, containers: [ containerTemplate( name: 'docker', image: 'docker', command: 'cat', ttyEnabled: true)], volumes: [ hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock'), hostPathVolume(hostPath: '/usr/bin/kubectl', mountPath: '/usr/bin/kubectl'), secretVolume(mountPath: '/etc/kubernetes', secretName: 'cluster-admin')], annotations: [ podAnnotation(key: "development", value: appName)] ) // End of podTemplate [...inside your pipeline] container('docker') { stage('Docker Image and Push') { docker.withRegistry('https://registry.domain.it', 'nexus') { def img = docker.build(appName, '.') img.push('latest') } I hope this helps you
{ "language": "en", "url": "https://stackoverflow.com/questions/53602681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get Device name How can i get device name for drive letter example: how can i get device name for G:/ Thank you for any help A: If you want "C:\" to "\Device\SomeHardDisk1" you can use QueryDosDevice. (GetLogicalDriveStrings will list them all)
{ "language": "en", "url": "https://stackoverflow.com/questions/3109681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: if else statement not working on integer values I have the following code: -- content of sys.argv is 2 and 10 which is assigned to the specified variables. wthreshold, cthreshold = sys.argv def Alerting(): if PatternCount < wthreshold: print print LRangeA print print 'PatternMatch=(' + str(PatternCount) + '),' + 'ExactTimeFrame[' + str(BeginSearchDVar) + ',' + str(EndinSearchDVar) + ']=(Yes)' print sys.exit(0) elif PatternCount >= wthreshold and PatternCount < cthreshold: print print LRangeA print print 'PatternMatch=(' + str(PatternCount) + '),' + 'ExactTimeFrame[' + str(BeginSearchDVar) + ',' + str(EndinSearchDVar) + ']=(Yes)' print sys.exit(1) elif PatternCount >= cthreshold: print print LRangeA print print 'PatternMatch=(' + str(PatternCount) + '),' + 'ExactTimeFrame[' + str(BeginSearchDVar) + ',' + str(EndinSearchDVar) + ']=(Yes)' print sys.exit(2) else: print print LRangeA print print 'PatternMatch=(' + str(PatternCount) + '),' + 'ExactTimeFrame[' + str(BeginSearchDVar) + ',' + str(EndinSearchDVar) + ']=(Yes)' print sys.exit(3) LRangeA = """this line 1 another line 2 one more line 3 line 4 line 5 line 6 line 7 line 8""" PatternCount = len(LRangeA.split('\n')) Alerting() When I run this code, it doesn't seem to be correctly checking the numbers in the if statements. The code always seems to go into the first if statement even though the value of PatternCount is 8. A: wthreshold and cthreshold are strings coming from the command line arguments. If you want to compare them numerically, you need to convert them to numbers: wthreshold, cthreshold = [int(x) for x in sys.argv]
{ "language": "en", "url": "https://stackoverflow.com/questions/51003479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web Scraping with BeautifulSoup and unchanging URL I am trying to scrape this r = requests.get(url) soup = BeautifulSoup(r.text , 'lxml') details = soup.find_all('span', {'class' : 'src'}) details = soup.find_all('div', {'class' : 'product_contain'}) i=0 for d in details: print(i,d.get_text(strip=True).strip()) i+=1 But it scrapes only one webpage. I inspected the XHR but nothing gets triggered when it changes the page. I also inspected the FORM DATA in advancesearch.aspx, but it also doesn't have page index related information. On page click event I found ctl00$ContentPlaceHolder1$gvItem$ctl01$ctl03 but not sure how to use this in URL. What URL should I use to access the other pages? A: You should use Selenium in this case which will open the page in a browser and then you can handle the click event of navigator button and access the refreshed DOM each time. Here is a simple code for your reference: from selenium import webdriver browser = webdriver.Firefox() browser.get("http://www.google.com") browser.find_element_by_id("lst-ib").send_keys("book") browser.find_element_by_name("btnK").click() A: The page url you shared, shows that the page-numbers can be accessed through the following hyperlink-tags: * *Current Page: <a class="pager currentpage"> *Other Pages (each): <a class="pager"> You can access the relevant information as follows. The second line will give you a list of all the pages. Extract the "href" attribute from them. When you click on the button, a javascript fires and most likely appends a part of the url to open the new page. soup.findall('a', _class="pager currentpage") soup.findall('a', _class="pager") This is the text of one of the buttons. You will need to study the page source further to figure out what url is needed. <a class="pager currentpage" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions( &quot;ctl00$ContentPlaceHolder1$gvItem$ctl01$ctl03&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, true))" style="display:inline-block;width:27px;">1</a> function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } A better Option Use selenium browser automation to execute the clicks on such javascript-wrapped buttons. A: I was able to achieve without selenium. Although code is not complete but we can scrape all the pages by looping __EVENTTARGET from bs4 import BeautifulSoup import requests,json def returnJson(wordmark): url = "https://classicalnumismaticgallery.com/advancesearch.aspx?auctioncode=0&pricerange=0&keyword=indore&category=&material=0&lotno=&endlotno=" r_init = requests.get(url) soup = BeautifulSoup(r_init.text, 'html.parser') event_validation = soup.find("input", attrs={"name" : "__EVENTVALIDATION"})['value'] view_state = soup.find("input", attrs={"name" : "__VIEWSTATE"})['value'] pages=4 event_target = 'ctl00$ContentPlaceHolder1$gvItem$ctl01$ctl{:>02d}'.format(pages) postdata = { 'ctl00$ContentPlaceHolder1$DDLFilter' : '0', '__EVENTVALIDATION' : event_validation, '__EVENTTARGET' : event_target, "__VIEWSTATE" : view_state, } r = requests.post(url, data=postdata) return r def scraping(r): description='' soup = BeautifulSoup(r.text, 'html.parser') desc = soup.find_all('div' , {'class' : 'product_contain'}) for d in desc: print(d) scraping(returnJson('indore'))
{ "language": "en", "url": "https://stackoverflow.com/questions/58006473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Render function branch not getting covered in react test case I have a Pure Component but i am not getting the render function branch covered in the test cases.What could be the reason
{ "language": "en", "url": "https://stackoverflow.com/questions/53628363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React.js: how to use json data that is loaded in index.js in source file? So this is index.js (my entry point) and I'm loading the json data here import React from 'react'; import ReactDOM from 'react-dom'; import fetch from 'isomorphic-fetch'; import {Filter} from './src/filter'; fetch('./pizza.json') .then(function(response) { return response.json() }).then(function(json) { console.log('parsed json', json) }).catch(function(ex) { console.log('parsing failed', ex) }); ReactDOM.render(<Filter />, document.querySelector('.content')); Now in filter.js where I want to render the contents of the page, I'm not sure how to use the loaded data in index.js, here in filter.js import React, {Component} from 'react'; export class Filter extends Component { render() { return ( <div> <h1> Pizza Search App </h1> </div> ); } } I'm new at React.js and am trying to learn, having trouble understand basic react.js fundamentals, help! A: You should do the fetching in Filter import React, { Component } from 'react'; import fetch from 'isomorphic-fetch'; export class Filter extends Component { state = { data: null } componentWillMount() { fetch('./pizza.json') .then(function (response) { return response.json() }).then(function (json) { console.log('parsed json', json) this.setState(() => ({ data: json })) }).catch(function (ex) { console.log('parsing failed', ex) }); } render() { const { data } = this.state if(!data){ return <div>Loading...</div> } return ( <div> <h1> Pizza Search App </h1> (use data here...) </div> ); } } A: Alex is correct except you need to set the state once you've got the response: EDIT: I missed that he had another link in his promise chain down there... either way, you only need the one. Like so: componentWillMount() { fetch(...).then(res => this.setState({data: res.json()})).catch(.... Also, you need to 'stringify' the json in order to display it in the render method of your component. You're not able to display raw objects like that. Sooo... you'll need to do something like ... render() { const { data } = this.state return ( <div> <pre> <code> {JSON.stringify(data, null, 2)} // you should also look into mapping this into some kind of display component </code> </pre> </div> ) }
{ "language": "en", "url": "https://stackoverflow.com/questions/46920905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL case statement - Multiple conditions I am writing a case statement where I need to check columns and assign a value . But what if a row qualifies for multiple cases ? For example in following table I want assign a bucket when COLA and/or COLB is null ; so in first case both are NULL , so how will I tell SQL case statement to assign "Both are NULL " when COLA and COLB are null. I can easily assign when COLA or COLB is null . At my work I am checking 8 columns , so I need to find every combination and right case for that ? There has to be an easy way . **RowNumber COLA COLB Case** 1 Null Null **Both are NULL** 2 Null B A is null 3 A Null B is null 4 AA BB NULL 5 CC Null B is null A: Given you have 8 columns, you probably need to do something like this: WITH t AS ( SELECT CASE WHEN (colA IS NULL AND colB IS NULL AND colC IS NULL AND colD IS NULL AND colE IS NULL AND colF IS NULL AND colG IS NULL AND colH IS NULL) THEN 'ALL' ELSE '' END [ALL], CASE WHEN colA IS NULL THEN 'A' ELSE '' END [A], CASE WHEN colB IS NULL THEN 'B' ELSE '' END [B], CASE WHEN colC IS NULL THEN 'C' ELSE '' END [C], CASE WHEN colD IS NULL THEN 'D' ELSE '' END [D], CASE WHEN colE IS NULL THEN 'E' ELSE '' END [E], CASE WHEN colF IS NULL THEN 'F' ELSE '' END [F], CASE WHEN colG IS NULL THEN 'G' ELSE '' END [G], CASE WHEN colH IS NULL THEN 'H' ELSE '' END [H] FROM <TABLENAME>) SELECT CASE WHEN [ALL] = 'ALL' THEN 'ALL are NULL' ELSE [ALL] + ',' + A + ',' + B + ',' + C + ',' + D + ',' + E + ',' + F + ',' + G + ',' + H + ' are NULL' END FROM T In the final select statement, you could make further alterations to present the results as you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/18128331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I create separate output file for each sql record? public void selectdata(Connection conn, String database){ String table = "Mo"; // using Mo table, String comandoSql = "SELECT * FROM " + database + "."+"dbo"+ "."+ table; try { stmt = conn.createStatement(); rs = stmt.executeQuery(comandoSql); System.out.println("Command sql: "); while (rs.next()) { String DocumentName = rs.getString(2); doc1 = DocumentName; try { File file = new File("///.txt"); // path to output folder. FileWriter fileWritter = new FileWriter(file,true); BufferedWriter out = new BufferedWriter(fileWritter); out.write(doc1); out.newLine(); out.close(); } catch (IOException e1) { System.out.println("Could not write in the file"); } } } catch (SQLException e) { e.printStackTrace(); } this generates the output file but contains all the records in one file, my problem is how to generate separate file for each record don't want to do the post process in order to generate the separate files? any help?????? not fancy for scanner, because don't know how many lines will be in one record(it is a kind of multiple documents which stored into database table!!!!) A: Just create a new file for each record: int counter = 0; while (rs.next()) { String DocumentName = rs.getString(2); doc1 = DocumentName; try { File file = new File("///" + counter + ".txt"); // path to output folder. FileWriter fileWritter = new FileWriter(file,true); BufferedWriter out = new BufferedWriter(fileWritter); out.write(doc1); out.newLine(); out.close(); counter++; } catch (IOException e1) { System.out.println("Could not write in the file"); } } Just create a counter variable or something to differentiate each file. Append the counter to the file name so it will create a new file for each record...
{ "language": "en", "url": "https://stackoverflow.com/questions/27151931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic controls Handling Postsback caused by calendar and button click Currently, I am having some issues handling post-backs. I can't seem to get the right checkbox value. Been trying to figure this out but not able to. Appreciate all the help I can get. I have a dynamic table, which creates check-boxes in 10 cells (representing hours), according to the number of objects in the database. It is able to insert to datebase without problem if Load Page -> select date by clicking on Img Button -> generate dynamic table based on selected date -> check checkboxes -> add record. However, problem occurs when I view multiple dates (eg:) Load Page -> select date by clicking on Img Button -> generate dynamic table based on selected date -> click Img Button -> Generate dynamic table -> I have done the following code: protected void Page_Load(object sender, EventArgs e) { Calendar1.Visible = false; if (IsPostBack) { LoadData(); //generate dataset to construct table } } protected void Calendar1_SelectionChanged(object sender, EventArgs e) { Calendar1.Visible = false; Table.Rows.Clear(); LoadData(); } I've added Table.Rows.Clear(); on Calendar.SelectionChanged and Imagebutton click. If not, more than one table will appear. Eg: 1 for first date selection, 2nd one following below it from second date selection A: I would suggest using !IsPostBack if (!IsPostBack) { LoadData(); //generate dataset to construct table } This is the initial load. Once you postback - selected change - this should not load again. I assume the LoadData() creates the datatable or set therefore on postback loading it multiple times.
{ "language": "en", "url": "https://stackoverflow.com/questions/36521327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: external interrupt using microphone sensor Arduino UNO Hello when i am not using my Arduino i want it to go to sleep so i can save battery power. this is my output right now i am going to to wake up i am going to to wake up i am going to sleep when it goes to sleep it doesn't wake up again when i clap. I am using arduino uno and this sensor https://www.auselectronicsdirect.com.au/audio-microphone-module-for-arduino-projects?gclid=CjwKCAjwhMmEBhBwEiwAXwFoEVAz-xxw7jaHoXDWixiTV1IHz8TF5i4tKr_1jjTK8s3JvowUDUDnCBoCxdgQAvD_BwE here is my code #include <Servo.h> #include <avr/sleep.h> #define interruptPin 2 Servo myservo; int pos = 0; int soundSensor = 2; boolean LEDStatus = false; void setup() { Serial.begin(9600); pinMode(interruptPin, INPUT_PULLUP); myservo.attach(7); pinMode(soundSensor, INPUT); } void Goint_to_Sleep() { Serial.println(" i am going to sleep"); delay(5000); sleep_enable(); attachInterrupt(digitalPinToInterrupt(interruptPin), wakeUp, LOW); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_cpu(); } void wakeUp() { sleep_disable(); detachInterrupt(0); } void loop() { int SensorData = digitalRead(soundSensor); if (SensorData == 1) { wakeUp(); Serial.println(" i am going to to wake up"); if (LEDStatus == false) { LEDStatus = true; for (pos = 180; pos >= 0; pos -= 40) { // goes from 180 degrees to 0 degrees // in steps of 1 degree myservo.write(pos); delay(15); // waits 15ms for the servo to reach the position } } else { LEDStatus = false; for (pos = 0; pos <= 180; pos += 20) { // goes from 0 degrees to 180 degrees myservo.write(pos); delay(15); // waits 15ms for the servo to reach the position Goint_to_Sleep(); } } } } A: Just a heads-up. You are declaring pin 2 twice, first as interruptPin, then as soundSensor. This might be prone to confusion and misfiring of the ISR Inside your interrupt function, you should wrap your logic inside cli(); and sei(); to avoid false triggering during the interruption. Do not use detachInterrupt(). Review the documentation from avr/sleep.h (here). As it reads, you MUST make sure that interrupts are enabled before sending the CPU to sleep. I believe you are missing a sei() before sending the CPU to sleep I would advise you to use an external (strong) pull-up to guarantee that pin 2 won't be triggered unless is via the sensor. Finally, please observe that according to your logic, the interrupt service will be called any time the pin goes LOW. This will override the else from the conditional inside the loop() (at least this will occur after the first time you call the (mispelled) function Goint_to_sleep()). Think of another approach to accomplish what you want. Just be careful with the ISRs that you implement EDIT: I forgot to mention something extremely important: You need to be absolutely sure that the output signal from the microphone that you are connecting to is above the threshold for a digital signal (~2.60-2.8V). Having said that, are you sure that the interrupt edge detection should be LOW when clapping? I think it must be high in which case the pin should be pulled low. You can always reverse this logic and amplify the signal with an external transistor to convert the sensor's signal into an adequate digital pulse
{ "language": "en", "url": "https://stackoverflow.com/questions/67410735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to programmatically link Field in Enterprise Portal AX 2009 to open a specifical File I'm a new beginner in Microsoft AX. I have a problem in AX 2009. I create a Table ImportFile with 2 Fields,("FileName-->Typ:String", "FileDocuValue-->Typ:Container"). When the User import a CSV-File it will be save in the Table ImportFile. Now in EP I Just show in My GridView a Column FileName and I want that FileName be a Link so that when I click in one one these Names that it Open the Corresponding CSV-File in Excel. Is it possible to do it? A: I can suggest the following approach: * *You can use a standard asp LinkButton control to display a link. When the link has been clicked, *Create a temporary CSV file from the data in your ImportFile table. *Create a URL to the generated CSV file (you can use the WebLink.url method). *Open the generated URL. When I was working on a similar task (generate and download PDF) I also had to modify some standard classes such as WebSession and EPDocuGetWebLet.
{ "language": "en", "url": "https://stackoverflow.com/questions/26139103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to extract the data from from website and save the into txt file i am using python 3.3.3 and trying to extract the data as well as links in txt file. I have tried this code but it is not creating neither saving any thing in the file.At console if i would write "print(s)" then still does not shows anythings to me. import urllib.request with urllib.request.urlopen("http://www.python.org") as url: s = url.read() url.close() #I'm guessing this would output the html source code? #print(s) # write data ff = open("ne.txt", "w") ff.write('s') ff.close() if i am doing wrong then please tell me the correct criteria because i am also understanding and studying from internet resources. Any help please.... A: You can use urllib.request.urlretrieve(url, path_to_file) All code: import urllib.request urllib.request.urlretrieve("https://www.python.org", "/home/user/ne.txt")
{ "language": "en", "url": "https://stackoverflow.com/questions/26673636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cannot access user with HttpContext I'm building and .Net-Core MVC project. The application provides a service called CurrentUserService (classic). I access this service for example when I log and CRUD operation on an entity. When I try to access the user by the IHttpContextAccessor he is not authenticatated even thought he is. And yes I did add services.AddHttpContextAccessor(); to my service collection. I created a contoller, accessed the User property and the user was authenticated. The following picture shows that: Not sure what to do, Help. CurrentUserService public class CurrentUserService : ICurrentUserService { public CurrentUserService(IHttpContextAccessor httpContextAccessor) { var user = httpContextAccessor.HttpContext?.User; if (user != null && user.Identity.IsAuthenticated) { UserId = int.Parse(user.FindFirstValue(ClaimTypes.PrimarySid)); IsAuthenticated = user.Identity.IsAuthenticated; } } public int UserId { get; } public bool IsAuthenticated { get; } } A: It is probably problem with CurrentUserService itself. You are instantiating user in its constructor at which point you maybe don't have user authenticated. I would try to change CurrentUserService like this: public class CurrentUserService : ICurrentUserService { private IHttpContextAccessor httpContextAccessor; public CurrentUserService(IHttpContextAccessor httpContextAccessor) { this.httpContextAccessor = httpContextAccessor; } private ClaimsPrincipal User => httpContextAccessor.HttpContext?.User; public int UserId => User != null && User.Identity.IsAuthenticated ? int.Parse(User.FindFirstValue(ClaimTypes.PrimarySid)) : 0; public bool IsAuthenticated => User != null && User.Identity.IsAuthenticated; }
{ "language": "en", "url": "https://stackoverflow.com/questions/63117812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dealing with strings in c++ template As part of some beginner c++ template exercises, I'm trying to write a template as a wrapper for std::vector in c++, and I've come across a snag. Say the types of variables I'll be using are int, double and string. I'm trying to write a loop to fill in the vector: type element; while (element != 0){ std::cout << "Enter an element, use 0 to exit: "; std::cin >> element; if(element != 0) items.push_back(element); } The problem is, while this works for int & double, it doesn't work with std::string, as string doesn't support !=. I can also see myself having problems with working out the largest/small value in the vector. What is the best way to get around this issue? A: You could provide an optional template argument which is a comparator (I think the standard lib does that frequently). Less ambitiously, you could use type{} to compare against which should work for anything with a default ctor: if(element != type{}). (Your problem is not that string doesn't have a comparison operator but that the operators aren't defined for comparisons with ints).
{ "language": "en", "url": "https://stackoverflow.com/questions/22650497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Neo4j webadmin - wrong dashboard data I have crated a new database from scratch and I loaded there one single type of node. There are no relationships. Each node has two properties. For all these properties the values are not null. Here is the math I cannot understand in the webadmin dashboard. nodes: 19 798 966 properties: 25 440 880 relationships: 0 relationship types :0 I was expecting the number of properties to be 19 798 966 x 2 = 39 597 932 However when query the database, the results are: $ MATCH (n) WHERE has(n.woka_id) RETURN count (n); count (n) 19 798 966 and $MATCH (n) WHERE has(n.woka_title) RETURN count (n); count (n) 19798966 What is wrong here? A: webadmin doesn't really report counts, indeed the highest ID in use is reported. Since multiple properties are stored internally in the same block you'll see misleading numbers there. To validate: MATCH (n) where has(n.woka_title) and has (n.woka_id) RETURN count(n) == 19798966 should return true.
{ "language": "en", "url": "https://stackoverflow.com/questions/31596270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bind ng-model name and ng-click inside ng-repeat in angularjs I need to know naming convention for the ng-model and ng-click inside the ng-repeat. And also need to know how to use each model name and ng-click function in the controller. I have given a sample code to show you what I exactly need know. <input name="" type="button" ng-click="incrementRoomCount()"> <div ng-repeat="student in studentList"> <div>Room <span>{{student.studentCount}}</span></div> <div> <input name="" type="button" ng-click="removeStudent()"> <input name="adult" type="text" ng-model="noOfStudents"> <input name="" type="button" class="roomPopupPlusBtn" ng-click="addStudent()"> </div> <div ng-repeat="studentAge in studentList"> <div ng-show="studentAgeWrapper"> <select name="age"> <option ng-repeat="studentAge in ['20','21','22','23','24','25']">{{studentAge}</option> </select> </div> </div> </div> Thanks A: The following fiddle demonstrates how to call functions when repeating over items. You could also just pass in an id to the remove function. <input value="Remove From Room" type="button" ng-click="removeStudent(student)"/> </div> $scope.removeStudent = function(student) { angular.forEach($scope.studentList, function(checkStudent, index) { if (checkStudent.id === student.id) { $scope.studentList.splice(index,1); } }); }; http://jsfiddle.net/houston88/ab23r/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/21385164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using custom attributes in DOM elements, with boolean value Is there a way to add attributes to a DOM element with boolean value like this: <body test='false'></body> I need to set this without using javascript. Thanks A: HTML5 has something called data-attributes that might fit your needs. You could do something like this: <body data-test="true"></body> And then check the boolean value of the attribute like this (using jQuery): !!$('body').attr('data-test') Explanation of the "double bang" operator: You can get the boolean value of any javascript object like this: !!0 //false !!1 //true !!undefined //false !!true //true Edit As noted by David, a non-empty string (like "false" for example) would yield true. You've got 2 options here: * *dont set the attribute, which will be undefined and hence false *compare to the string "true" instead of using the !! operator Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/3486714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C check if space exists in array, if not reallocate more space? I have to write a program which takes a string argument such as "abcd" and returns a new string like "a-bb-ccc-dddd". so for each char in the string, increment its repetition in new string. In something like C# or Java I would just use a StringBuilder but in C I'm not sure how to check if the string has enough space for a new character. if not, reallocate. char *str = malloc(strlen(source) * sizeof(char)); for (int i = 0; i <= strlen(source) - 1; i++) (for int j = 0; j < i + 1; j++) if (space_exists_in_string(source)) str[j] = source[i]; else { str = realloc(str, strlen(str) * 2); str[j] = source[i] } So basically im looking to find a way to check if (space_exists_in_string). Thanks A: If the array is declared as character array, like char arr[], you can call sizeof(arr) and you'll get the size of the array. But, if it is allocated some heap memory using malloc or calloc, you cannot get the size of the array, except for calling strlen(), which only gives the size of the string, not the memory location. So, either declare your string as an array of characters or store the size of the memory created (when created dynamically) and update it every time you extend/shrink your memory. In your case, I think it would be simple if you allocate some storage for your output and iterate through input and insert data into output. This way, you know how much data to allocate to output and you don't need to extend it. Required space for your output would be (1 + 2 + 3 + 4 + 5 +... strlen(input) times) + (strlen(input)-1)
{ "language": "en", "url": "https://stackoverflow.com/questions/58686813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I make log4j reopen log files periodically (logrotate) My sysadmin has been "encouraging" me to fix our web application logs to play nicely with logrotate. The problem is that after logrotate works on a file the application stops logging. Is there a way to configure log4j to reopen log files after this happens? This comment explains the general problem but doesn't provide a solution for log4j: https://stackoverflow.com/a/6514233/201748 A: I have still to test it, but the copytruncate option of logrotate should do.
{ "language": "en", "url": "https://stackoverflow.com/questions/10710142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CONTAINS function is not working in SQL Server 2014 The following query is written using SQL Server 2014 CONTAINS function. SELECT Org1.OrganizationPK ,* FROM Organization Org1 WHERE Org1.Deleted = 0 AND CONTAINS (Org1.NAME,'"chris6*"') AND org1.OrgDomainInd = 1 But, the above query is NOT working. I have followed this article to understand more about CONTAINS function. I have verified those examples as-they-are. Even here also, I am not getting any results. I have verified this post from stackoverflow, but I could not apply for my requirement. Hence, I am getting doubt whether I need to do anything more to configure SQL Server 2014 to work with CONTAINS fuction? Please let me know if there is anything I need to do to make SQL Server 2014 ready to use CONTAINS function. If there is nothing like that, please suggest me the solution. Please don't suggest me to use LIKE operator. I am telling this why because, most of my colleagues suggested me same; hence, as a precautionary matter I am writing this statement here. I am running behind my schedule to complete this task. A: I believe that contains functionality can only be used in tables configured to use/support Full Text Search -- an elderly feature of SQL Server that I have little experience with. If you are not using Full Text Search, I'm pretty sure contains will not work. A: Before CONTAINS will work against a column you need setup full text index. This is actually a different engine which runs as a separate service in SQL Server, so make sure it is installed an running. Once you're sure the component is installed (it may already be installed) You need to do the following: * *Create a Full-Text Catalogue *Create a Full-Text Index (you can have multiple of these in the same catalogue) against the tables/columns you want to be able to use full-text keywords *Run a Population which will crawl the index created & populate the catalogue (these are seperate files which SQL Server needs to maintain in addition to mdf/ldf ) There's an ok tutorial on how to do this by using SSMS in SQL Server 2008 by Pinal Dave on CodeProject. SQL Server 2014 should be very similar. You can also perform these steps with TSQL: * *CREATE FULLTEXT CATALOG *CREATE FULLTEXT INDEX *ALTER FULLTEXT INDEX
{ "language": "en", "url": "https://stackoverflow.com/questions/32972254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: LoginPage is the part of declarations of 2 modules ERROR Error: Uncaught (in promise): Error: Type LoginPage is part of the declarations of 2 modules: AppModule and LoginPageModule! Please consider moving LoginPage to a higher module that imports AppModule and LoginPageModule. You can also create a new NgModule that exports and includes LoginPage then import that NgModule in AppModule and LoginPageModule. Error: Type LoginPage is part of the declarations of 2 modules: AppModule and LoginPageModule! Please consider moving LoginPage to a higher module that imports AppModule and LoginPageModule. You can also create a new NgModule that exports and includes LoginPage then import that NgModule in AppModule and LoginPageModule. I am trying to build an ionic 4 application for login, everything works fine when i am running the home page of the application, but when i try to run my generated pages of login, there isn't the error in the file but the output page on the browser is blank, and when i check the console of the browser, the above error is occured.enter image description hereenter image description here A: This is an error because you use same declaration component in 2 modules AppModule and LoginPageModule. If you need to use 2 components in different modules you can try to use sharedModule where you can add your component and import sharedModule when you need it. A: You have declared LoginPage in both LoginPageModule and AppModule. Remove it from One module. A: Go in your app.module.ts file and remove LoginPage from the declarations A: Removed the LoginPage declaration from AppModule and got the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/59644188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: STL - Use member functions or functions in ? I thought of this problem due to some of the answers I got to the following problem suggesting that I could use vector<T>::assign or copy with a back_insert_iterator here. My problem is, what are the drawbacks and advantages of using one method over another? A: assign overwrites the content of the vector where as copy with back_insert_iterator does a push_back on the vector thus preseving its content. EDIT: If the question is generic (i.e. whether to use a member function defined in the container or an algorithm), I prefer to use the member function as it might have been optimized for the particular container compared to a generic algorithm. A: Complementing Naveen's answer, using std::copy() is also much more versatile, as this way you can easily write to any output iterator. This could be a stream or something entirely custom. A: In the general case, prefer member functions to functionally-equivalent algorithms. Scott Meyers discusses this in depth in Effective STL. A: In essence, they are the same. Vector's reallocation behavior (defined in terms of how it behaves with push_back) avoids too many reallocations by progressively using more memory. If you need identical code to work with multiple container types (i.e. you're writing a template), including those containers not in the stdlib, then generally prefer free functions. If you don't mind rewriting this code if/when container types change, then you can prematurely optimize if you like, or simply use whichever is more convenient. And just for completeness' sake, copy+back_inserter is equivalent to vector::insert at the end(), while vector::clear + copy+back_inserter is equivalent to vector::assign. A: Your question can be generalized as follows: When dealing with STL containers, should I prefer to use member functions or free-standing functions from <algorithm> when there are functional equivalents? Ask 10 programmers, and you'll get 12 responses. But they fall in to 2 main camps: 1) Prefer member functions. They are custom-designed for the container in question and more efficient than the <algorithm> equivalent. 2) Prefer free-standing functions. They are more generic and their use is more easily maintained. Ultimately, you have to decide for yourself. Any conclusion you come to after giving it some reasoned, researched thought is better than following anyone else's advice blindly. But if you just want to blindly follow someone's advice, here's mine: prefer the free-standing functions. Yes, they can be slower than the member functions. And "slow" is such a dirty word. But 9 times out 10 you just don't (or shouldn't) care how much more efficient one method is than the other. Most of the time when you need a collection, you're going to periodically add a few elements, do something, and then be done. Sometimes you need ultra-high performance lookup, insertion or removal, but not normally. So if you're going to come down one one side or the other with a "Prefer Method X" approach, it should be geared for the general case. And the approach that prefers the member methods seems to be slanted towards optimization -- and I call that a premature micro-optimization.
{ "language": "en", "url": "https://stackoverflow.com/questions/4152815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I create a function to mutate new columns with a variable name and "_pct"? Using mtcars as an example. I would like to write a function that creates a count and pct column such as below - library(tidyverse) mtcars %>% group_by(cyl) %>% summarise(count = n()) %>% ungroup() %>% mutate(cyl_pct = count/sum(count)) This produces the output - # A tibble: 3 x 3 cyl count mpg_pct <dbl> <int> <dbl> 1 4 11 0.344 2 6 7 0.219 3 8 14 0.438 However, I would like to create a function where I can specify the group_by column to be any column and the mutate column will be name the column name specified in the groub_by, and a _pct. So if I want to use disp, disp will be my group_by variable and the function will mutate a disp_pct column. A: Similar to akrun's answer, but using {{ instead of !!: foo = function(data, col) { data %>% group_by({{col}}) %>% summarize(count = n()) %>% ungroup %>% mutate( "{{col}}_pct" := count / sum(count) ) } foo(mtcars, cyl) # `summarise()` ungrouping output (override with `.groups` argument) # # A tibble: 3 x 3 # cyl count cyl_pct # <dbl> <int> <dbl> # 1 4 11 0.344 # 2 6 7 0.219 # 3 8 14 0.438 A: Assuming that the input is unquoted, convert to symbol with ensym, evaluate (!!) within group_by while converting the symbol into a string (as_string) and paste the prefix '_pct' for the new column name. In mutate we can use := along with !! to assign the column name from the object created ('colnm') library(stringr) library(dplyr) f1 <- function(dat, grp) { grp <- ensym(grp) colnm <- str_c(rlang::as_string(grp), '_pct') dat %>% group_by(!!grp) %>% summarise(count = n(), .groups = 'drop') %>% mutate(!! colnm := count/sum(count)) } -testing f1(mtcars, cyl) # A tibble: 3 x 3 # cyl count cyl_pct # <dbl> <int> <dbl> #1 4 11 0.344 #2 6 7 0.219 #3 8 14 0.438 A: This is probably no different than the one posted by my dear friend @akrun. However, in my version I used enquo function instead of ensym. There is actually a subtle difference between the two and I thought you might be interested to know: * *As per documentation of nse-defuse, ensym returns a raw expression whereas enquo returns a "quosure" which is in fact a "wrapper containing an expression and an environment". So we need one extra step to access the expression of quosure made by enquo. *In this case we use get_expr for our purpose. So here is just another version of writing this function that I thought might be of interest to whomever read this post in the future. library(dplyr) library(rlang) fn <- function(data, Var) { Var <- enquo(Var) colnm <- paste(get_expr(Var), "pct", sep = "_") data %>% group_by(!!Var) %>% summarise(count = n()) %>% ungroup() %>% mutate(!! colnm := count/sum(count)) } fn(mtcars, cyl) # A tibble: 3 x 3 cyl count cyl_pct <dbl> <int> <dbl> 1 4 11 0.344 2 6 7 0.219 3 8 14 0.438
{ "language": "en", "url": "https://stackoverflow.com/questions/67695176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: AWS ECS Fargate Target Group Failing HealthChecks The SpringBoot application is running as an ECS Task in a ECS Service of an AWS Fargate Cluster. The ECS Service is LoadBalanced as such the Tasks spawned by the Services are automatically registered to a target group. I am able to call the Health endpoint via API Gateway => VPC Link => Network ELB => Application ELB => ECS Task, as shown below: However, the HealthChecks seem to be failing and as such, the tasks are being deregistered continously resulting in totally unusable setup. I have made sure to configure the HealthCheck of the Target Group point towards the right endpoint URL, as shown below: I also made sure that the Security Group that the Fargate Tasks belong in allows traffics from the Application Load Balancer, as shown below: But somehow, the HealthChecks kept failing and the tasks are being deregistered, and I'm very confused! Your help is much appreciated! A: The problem actually is with the Health Check Intervals (30 seconds) and Threshold (2 checks) which is too frequent when the Task is just starting up and is unable to respond to the HTTP request. So, I increased the interval and the threshold, and everything is fine now!
{ "language": "en", "url": "https://stackoverflow.com/questions/66643785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Query / Ping a website to display website online status Alright so I'm trying to figure out a way to query a websites online status so that it displays on my main hub website the online status of that particular website. For example, I'm looking for it to look like: Websites: www.google.com - ONLINE or OFFLINE ... ... The "..." would be the other sites of course and after the "-" would either say Online or Offine... I'm googled this but can't find anything specific on how to do this with websites, just Minecraft servers A: I found several sites explaining how to do this https://dl.dropboxusercontent.com/u/98433173/links.html
{ "language": "en", "url": "https://stackoverflow.com/questions/22420174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to get intersection of two lists in terraform? I have two lists in terraform and want to get the intersection of these lists. For example, list1 = ["a", "b", "c"] lists2 = ["b", "c", "d"] I am looking to get output as ["b", "c"] using built-in terraform functions. A: You are looking for something like this output my_intersection { value = setintersection( toset(var.list1), toset(var.list2) ) }
{ "language": "en", "url": "https://stackoverflow.com/questions/54117373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: last image in Camera Roll not shown when method called outside viewDidLoad I'm using a code snippet to get the last image from Camera Roll. I've made a method and I'm calling it in viewDidLoad method. I'm using this functionality to share the last image through Social Framework when I hit a button. That way everything works fine. The problem is when I try to replace my method from viewDidLoad and put it inside IBAction, the picture isn't rendered in social popup. Debugging shows my method returns what it should, an image, and it is fired on the touch of a button. Due to the fact there will be a change in the latest image while this viewController is loaded, calling it from viewDidLoad is not an option. Here is the code. Method: - (void) LastPic { ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) { [group setAssetsFilter:[ALAssetsFilter allPhotos]]; [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) { if (alAsset) { ALAssetRepresentation *representation = [alAsset defaultRepresentation]; UIImage *latestPhoto = [UIImage imageWithCGImage:[representation fullScreenImage]]; *stop = YES; *innerStop = YES; self.imageToShare = latestPhoto; } }]; } failureBlock: ^(NSError *error) { NSLog(@"No groups"); }];} Action: - (IBAction)ShareT:(id)sender { [self LastPic]; //when in viewDidLoad everything kk if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]){ self.slComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter]; [self.slComposeViewController addImage:self.imageToShare]; [self presentViewController:self.slComposeViewController animated:YES completion:NULL]; } else {}} I have all the necessary frameworks enabled and my h file looks like this. The same happens when I try to modify the code to pass the image as NSData. @property (strong, nonatomic) UIImage *imageToShare; Thanks! A: It happens because ALAssets is fetching in block. This means, you call Share controller when image is not fetched yet. I propose you add some progress hud like this with 2-3 seconds delay. This will solve your problem and it'll be friendly for the user. To check if it really works, test the code below: - (void)fetchLastPhoto { __block UIImage *latestPhoto; ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) { [group setAssetsFilter:[ALAssetsFilter allPhotos]]; [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) { if (alAsset) { ALAssetRepresentation *representation = [alAsset defaultRepresentation]; latestPhoto = [UIImage imageWithCGImage:[representation fullScreenImage]]; _imageToShare = latestPhoto; *stop = YES; *innerStop = YES; } NSLog(@"Image fetched"); }]; } failureBlock: ^(NSError *error) { NSLog(@"No groups"); }]; } - (IBAction)buttonShare:(id)sender { [self fetchLastPhoto]; [self performSelector:@selector(openShareController) withObject:nil afterDelay:3.0f]; } -(void)openShareController { NSLog(@"Share controller called"); SLComposeViewController *slComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter]; [slComposeViewController addImage:self.imageToShare]; [self presentViewController:slComposeViewController animated:YES completion:NULL]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/24993488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: libgdx and drwaing app I am looking at using LibGdx to write a simple drawing app. The user gestures would be used for drawing rectangles and other shapes. Is it a good idea to use Libgdx for such an app? If yes could someone point to an example which shows how to draw shapes using libgdx and gestures. A: There is an example in the LibGDX tests that does drawing. All of the source code for LibGDX including the tests can be found here: http://github.com/libgdx/libgdx As for the shapes, there is a shape renderer, I have never used it, but you could maybe use it for a drawing game. Best of luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/11405859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Psychopy gives the ffmpeg error and does not play the videos I want to create an experiment with Psychopy in which I will present randomly video that participant will have to evaluate. I have created a routine with my MovieStim and my Rating response and a Loop with my conditions file (in which are my video files videoname.wmv). All my videos are in the same folder as my experiment. I have specified the MovieStim with a variable refering to my Loop's column ($Stimulus). But when I run the experiment I have this message. Running: E:\Thèse ESPRIT\Approach_Aversion\Experience_AA\Approach_Aversion_lastrun.py pyo version 0.8.0 (uses single precision) WARNING:root:Warning: could not find imageio's ffmpeg executable: [Error 5] Accès refus: 'C:\\Program Files (x86)\\PsychoPy2\\lib\\site-packages\\imageio\\resources\\ffmpeg\\ffmpeg.win32.exe' Traceback (most recent call last): File "E:\Thèse ESPRIT\Approach_Aversion\Experience_AA\Approach_Aversion_lastrun.py", line 105, in <module> depth=0.0, File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\psychopy-1.84.2-py2.7.egg\psychopy\contrib\lazy_import.py", line 120, in __call__ return obj(*args, **kwargs) File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\psychopy-1.84.2-py2.7.egg\psychopy\visual\movie3.py", line 124, in __init__ self.loadMovie(self.filename) File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\psychopy-1.84.2-py2.7.egg\psychopy\visual\movie3.py", line 170, in loadMovie self._mov = VideoFileClip(filename, audio=(1 - self.noAudio)) File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 55, in __init__ reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt) File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 32, in __init__ infos = ffmpeg_parse_infos(filename, print_infos, check_duration) File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 237, in ffmpeg_parse_infos proc = sp.Popen(cmd, **popen_params) File "C:\Program Files (x86)\PsychoPy2\lib\subprocess.py", line 710, in __init__ errread, errwrite) File "C:\Program Files (x86)\PsychoPy2\lib\subprocess.py", line 958, in _execute_child startupinfo) WindowsError: [Error 2] Le fichier spécifié est introuvable It seems to be something wrong with the ffmpeg executable but I don't understand what. Do you have any idea ? Thank you very much fo advance ! Have a nice day. Ivane
{ "language": "en", "url": "https://stackoverflow.com/questions/45738517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: connect to Oracle11g DB from pypyodbc Am relatively beginner level python dev here. I am just not able to connect to Oracle from pypyodbc import pypyodbc as pyodbc connstr = 'DSN = IDW;PWD=XXXXX' connection = pyodbc.connect(connstr) errs out with the below: File "C:\Users\PRXM\Desktop\JobReadings\PythonIDE\eclipse-standard-luna-R-win32-x86_64\eclipse\plugins\org.python.pydev_4.1.0.201505270003\pysrc\pydevd.py", line 1709, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Users\PRXM\workspace\tests\gettingstarted.py", line 10, in <module> connection = pyodbc.connect(connstr) File "C:\Users\PRXM\Desktop\JobReadings\PythonIDE\Anaconda_64\lib\site-packages\pypyodbc.py", line 2434, in __init__ self.connect(connectString, autocommit, ansi, timeout, unicode_results, readonly) File "C:\Users\PRXM\Desktop\JobReadings\PythonIDE\Anaconda_64\lib\site-packages\pypyodbc.py", line 2483, in connect check_success(self, ret) File "C:\Users\PRXM\Desktop\JobReadings\PythonIDE\Anaconda_64\lib\site-packages\pypyodbc.py", line 988, in check_success ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi) File "C:\Users\PRXM\Desktop\JobReadings\PythonIDE\Anaconda_64\lib\site-packages\pypyodbc.py", line 964, in ctrl_err raise Error(state,err_text) pypyodbc.Error: (u'IM002', u'[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified') A: Try this: Connection_String = 'Driver={Oracle in OraClient11g_home1};DBQ=MyDB;Uid=MyUser;Pwd=MyPassword;'
{ "language": "en", "url": "https://stackoverflow.com/questions/30718004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nested Routes and Parameters for Rails URLs (Best Practice) I have a decent understanding of RESTful urls and all the theory behind not nesting urls, but I'm still not quite sure how this looks in an enterprise application, like something like Amazon, StackOverflow, or Google... Google has urls like this: * *http://code.google.com/apis/ajax/ *http://code.google.com/apis/maps/documentation/staticmaps/ *https://www.google.com/calendar/render?tab=mc Amazon like this: * *http://www.amazon.com/books-used-books-textbooks/b/ref=sa_menu_bo0?ie=UTF8&node=283155&pf_rd_p=328655101&pf_rd_s=left-nav-1&pf_rd_t=101&pf_rd_i=507846&pf_rd_m=ATVPDKIKX0DER&pf_rd_r=1PK4ZKN4YWJJ9B86ANC9 *http://www.amazon.com/Ruby-Programming-Language-David-Flanagan/dp/0596516177/ref=sr_1_1?ie=UTF8&s=books&qid=1258755625&sr=1-1 And StackOverflow like this: * *https://stackoverflow.com/users/169992/viatropos *https://stackoverflow.com/questions/tagged/html *https://stackoverflow.com/questions/tagged?tagnames=html&sort=newest&pagesize=15 So my question is, what is best practice in terms of creating urls for systems like these? When do you start storing parameters in the url, when don't you? These big companies don't seem to be following the rules so hotly debated in the ruby community (that you should almost never nest URLs for example), so I'm wondering how you go about implementing your own urls in larger scale projects because it seems like the idea of not nesting urls breaks down at anything larger than a blog. Any tips? A: Don't get too bogged down by the "rules" in the Ruby community. The idea is that you shouldn't go overboard when nesting URLs, but when they're appropriate they're built into the Rails framework for a reason: use them. If a resource always falls within another resource, nest it. Nothing wrong with that. Going deeper than one can sometimes be a bit of a pain because your route paths will be very long and can get a bit confusing. Also, don't confuse nesting with namespacing. Just because you see example.com/admin/products/1234/edit does not mean that there's any nesting happening. Routing can make things look nested when they're actually not at the code level. I'm personally a big fan of nesting and use it often (just one level -- occasionally two) in my applications. Also, adding permalink style URLs that use words rather than just IDs are more visually appealing and they can help with SEO, whether or not they're nested. A: I believe the argument for or against REST and/or nesting in your routes has much to do with how you want to expose your API. If you do not care to ever expose an API for your app publicly, there is an argument to be made that strict adherence to RESTful design is a waste of time, particularly if you disagree with the reasoning behind REST. Your choice. I find that thinking about how a client (other than a browser) might access information from you app helps in the design process. One of the greatest advantages of thinking about your app's design from an API perspective is that you tend to eliminate unnecessary complexity. To me this is the root of the cautions you hear in the Rails community surrounding nested routes. I would take it as an indication that things are getting a bit complicated and it might be time to step back and rethink the approach. Systems "larger than a blog" do not have to be inherently complex. Some parts might be but you also may be surprised when you approach the design from a different perspective. In short, consider some of the dogma you might hear from certain parts of the community as guides and signals that you may want to think more deeply about your design. Strict REST is simply another way to think about how you are structuring your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/1773633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Apache Axis JAX-RPC over IBM MQ - IllegalArgumentException: noCFName I'm trying to create a JAX-RPC client with JMS / IBM MQ transport. I'm using the following guide as reference: https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_7.5.0/com.ibm.mq.dev.doc/q033020_.htm I have received the wsdl from an external party. It contains only http bindings, but we are required to use JMS/IBM MQ transport. The endpoint is .NET and IBM MQ 8. I use Axis 1.4 to generate classes from wsdl. When I try to test the web service call with the endpoint URL provided by external party: public static void main(String[] args) throws MalformedURLException, ServiceException, RemoteException { com.ibm.mq.soap.Register.extension(); Wf1AGwImplLocator locator = new Wf1AGwImplLocator(); IWf1AGw impl = locator.getBasicHttpBinding_IWf1aGw( new URL("jms:/queue?destination=QG.WF1AGW.REQ&amp;connectionFactory=clientChannel(WIP.SVRCONN)clientConnection(<externalIP1>(1414), <externalIP2>(1414))&amp;initialContextFactory=com.ibm.mq.jms.Nojndi&amp;replyDestination=QP.ABBSVC.WF1AGW.RESP&amp;timeToLive=30000&amp;persistence=1")); impl.dispatch("", "", "", "", "",false, "", "", 1, Calendar.getInstance(), false, "", ""); } I get the following error: cannotConnect; nested exception is: java.lang.IllegalArgumentException: noCFName at org.apache.axis.transport.jms.JMSConnectorManager.getConnector(JMSConnectorManager.java:122) at org.apache.axis.transport.jms.JMSTransport.setupMessageContextImpl(JMSTransport.java:163) at org.apache.axis.client.Transport.setupMessageContext(Transport.java:46) at org.apache.axis.client.Call.invoke(Call.java:2738) at org.apache.axis.client.Call.invoke(Call.java:2443) at org.apache.axis.client.Call.invoke(Call.java:2366) at org.apache.axis.client.Call.invoke(Call.java:1812) at com.test.BasicHttpBinding_IWf1AGwStub.dispatch(BasicHttpBinding_IWf1AGwStub.java:201) at com.test.Test.main(Test.java:19) Caused by: java.lang.IllegalArgumentException: noCFName at org.apache.axis.components.jms.JNDIVendorAdapter.getConnectionFactory(JNDIVendorAdapter.java:71) at org.apache.axis.components.jms.JNDIVendorAdapter.getQueueConnectionFactory(JNDIVendorAdapter.java:55) at org.apache.axis.transport.jms.JMSConnectorFactory.createConnector(JMSConnectorFactory.java:227) at org.apache.axis.transport.jms.JMSConnectorFactory.createClientConnector(JMSConnectorFactory.java:178) at org.apache.axis.transport.jms.JMSConnectorManager.getConnector(JMSConnectorManager.java:107) The error text suggests that I need to name the QCF even though this is a nojndi QCF? How can I solve this? A: Needed to add a client-config.wsdd to my project and add the following line: <transport name="jms" pivot="java:com.ibm.mq.soap.transport.jms.WMQSender"/> To override the client-config in axis.jar. I thought this was already done in this call: com.ibm.mq.soap.Register.extension(); It still complained about the connection factory. Apparently it didn't understand the URL and I had to replace all &amp; with & and remove the ports(it defaults to 1414 anyway..) EDIT: The IllegalArgumentException: noCFName occurs because of the ORDER of the external libraries. The jars in MQ_INSTALLATION_PATH/java/lib must be compiled before the jars in MQ_INSTALLATION_PATH/java/lib/soap.
{ "language": "en", "url": "https://stackoverflow.com/questions/46522307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android - Unable to create new Intent which triggered from OptionMenu I am new to Android development and currently stuck when trying to develop a simple app based on This Tutorial What i want is basically start a new intent when user click on a button via the setting menu (of the said app). This are some segment of my code: MainActivity.java Here i am getting an error with SET_TIME_REQUEST_ID which is a constant that has not been declared anywhere in my code. Should i declare it, i am not sure what is the type of the constant and what value should i assign it with. *** REST OF THE CODE **** private void setTime() { Intent i = new Intent(getBaseContext(), CountdownSetTime.class); startActivityForResult(i, SET_TIME_REQUEST_ID); } *** REST OF THE CODE *** CountdownSetTime.java The error i am getting with this part are; context and secondsSet cannot be resolved to any variable. Again, i am not sure what to do with this. Should i declare a variable called secondsSet? If yes, what is the type? *** REST OF THE CODE *** public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.set_time); context = this.getApplicationContext(); // ERROR HERE. Spinner spinner = (Spinner) findViewById(R.id.spinner); ArrayList<Integer> spinnerList = new ArrayList<Integer>(); for (int i = MIN; i <= MAX; i++) { spinnerList.add(i); } ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(context, android.R.layout.simple_spinner_item, spinnerList); adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { secondsSet = (Integer)parent.getItemAtPosition(pos); // ERROR HERE } public void onNothingSelected(AdapterView<?> parent) { // Do nothing. } }); } *** REST OF THE CODE *** manifest.xml I am absolutely clueless with this. I am not sure how could i register my new intent. <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.gelliesmedia.countdown.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.gelliesmedia.countdown.CountdownSetTime" android:label="@string/app_name" android:parentActivityName="com.gelliesmedia.countdown.MainActivity" > <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.gelliesmedia.countdown.MainActivity" /> </activity> </application> Could anyone point me to the right direction? A: I have read the tutorial you give as a link. That tutorial doesn't give the full code. According to what I see the variables you mention must be defined. For SET_TIME_REQUEST_ID usually you add this at the beginning with something like that private static final int SET_TIME_REQUEST_ID = 1; because onActivityResult(int, int, Intent) That ID is your internal identification. I put 1 but you can put any number. It is an ID for you so that when the activity closes you can fetch the result. So yes you have to define it. Same for secondsSet. The type seems to be Integer because the parent.getItemAtPostion is cast to Integer. It is used but not defined. Seems to me to be a global variable. The ones you put at the top of your class. So yes you have to define it also :-) And finally it is the same for context. It is used but not declared. It seems the tutorial you use declares all these variable globally. EDIT The manifest file tells the system that an intent (activity) exist. You should have some thing like that <activity android:name="com.gelliesmedia.countdown.CountdownSetTime"> </activity>
{ "language": "en", "url": "https://stackoverflow.com/questions/18267116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: setting f:validatelength dynamically does not work When I use a bean to set the min and max values on f:validatelength it simply does not work. It breaks the functionality in the form so it can't be submitted... When I outputtext the values they do come out as legit numbers and hardcoding those numbers work fine. My guess it that it somehow lacks the required connection to beans at that time in the lifecycle or something? (I'm pretty much a beginner). Example below is example of what I want to do <h:inputSecret id="password" value="#{userBean.user.password}"> <f:validateLength minimum="#{myBean.minSize}" maximum="#{myBean.maxSize}" /> </h:inputSecret> <h:message for="password" /> I tried using < a4j:keepAlive > on the bean but I couldn't get that to work. I am using JSF 1.2 with Richfaces 3.3.3 and Seam 2. Hopefully someone has a clue here. And a good way to achieve this using another tag then that's fine as well! Thanks for reading. A: Is the el expression evaluated to integer type? A: I have no idea, but you can try a couple of these variations <h:inputSecret id="password" value="#{userBean.user.password}" maxlength="#{myBean.maxSize}"> <f:validateLength minimum="#{myBean.minSize}"/> </h:inputSecret> <h:message for="password" /> <h:inputSecret id="password" value="#{userBean.user.password}" maxlength="#{myBean.maxSize}"> <f:validator validatorId="javax.faces.validator.LengthValidator"> <f:attribute name="minimum" value="#{myBean.minSize}"/> </f:validator> </h:inputSecret> <h:message for="password" />
{ "language": "en", "url": "https://stackoverflow.com/questions/8596949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Consumer poll kafka streaming https://kafka.apache.org/0101/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html#poll(long) I would like to use the poll based interface (above) to pick messages from kafka streaming (see link below). How can i set the timeout property when i use the direct stream approach from Spark. https://spark.apache.org/docs/2.1.0/structured-streaming-kafka-integration.html Any advice on handling this type of interaction is welcome :) thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/46324958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing prompts for loop I'm doing an exercise where I have to ask the user for 5 integer inputs and then print the total of the 5 numbers. I have to do this using a for loop. I know how to do this with a while loop but we're currently learning about for loops. I have written the following code: num = 0 count = 0 for i in range(num): while count < 5: num = getInteger("Please enter a number: ", format(num + 1)) count += 1 print(num) total = num + num print(total) Though I get so many errors because frankly, I don't know what I'm doing. A: Try this: total=0 for i in range(5): num = int(input(f"Please enter number {i+1}: ")) total+=num print(total)
{ "language": "en", "url": "https://stackoverflow.com/questions/65446719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to name Node js workers Simple question that I can't find a solution to - is there a way to give names to workers that I initialize in my Node.js app? My target is being able to know in which worker I'm looking while debugging a Node.js application in VS Code (by seeing the worker name instead of `Worker ${X}`. A: Alas, no: https://github.com/nodejs/node/blob/56679eb53044b03e4da0f7420774d54f0c550eec/src/inspector/worker_inspector.cc#L28 But you could always try to convince them and submit a PR because the feature appears useful
{ "language": "en", "url": "https://stackoverflow.com/questions/70756313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can TNEF be avoided using MAPI? I am using this code to send emails through MAPI using Delphi. A few users who use Microsoft mailing software report that the receipants receive emails with an attachment WinMail.dat. I know that this is an issue with Microsoft Exchange/Outlook and can be corrected by disabling RTF/TNEF. (I don't know for sure because I do not use Microsoft mailing software). My question is, if I can tell the mailing software to not use TNEF using the MAPI. function SendEMailUsingMAPI(const Subject, Body, FileName, SenderName, SenderEMail, RecipientName, RecipientEMail: string): Integer; var Message: TMapiMessage; lpSender, lpRecipient: TMapiRecipDesc; FileAttach: TMapiFileDesc; SM: TFNMapiSendMail; MAPIModule: HModule; FileType: TMapiFileTagExt; begin // Source: http://www.stackoverflow.com/questions/1234623/how-to-send-a-mapi-email-with-an-attachment-to-a-fax-recipient // Modified FillChar(Message,SizeOf(Message),0); if (Subject <> '') then begin Message.lpszSubject := PChar(Subject); end; if (Body <> '') then begin Message.lpszNoteText := PChar(Body); end; if (SenderEmail <> '') then begin lpSender.ulRecipClass := MAPI_ORIG; if (SenderName = '') then begin lpSender.lpszName := PChar(SenderEMail); end else begin lpSender.lpszName := PChar(SenderName); end; lpSender.lpszAddress := PChar('smtp:'+SenderEmail); lpSender.ulReserved := 0; lpSender.ulEIDSize := 0; lpSender.lpEntryID := nil; Message.lpOriginator := @lpSender; end; if (RecipientEmail <> '') then begin lpRecipient.ulRecipClass := MAPI_TO; if (RecipientName = '') then begin lpRecipient.lpszName := PChar(RecipientEMail); end else begin lpRecipient.lpszName := PChar(RecipientName); end; lpRecipient.lpszAddress := PChar('smtp:'+RecipientEmail); lpRecipient.ulReserved := 0; lpRecipient.ulEIDSize := 0; lpRecipient.lpEntryID := nil; Message.nRecipCount := 1; Message.lpRecips := @lpRecipient; end else begin Message.lpRecips := nil; end; if (FileName = '') then begin Message.nFileCount := 0; Message.lpFiles := nil; end else begin FillChar(FileAttach,SizeOf(FileAttach),0); FileAttach.nPosition := Cardinal($FFFFFFFF); FileAttach.lpszPathName := PChar(FileName); FileType.ulReserved := 0; FileType.cbEncoding := 0; FileType.cbTag := 0; FileType.lpTag := nil; FileType.lpEncoding := nil; FileAttach.lpFileType := @FileType; Message.nFileCount := 1; Message.lpFiles := @FileAttach; end; MAPIModule := LoadLibrary(PChar(MAPIDLL)); if MAPIModule = 0 then begin Result := -1; end else begin try @SM := GetProcAddress(MAPIModule,'MAPISendMail'); if @SM <> nil then begin Result := SM(0,Application.Handle,Message, MAPI_DIALOG or MAPI_LOGON_UI,0); end else begin Result := 1; end; finally FreeLibrary(MAPIModule); end; end; if Result <> 0 then begin raise Exception.CreateFmt('Error sending eMail (%d)', [Result]); end; end; A: Not in Simple MAPI. If you were using Outlook Object Model or Extended MAPI, you could set a special MAPI property on the message before sending it to disable TNEF format.
{ "language": "en", "url": "https://stackoverflow.com/questions/49053393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BeginInvoke vs Invoke in EventHandler with no code afterwards What exactly is the difference between these two snippets: A: MyDataGrid.IsKeyboardFocusWithinChanged += (sender, e) => { if ((bool)e.NewValue == true) { Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => { // do something })); } }; B: MyDataGrid.IsKeyboardFocusWithinChanged += (sender, e) => { if ((bool)e.NewValue == true) { Dispatcher.Invoke(DispatcherPriority.Loaded, new Action(() => { // do something })); } }; I thought the only difference between Invoke and BeginInvoke is that the first one waits for the task to be finished while the latter retuns instantly. Since the Dispatcher call is the only thing that happens in the EventHandler, I assumed that using Invoke would have the exact same effect as using BeginInvoke in this case. However I have a working example where this is clearly not the case. Take a look for yourself: MainWindow.xaml <Window x:Class="DataGridFocusTest.MainWindow" x:Name="MyWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DataGridFocusTest" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <DockPanel> <TextBox DockPanel.Dock="Top"></TextBox> <DataGrid x:Name="MyDataGrid" DockPanel.Dock="Top" SelectionUnit="FullRow" ItemsSource="{Binding SomeNumbers, ElementName=MyWindow}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Data" Binding="{Binding Data}" IsReadOnly="True" /> <DataGridTemplateColumn Header="CheckBox"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </DockPanel> </Window> MainWindow.xaml.cs using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace DataGridFocusTest { public class MyDataClass { public string Data { get; set; } } public partial class MainWindow : Window { public IList<MyDataClass> SomeNumbers { get { Random rnd = new Random(); List<MyDataClass> list = new List<MyDataClass>(); for (int i = 0; i < 100; i++) { list.Add(new MyDataClass() { Data = rnd.Next(1000).ToString() }); } return list; } } public MainWindow() { InitializeComponent(); MyDataGrid.IsKeyboardFocusWithinChanged += (sender, e) => { if ((bool)e.NewValue == true) { // whenever MyDataGrid gets KeyboardFocus set focus to // the selected item // this has to be delayed to prevent some weird mouse interaction Dispatcher.Invoke(DispatcherPriority.Loaded, new Action(() => { if (MyDataGrid.IsKeyboardFocusWithin && MyDataGrid.SelectedItem != null) { MyDataGrid.UpdateLayout(); var cellcontent = MyDataGrid.Columns[1].GetCellContent(MyDataGrid.SelectedItem); var cell = cellcontent?.Parent as DataGridCell; if (cell != null) { cell.Focus(); } } })); } }; } } } What we have here is a DataGrid which rows include a CheckBox. It implements two specific behaviors: * *When the DataGrid gets keyboard focus it will focus it's selected row (which for some reason is not the default behavior). *You can change the state of a CheckBox with a single click even when the DataGrid is not focused. This works already. With the assumption at the top of the post, I thought that it would not matter whether I use Invoke or BeginInvoke. If you change the code to BeginInvoke however, for some reason the 2cnd behavior (one-click-checkbox-selection) does not work anymore. I don't look for a solution (the solution is just using Invoke) but rather want to know why Invoke and BeginInvoke behave so differently in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/40343545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cut string in PHP at nth-from-end occurrence of character I have a string which can be written in a number of different ways, it will always follow the same pattern but the length of it can differ. this/is/the/path/to/my/fileA.php this/could/also/be/the/path/to/my/fileB.php another/example/of/a/long/address/which/is/a/path/to/my/fileC.php What I am trying to do is cut the string so that I am left with path/to/my/file.php I have some code which I got from this page and modified it to the following $max = strlen($full_path); $n = 0; for($j=0;$j<$max;$j++){ if($full_path[$j]=='/'){ $n++; if($n>=3){ break 1; } } } $path = substr($full_path,$j+1,$max); Which basically cuts it at the 3rd instance of the '/' character, and gives me what is left. This was fine when I was working in one environment, but when I migrated it to a different server, the path would be longer, and so the cut would give me too long an address. I thought that rather than changing the hard coded integer value for each instance, it would work better if I had it cut the string at the 4th from last instance, as I always want to keep the last 4 'slashes' of information Many thanks EDIT - final code solution $exploded_name = explode('/', $full_path); $exploded_trimmed = array_slice($exploded_name, -4); $imploded_name = implode('/', $exploded_trimmed); A: just use explode with your string and if pattern is always the same then get last element of the array and your work is done $pizza = "piece1/piece2/piece3/piece4/piece5/piece6"; $pieces = explode("/", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 Then reverse your array get first four elements of array and combine them using "implode" to get desired string A: This function below can work like a substr start from nth occurrence function substr_after_nth($str, $needle, $key) { $array = explode($needle, $str); $temp = array(); for ($i = $key; $i < count($array); $i++) { $temp[] = $array[$i]; } return implode($needle, $temp); } Example $str = "hello-world-how-are-you-doing"; substr after 4th occurrence of "-" to get "you-doing" call the function above as echo substr_after_nth($str, "-", 4); it will result as you-doing
{ "language": "en", "url": "https://stackoverflow.com/questions/16234860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL table with composite primary key LIMIT 1 is very slow while Limit 2 is fast I have ProductInfo table with following indexes - Primary: ProductCode, Model, Added_Date, id Index: id The composite primary key are the columns I use in the following query SELECT * FROM ProductInfo WHERE ProductCode='45678' AND Model='PQA-1' AND (Added_Date >='2021-08-01 00:00:00' AND Added_Date <='2021-08-14 23:59:59') ORDER BY Added_Date ASC; This query works pretty fine Problem The following query is fast select * from ProductInfo WHERE ProductCode="45678" order by id desc limit 1; Here is the explain But the following query is very very slow. Please note that query is same but just ProductCode is different select * from ProductInfo WHERE ProductCode="78342" order by id desc limit 1; Here is the explain. However, same query with Limit 2 is fast select * from ProductInfo WHERE ProductCode="78342" order by id desc limit 2; Here is the explain What is the cause? Is my indexing correct? What will be the solution? Thanks A: The first query benefits from this index: PRIMARY KEY(ProductCode, Model, Added_Date) All the other queries could not fully benefit from either of your indexes. The Optimizer guessed at one index in one case; the other index in the other. This would work well for both cases: INDEX(ProductCode, Id) One reason for the timing differences is the distribution of data in the table. Your examples may not show the same timings if you change the 78342 to some other value. The new index I recommend will make those queries "fast" regardless of the ProductCode searched on. And "Rows" will say "1" or "2" instead of about "25000". It sounds like there are about 25K rows with ProductCode = 78342.
{ "language": "en", "url": "https://stackoverflow.com/questions/68792742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: docker: SSH access directly into container Up to now we use several linux users: * *system_foo@server *system_bar@server *... We want to put the system users into docker container. * *linux user system_foo --> container system_foo The changes inside the servers are not problem, but remote systems use these users to send us data. We need to make ssh system_foo@server work. The remote systems can't be changed. I would be very easy if there would be just one system per linux operating system (pass port 22 to the container). But there are several. How can we change from the old scheme to docker containers and keep the service ssh system_foo@server available without changes at the remote site? Please leave a comment if you don't understand the question. Thank you. A: Let's remember however that having ssh support in a container is typically an anti-pattern (unless it's your container only 'concern' but then what would be the point of being able to ssh in. Refer to http://techblog.constantcontact.com/devops/a-tale-of-three-docker-anti-patterns/ for information about that anti-pattern A: nsenter could work for you. First ssh to the host and then nsenter to the container. PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)` nsenter --target $PID --mount --uts --ipc --net --pid source http://jpetazzo.github.io/2014/06/23/docker-ssh-considered-evil/ A: Judging by the comments, you might be looking for a solution like dockersh. dockersh is used as a login shell, and lets you place every user that logins to your instance into an isolated container. This probably won't let you use sftp though. Note that dockersh includes security warnings in their README, which you'll certainly want to review: WARNING: Whilst this project tries to make users inside containers have lowered privileges and drops capabilities to limit users ability to escalate their privilege level, it is not certain to be completely secure. Notably when Docker adds user namespace support, this can be used to further lock down privileges. A: Some months ago, I helped my like this. It's not nice, but works. But pub-key auth needs to be used. Script which gets called via command in .ssh/authorized_keys #!/usr/bin/python import os import sys import subprocess cmd=['ssh', 'user@localhost:2222'] if not 'SSH_ORIGINAL_COMMAND' in os.environ: cmd.extend(sys.argv[1:]) else: cmd.append(os.environ['SSH_ORIGINAL_COMMAND']) sys.exit(subprocess.call(cmd)) file system_foo@server: .ssh/authorized_keys command="/home/modwork/bin/ssh-wrapper.py" ssh-rsa AAAAB3NzaC1yc2EAAAAB... If the remote system does ssh system_foo@server the SSH-Daemon at server executes the comand given in .ssh/authorized_keys. This command does a ssh to a different ssh-daemon. In the docker container, there needs to run ssh-daemon which listens on port 2222.
{ "language": "en", "url": "https://stackoverflow.com/questions/25783324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: XSS Protection on Yii I need to protect my web application against xss attacks via URL. what is the best way to do this? the application is huge, so I can not edit each of the actions, need something general. Examples: * *http://example.com/[anyproductpage.html]?source=alert('Xss') *http://example.com/catalog/?baseUrl=alert('Xss')&q=1 *http://example.com/catalog/productimagezoom?index=alert('Xss') A: If you aim to manipulate your actions before handle them you can use beforeAction in your controller/component, with something like this: protected function beforeAction($action) { #check a preg_match on a url sanitization pattern, like "[^-A-Za-z0-9+&@#/%?=~_|!:,.;\(\)]", for instance return parent::beforeAction($action); } A: This articles shows how you can make your application secure with SQL Injections, XSS Attacks and CSRF. Hope it helps you. A: Firstly, you can use regular expressions to validate your inputs, you can generalize your inputs in some regular expresions, something like this: $num = $_GET["index"]; if (preg_match("^\d{2}$", $num)) { //allowed } else { //not allowed } Also you can create a white list or black list, if your inputs can be grouped into what is allowed in your application, use a white list, otherwise use a black list. This lists can be sotored in your database or files, something you can easily upgrade without affecting your application. You just have to compare your inputs with that list before proccesing your inputs. My last recommendation is encoding, you should encode your inputs and outputs, because your data from database can contain malicious code, maybe someone put it by mistake or mischief, always think in all possibilities. For this case, I remember the functions htmlspecialchars and utf8_encode, I think you should the first function, also you can analyze your inputs and build your own encoding function. I share the following links: * *http://php.net/manual/es/function.preg-match.php *http://php.net/manual/es/function.utf8-encode.php *http://php.net/manual/es/function.htmlspecialchars.php *https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet I hope this information helps you. Good Luck. A: for all actions in same just add a event handle to onBeginRequest: $this->attachEventHandler('onBeginRequest', [$this, 'purifyParams']); public function purifyParams($event) { $userAgent = $this->getRequest()->getUserAgent(); $isIE = preg_match('/(msie)[ \/]([\w.]+)/i', $userAgent, $version); if (!empty($isIE) && (int) $version[2] < 11) { $purifier = new CHtmlPurifier(); $_GET = array_map(function ($param) use ($purifier) { return $purifier->purify($param); }, $_GET); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/29821193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is the Layout style being applied to all of my JPanels? I am giving myself a crash course on re-learning Java. I am writing a very simple program that simply changes the place of the button when you click it to a random panel. There is no real problem, I pretty much finished the program that I wanted. However, I was wondering why is it that when I apply the Layout Style to the first panel (buttonPanel1), it is automatically applied to every panel? /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package buttonswitch; import javax.swing.*; import java.awt.*; import javax.swing.border.*; import java.awt.event.*; import java.util.*; /** * * @author Supreme Lenova */ import java.util.Random; public class ButtonWindow extends JFrame{ private JPanel buttonPanel1; private JPanel buttonPanel2; private JPanel buttonPanel3; private JPanel buttonPanel4; private JButton Button; private Border raisedbevel, loweredbevel; private Border compound; public ButtonWindow(){ setTitle("Button Game"); setLocation(600,50); setDefaultCloseOperation(EXIT_ON_CLOSE); GridLayout grid = new GridLayout(2,2); setLayout(grid); raisedbevel = BorderFactory.createRaisedBevelBorder(); loweredbevel = BorderFactory.createLoweredBevelBorder(); compound = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel); buildPanels(); Button = new JButton("Click!"); Button.setAlignmentX(Component.CENTER_ALIGNMENT); Button.addActionListener(new ButtonListener()); buttonPanel1.add(Button); buttonPanel1.add(Box.createVerticalGlue()); setSize(300,300); setVisible(true); } private void buildPanels(){ buttonPanel1 = new JPanel(); buttonPanel2 = new JPanel(); buttonPanel3 = new JPanel(); buttonPanel4 = new JPanel(); buttonPanel1.setLayout(new BoxLayout(buttonPanel1, BoxLayout.PAGE_AXIS)); buttonPanel1.add(Box.createVerticalGlue()); buttonPanel1.setBorder(compound); buttonPanel2.setBorder(compound); buttonPanel3.setBorder(compound); buttonPanel4.setBorder(compound); this.add(buttonPanel1); this.add(buttonPanel2); this.add(buttonPanel3); this.add(buttonPanel4); } private class ButtonListener implements ActionListener{ public void actionPerformed(ActionEvent e){ generateButton(); } private void generateButton(){ int last = 5; int place = 5; Random rand = new Random(); while(place==last){ place = rand.nextInt(4)+1; } last = place; switch (place){ case 1: repaint(); buttonPanel1.add(Button); break; case 2: repaint(); buttonPanel2.add(Button); break; case 3: repaint(); buttonPanel3.add(Button); break; case 4: repaint(); buttonPanel4.add(Button); break; } } } } A: Setting a layout manager to buttonPanel1 buttonPanel1.setLayout(new BoxLayout(buttonPanel1, BoxLayout.PAGE_AXIS)); buttonPanel1.add(Box.createVerticalGlue()); Does not change the layout manager to other panels which use FlowLayout by default. It does effect the button size. Print out System.out.println(Button.getSize()); //use button, not Button Now change the layout manager of buttonPanel1 buttonPanel1.setLayout(new BorderLayout()); and change the code to add the button to the panel : buttonPanel1.add(Button, BorderLayout.CENTER); and print again. The layout manager changes the initial size of the button. The FlowLayout manager of the other 3 panels, does not change the size.
{ "language": "en", "url": "https://stackoverflow.com/questions/44865954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use calloc to init struct I have struct struct Person { char name[50]; int citNo; float salary; }; Now I do this code: struct Person* p = malloc (sizeof(struct Person)); memset (p,0x00,sizeof(struct Person)); now I want to convert that to calloc (clean code) , how can I do that? struct Person* p = calloc(sizeof(struct Person) ,1); Or maybe put 1 it's not correct? what is the right way? A: calloc() description from man7 #include <stdlib.h> void *calloc(size_t nelem, size_t elsize); The calloc() function shall allocate unused space for an array of nelem elements each of whose size in bytes is elsize. The space shall be initialized to all bits 0. The order and contiguity of storage allocated by successive calls to calloc() is unspecified. The pointer returned if the allocation ... I encourage you to keep reading in the link man7_calloc. now after reading the description above, calling calloc seems easy to me: in your case we allocating array of one struct person struct Person* p = NULL; struct Person* p = calloc(1, sizeof(struct Person)); you must check the return value of calloc(if calloc succedd to allocate, like malloc): if(p == NULL){ puts("calloc failed"); ... ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/62444631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Validation spanning a group of text boxes I'm trying to achieve the following: Where: * *Surname is always required *NI Number OR Reference Number is required Is this beyond the scope of the ASP.NET Validation Controls? The only solution I can think of is writing some bespoke javascript (for client side) and backing that up with some server side code. A: One thing you can try is to have a CustomValidator(see here) check that both textboxes are not empty. Then validate both textboxes with a regular expression. The expression should check for either a valid entry OR a blank field. A: You can create a CustomValidator and handle it there http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic7
{ "language": "en", "url": "https://stackoverflow.com/questions/5310757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Azure Search on searching articles with images I have 500+ articles with Images, I want to retrieve those articles with images and show the same in in chatbot using Microsoft bot Framework and Azure Search. But, Azure search isn't able to index images. In this scenario where do I need to store these images, how do I map these images to appropriate article? A: You can either populate the documents in the index via code or use an indexer that can create your documents. Here is the Indexer data source drop down showing the different data sources available. You could put the information about the image and a path to the image in any of these data sources and have an indexer pick it up and create your documents within the index. If you don't want to use a formal database, you could also upload your images into blob storage and decorate each blob with custom metadata. When creating your index with an indexer, it will find the custom metadata and it can become fields on documents within your index. There are lots of options, but my advice is to keep your documents within your index as small as possible to control your costs. That's usually done by having as few a fields as possible and have fields that reference where the stuff is located. The documents within an index are for discovering where things are located and NOT for storing the actual data. When you index start occupying lots of space, your cost will go up a LOT.
{ "language": "en", "url": "https://stackoverflow.com/questions/60389131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a calculation on the list of HashMaps in Java? I currently have the following sorted set of maps of data: [ {"name":"john", "date":2015, "status":"success"}, {"name":"john", "date":2013, "status":"fail"}, {"name":"chris", "date":2013, "status":"success"}, {"name":"john", "date":2012, "status":"fail"}, {"name":"john", "date":2009, "status":"success"}, {"name":"chris", "date":2007, "status":"fail"}, {"name":"john", "date":2005, "status":"fail"}, ] I'm trying to calculate the failure duration for each of the names until 2022. Status for each name is in failure until the next success status. So, let's say for the name john, it was failed on 2005, next success was 2009, which means 4 years of failure. Then it got failed again on 2012, and again on 2013, which overall until 2015 would be 3 years of failure. Combining them would result in 7 years for john. With the same logic, for chris we have 6 years of failure. I'm stuck in the implementation of this. Does anyone have an efficient solution for this problem? A: Suppose you have a Record class for each entry public class Record { public String name; public Integer date; public String status; public Record(String name, Integer date, String status) { this.name = name; this.date = date; this.status = status; } } You can use Stream API to achieve your goals public static Map<String, Integer> useStream(List<Record> records) { return records.stream() .collect(Collectors.groupingBy(r -> r.name)) .entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> { Integer[] lastFail = new Integer[]{null}; return e.getValue().stream() .sorted(Comparator.comparing(r -> r.date)) .mapToInt(t -> { if (t.status.equals("fail") && lastFail[0] == null) { lastFail[0] = t.date; } else if (t.status.equals("success") && lastFail[0] != null) { int last = lastFail[0]; lastFail[0] = null; return t.date - last; } return 0; }) .sum(); })); } Or you can use better Seq API with smoother code public static Map<String, Integer> useSeq(List<Record> records) { return Seq.of(records) .groupBy(r -> r.name) .toList() .toMap(Map.Entry::getKey, e -> { Integer[] lastFail = new Integer[]{null}; return Seq.of(e.getValue()) .sortBy(r -> r.date) .sumInt(t -> { if (t.status.equals("fail") && lastFail[0] == null) { lastFail[0] = t.date; } else if (t.status.equals("success") && lastFail[0] != null) { int last = lastFail[0]; lastFail[0] = null; return t.date - last; } return 0; }); }); } Both of these methods result as {chris=6, john=7}
{ "language": "en", "url": "https://stackoverflow.com/questions/74793923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to verify schedules I need to verify if a certain time are between another two. For example: Today: Thursday, 11:39PM The store X is open from 00:00AM to 11:59PM on thursdays (in plural, its recorrent). So, a function isOpen returns true. I have made a workaround for this, writing this on the database (Firebase): { "open" : 7200000, "day" : "Thursday", "close" : 93540000 } Where open and close is milliseconds from 01/01/1970 In the function I check if there is a day in the database that matches the current day, after this i need to create a Date from 01/01/1970 with 11:39PM and check if open is smaller and close is bigger than current time. let open = false; if (store.schedule) { for (sch in store.schedule) { if (store.schedule[sch].day == day) { open = self.checkHour(store.schedule[sch].open, store.schedule[sch].close); } } } return open; And checkHour checkHour = function (open, close) { return moment().year(1970).month(0).date(1).isBetween(moment(open), moment(close)); }; PS: I'm using moment.js Terrible, terrible solution, I know. I'm sure there is a better way. A: Don't try to manually query your database, let the database do its own querying. You never explained which database you're using, but most a "datetime" field of some sort you can use. You can then pass a formatted date string in your query and check if it's greater than the open field and less than the close field. For example, in SQL you would do: SELECT * FROM stores WHERE {date} >= open and {date} <= close; In this case {date} would be the formatted date you're passing into the query. That said, if you already have the store in question, you can simply compare the data you already have in your javascript object. var store = { "open" : 7200000, "day" : "Thursday", "close" : 93540000 }; var now = Date.now(); if (now >= store.open && now <= store.close) { // you are in range }
{ "language": "en", "url": "https://stackoverflow.com/questions/46841536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: One to Many relationship issue in .net core web api I have two tables in my database Student and Course. Using these two tables, I have created a relationship like one student can have multiple courses. Student table : Id | FirstName | LastName | AddressNo | City | CourseId ---------------------------------------------------------------- 1 | Sandanuwan Dharmarathna 52 Kurunegala 1 Course table : Id | CourseName -------------------- 1 | English Course in my ASP.NET Core Web API, I have created two model classes called Student and Course: public class Student { public int Id { get; set; } public string FirstName { get; set; } = null!; public string LastName { get; set; } = null!; public string AddressNo { get; set; } = null!; public string City { get; set; } = null!; public List<Course> Courses { get; set; } } public class Course { public int Id { get; set; } public string CourseName { get; set; } = null!; } Now I want to get response like this { "data": [ { "id": 0, "firstName": "string", "lastName": "string", "addressNo": "string", "city": "string", "country": "string", "street": "string", "grade": "string", "className": "string", "courses": [ { "id": 0, "courseName": "string" } ] } ], "success": true, "message": "string" } But after call get function I am getting this response. It's always sending empty array in payload. { "data": [ { "id": 1, "firstName": "Sandanuwan", "lastName": "Dharmarathna", "addressNo": "52", "city": "Kurunegala", "country": "Sri Lanka", "street": "Piduruwella", "grade": "10", "className": "B", "courses": [] } ], "success": true, "message": "Successfully received all Students details" } This is my GET method: public async Task<ServiceResponse<List<GetStudentDto>>> GetAllStudents() { var response = new ServiceResponse<List<GetStudentDto>>(); var dbStudents = await _dataContext.Student.ToListAsync(); response.Data = dbStudents.Select(c => _mapper.Map<GetStudentDto>(c)).ToList(); response.Message = "Successfully received all Students details"; return response; } GetStudentDto class public class GetStudentDto { public int Id { get; set; } public string FirstName { get; set; } = null!; public string LastName { get; set; } = null!; public string AddressNo { get; set; } = null!; public string City { get; set; } = null!; public string Country { get; set; } = null!; public string Street { get; set; } = null!; public string Grade { get; set; } = null!; public string ClassName { get; set; } = null!; public List<GetCourseDto> Courses { get; set; } } public class GetCourseDto { public int Id { get; set; } public string CourseName { get; set; } = null!; } Errors Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid object name 'CourseStudent'. at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__188_0(Task`1 result) at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke() at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location --- at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread) --- End of stack trace from previous location --- Db Context Class public partial class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options): base(options) { } public virtual DbSet<Course> Course { get; set; } = null!; public virtual DbSet<Student> Student { get; set; } = null!; } enter image description here A: include courses into student instance var dbStudents = await _dataContext.Student .Include(i=>i.Courses) .ToListAsync(); and fix Course class public class Course { public int Id { get; set; } public string CourseName { get; set; } = null!; public virtual List<Student> Students { get; set; } } you have to repeat ef migration to database. New table will be created public class CourseStudent { public int CourseId { get; set; } public virtual Course Course { get; set; } public int StudentId { get; set; } public virtual Student Student { get; set; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/73071925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I brand my patternlabs installation with new colors, fonts etc? Im trying to figure out how I can change the look of the UI in patternlab. I would like to change the entire UI to something that fits my company brand more. I know there are some settings that I can change (logo for example) but I can't seem to find more changes. I would like to use our brand font and also change menu colors and so on. Mabey even move the entire menu, at least play around with it a bit. I changed the logo through the settings config but that is basically what I've found so far in regards of changing the UI. Everything I've tried so far in using my own styles mostly regard patterns and the actual components rendering. I want to style the patternlab UI including menus, text and colors.
{ "language": "en", "url": "https://stackoverflow.com/questions/75281082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Docker Containers with different Network Interface Problem: I want to have multiple VPN Servers running in Docker containers each with there own public IP. With the -p parameter I am able to connect to each one separately but the Public ip that I see is the eth0 interface not the one that I want it to be (eth0:1) so how can I create a new docker0 interface that uses eth0:1 as interface for the traffic? Best regards and thanks. A: Docker doesn't uses network outside of it . For the connection between the host to container from outside the world use port bindings. Expose the port in Dockerfile when creating docker image Expose Docker Container to Host : Exposing container is very important for the host to identify in which port container runs. -p in docker run command used to expose the ports. Syntax : docker run -p host_ip:host_port:container_port image_name e.g., docker run -itd -p 192.168.134.122:1234:1500 image_name This binds port 1500 of the container to port 1234 on 192.168.134.122 of the host machine. Use Iptables to view the network process – iptables -L -n -t nat Now the request send to host_ip (192.168.134.122) and port (1243) is redirect to container with ip (172.17.0.2) and port (1500).
{ "language": "en", "url": "https://stackoverflow.com/questions/40631867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using a custom variable in livecharts I am using the LiveCharts package in a .NET framework 4.7.2 C# form. I am trying to get data from a database into a chart, but have found that LiveCharts isn't very fond of me trying to use my own variables. I have not yet found a way to link these two with eachother. new StackedColumnSeries { Values = new ChartValues<double> {5}, StackMode = StackMode.Values, DataLabels = true, Fill = Brushes.DodgerBlue }, new StackedColumnSeries { Values = new ChartValues<double> {3}, StackMode = StackMode.Values, DataLabels = true, Fill = Brushes.LawnGreen }, new StackedColumnSeries { Values = new ChartValues<double> {1}, StackMode = StackMode.Values, DataLabels = true, Fill = Brushes.DimGray }, new StackedColumnSeries { Values = new ChartValues<double> {1}, StackMode = StackMode.Values, DataLabels = true, Fill = Brushes.IndianRed } }; I want to change the {5}, {3}, ... into a custom variable, let's say "VarDataSize". Is this possible? I am pretty new to Visual Studio 2019, so I would appreciate a lot of explanation. If I am missing any necessary information I'll gladly add it. A: Someone taught me how to do it. I had to add the following below namespace. static class global { public static int Var1; public static int Var2; public static int Var3; public static int Var4; } And then define their values in the same place as InitializeComponent(); is. global.Var1 = 5; global.Var2 = 3; global.Var3 = 1; global.Var4 = 1; And then just change the numbers with the correct variable name. It's fairly easy I suppose, but I din't know it and I hope it might help someone else too.
{ "language": "en", "url": "https://stackoverflow.com/questions/66763784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to improve speed with Stanford NLP Tagger and NLTK Is there any way to use the Standford Tagger in a more performant fashion? Each call to NLTK's wrapper starts a new java instance per analyzed string which is very very slow especially when a larger foreign language model is used... http://www.nltk.org/api/nltk.tag.html#module-nltk.tag.stanford A: Using nltk.tag.stanford.POSTagger.tag_sents() for tagging multiple sentences. The tag_sents has replaced the old batch_tag function, see https://github.com/nltk/nltk/blob/develop/nltk/tag/stanford.py#L61 DEPRECATED: Tag the sentences using batch_tag instead of tag, see http://www.nltk.org/_modules/nltk/tag/stanford.html#StanfordTagger.batch_tag A: Found the solution. It is possible to run the POS Tagger in servlet mode and then connect to it via HTTP. Perfect. http://nlp.stanford.edu/software/pos-tagger-faq.shtml#d example start server in background nohup java -mx1000m -cp /var/stanford-postagger-full-2014-01-04/stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTaggerServer -model /var/stanford-postagger-full-2014-01-04/models/german-dewac.tagger -port 2020 >& /dev/null & adjust firewall to limit access to port 2020 from localhost only iptables -A INPUT -p tcp -s localhost --dport 2020 -j ACCEPT iptables -A INPUT -p tcp --dport 2020 -j DROP test it with wget wget http://localhost:2020/?die welt ist schön shutdown server pkill -f stanford restore iptable settings iptables -D INPUT -p tcp -s localhost --dport 2020 -j ACCEPT iptables -D INPUT -p tcp --dport 2020 -j DROP
{ "language": "en", "url": "https://stackoverflow.com/questions/23322674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Return is happening before the loop finishes execution I am using for loop and return is happening before the loop finishes execution. I cant use .Map method because i have some conditions in between and want to break the loop in between. const getCompanies = async(searchURL,reqBody) => { const html = await rp(baseURL + searchURL); businessMap = cheerio('a.business-name', html); for(var i=0; i < businessMap.length; i++) { linkNew = baseURL + businessMap[i].attribs.href; const innerHtml = await rp(linkNew); .. ...My Code with conditions here ..... ...... ...... values.push( [a,b,c,d,e,f]); } return values } A: I see 2 options here: * *You have a break that gets executed where it is says My code with conditions here. *rp doesn't return a Promise. As for the second option, here's a quick code to show you that the final line of an async function gets executed only when all awaits are finished: const delay = (ms) => { return new Promise(r => { setTimeout(r, ms); console.log("delayed", ms); }); } const run = async () => { for (var i = 0; i < 3; i++) { await delay(1000); } console.log("finished"); } run();
{ "language": "en", "url": "https://stackoverflow.com/questions/64512391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to test for multiple command line arguments (sys.argv I want to test againts multiple command line arguments in a loop > python Read_xls_files.py group1 group2 group3 No this code tests only for the first one (group1). hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) How should I modify this that I can test against one, two or all of these arguments? So, if there is group1 in one sh.cell(i, 1), the list is appended and if there is group1, group2 etc., the hlo is appended. A: You can iterate over sys.argv[1:], e.g. via something like: for grp in sys.argv[1:]: for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == grp: hlo.append(sh.cell(i, 8).value) A: outputList = [x for x in values if x in sys.argv[1:]] Substitute the bits that are relevant for your (spreadsheet?) situation. This is a list comprehension. You can also investigate the optparse module which has been in the standard library since 2.3. A: I would recommend taking a look at Python's optparse module. It's a nice helper to parse sys.argv. A: argparse is another powerful, easy to use module that parses sys.argv for you. Very useful for creating command line scripts. A: I believe this would work, and would avoid iterating over sys.argv: hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value in sys.argv[1:]: hlo.append(sh.cell(i, 8).value) A: # First thing is to get a set of your query strings. queries = set(argv[1:]) # If using optparse or argparse, queries = set(something_else) hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value in queries: hlo.append(sh.cell(i, 8).value) === end of answer to question === Aside: the OP is using xlrd ... here are a couple of performance hints. Doesn't matter too much with this simple example, but if you are going to do a lot of coordinate-based accessing of cell values, you can do better than that by using Sheet.cell_value(rowx, colx) instead of Sheet.cell(rowx, colx).value which builds a Cell object on the fly: queries = set(argv[1:]) hlo = [] for i in range(len(sh.nrows)): # all columns have the same size if sh.cell_value(i, 1) in queries: hlo.append(sh.cell_value(i, 8)) or you could use a list comprehension along with the Sheet.col_values(colx) method: hlo = [ v8 for v1, v8 in zip(sh.col_values(1), sh.col_values(8)) if v1 in queries ]
{ "language": "en", "url": "https://stackoverflow.com/questions/1643643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: flask url_for returns internal server error I am tryin to have a form submit to a python script using flask. the form is in my index.html - <form action="{{ url_for('/predict') }}" method="POST"> <p>Enter Mileage</p> <input type="text" name="mileage"> <p>Enter Year</p> <input type="text" name="year"> <input type="submit" value="Predict"> </form> Here is my flask page (my_flask.py)- @app.route('/') def index(): return render_template('index.html') @app.route('/predict', methods=("POST", "GET")) def predict(): df = pd.read_csv("carprices.csv") X = df[['Mileage','Year']] y = df['Sell Price($)'] X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2) clf = LinearRegression() clf.fit(X_train, y_train) if request.method == 'POST': mileage = request.form['mileage'] year = request.form['year'] data = [[mileage, year]] price = clf.predict(data) return render_template('prediction.html', prediction = price) But when I go to my index page I get internal server error because of the Why would this be happening? {{ url_for('/predict') }} A: Instead of url_for('/predict'), drop the leading slash and use url_for('predict'). url_for(...) takes the method name and not the route name. A: I was not importing url_for. from flask import Flask, request, render_template, url_for
{ "language": "en", "url": "https://stackoverflow.com/questions/59023371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting error while writing dataframe to Ceph Storage In my organisation I'm currently exploring how we can use Ceph to replace HDFS to run out AI/ML workloads. As part of this initiative we setup a Ceph Cluster and imported it into Kubernetes using Rook. During my testing with Ceph I was able to access Ceph Storage using S3CMD CLI and also able to read data from Ceph using Spark on Kubernetes. However, I'm getting an error while writing data back to Ceph Storage. Below is my code and error which I'm getting while writing data back. Hoping someone can help with this. from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("prateek-pyspark-ceph") \ .config("spark.kubernetes.driver.master", "k8s://https://xxx:6443") \ .config("spark.kubernetes.namespace", "jupyter") \ .config("spark.kubernetes.container.image", "spark-executor-3.0.1") \ .config("spark.kubernetes.container.image.pullPolicy" ,"Always") \ .config("spark.kubernetes.container.image.pullSecrets" ,"gcr") \ .config("spark.kubernetes.authenticate.driver.serviceAccountName", "spark") \ .config("spark.kubernetes.authenticate.executor.serviceAccountName", "spark") \ .config("spark.kubernetes.authenticate.submission.caCertFile", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") \ .config("spark.kubernetes.authenticate.submission.oauthTokenFile", "/var/run/secrets/kubernetes.io/serviceaccount/token") \ .config("spark.hadoop.fs.s3a.access.key", "xxxx") \ .config("spark.hadoop.fs.s3a.secret.key", "xxxx") \ .config("spark.hadoop.fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider") \ .config("spark.hadoop.fs.s3a.endpoint", "{}:{}".format("http://xxxx", "8080")) \ .config("spark.hadoop.fs.s3a.connection.ssl.enabled", "false") \ .config("spark.hadoop.fs.s3a.path.style.access", "true") \ .config("spark.hadoop.fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem") \ .config("spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version", "2") \ .config("spark.hadoop.fs.AbstractFileSystem.s3a.impl", "org.apache.hadoop.fs.s3a.S3A") \ .config("spark.hadoop.fs.s3a.multiobjectdelete.enable", "false") \ .config("spark.hadoop.fs.s3a.fast.upload","true") \ .config("spark.eventLog.dir", "s3a://bucket/spark-event-log/") \ .config("spark.executor.instances", "1") \ .config("spark.executor.cores", "3") \ .config("spark.executor.memory", "55g") \ .config("spark.eventLog.enabled", "false") \ .getOrCreate() # Read Source Datasets musical_data= spark.read.json("s3a://bucket/input-data/Musical_Instruments_data.json") musical_metadata= spark.read.json("s3a://bucket/input-data/Musical_Instruments_metadata.json") # Register dataframes as temp tables musical_metadata.registerTempTable("musical_metadata") musical_data.registerTempTable("musical_data") # Top products based on unique user reviews top_rated = spark.sql(""" select musical_data.asin as product_id, count(distinct musical_data.reviewerID) as unique_reviewer_id_count, musical_metadata.price as product_price from musical_data left outer join musical_metadata on musical_data.asin == musical_metadata.asin group by product_id, product_price order by unique_reviewer_id_count desc limit 10 """) # Display top 10 products top_rated.show(truncate=False) # Save output as csv top_rated.write.format("csv") \ .option("header","true") \ .mode("overwrite") \ .save("s3a://bucket/output-data/") # Stop Spark Context to release resources spark.stop() Error while writing Dataframe. Py4JJavaError: An error occurred while calling o740.save. : org.apache.hadoop.fs.s3a.AWSBadRequestException: PUT 0-byte object on output-data/_temporary/0/: com.amazonaws.services.s3.model.AmazonS3Exception: null (Service: Amazon S3; Status Code: 400; Error Code: InvalidRequest; Request ID: tx0000000000000000002b3-00604055fa-1ea62-sg; S3 Extended Request ID: 1ea62-sg-sg; Proxy: null), S3 Extended Request ID: 1ea62-sg-sg:InvalidRequest: null (Service: Amazon S3; Status Code: 400; Error Code: InvalidRequest; Request ID: tx0000000000000000002b3-00604055fa-1ea62-sg; S3 Extended Request ID: 1ea62-sg-sg; Proxy: null) at org.apache.hadoop.fs.s3a.S3AUtils.translateException(S3AUtils.java:224) at org.apache.hadoop.fs.s3a.Invoker.once(Invoker.java:111) at org.apache.hadoop.fs.s3a.Invoker.lambda$retry$3(Invoker.java:265) at org.apache.hadoop.fs.s3a.Invoker.retryUntranslated(Invoker.java:322) at org.apache.hadoop.fs.s3a.Invoker.retry(Invoker.java:261) at org.apache.hadoop.fs.s3a.Invoker.retry(Invoker.java:236) at org.apache.hadoop.fs.s3a.S3AFileSystem.createEmptyObject(S3AFileSystem.java:2786) at org.apache.hadoop.fs.s3a.S3AFileSystem.createFakeDirectory(S3AFileSystem.java:2761) at org.apache.hadoop.fs.s3a.S3AFileSystem.innerMkdirs(S3AFileSystem.java:2088) at org.apache.hadoop.fs.s3a.S3AFileSystem.mkdirs(S3AFileSystem.java:2021) at org.apache.hadoop.fs.FileSystem.mkdirs(FileSystem.java:2275) at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.setupJob(FileOutputCommitter.java:354) at org.apache.spark.internal.io.HadoopMapReduceCommitProtocol.setupJob(HadoopMapReduceCommitProtocol.scala:163) at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:168) at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:178) at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:108) at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:106) at org.apache.spark.sql.execution.command.DataWritingCommandExec.doExecute(commands.scala:131) at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:175) at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:213) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:210) at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:171) at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:122) at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:121) at org.apache.spark.sql.DataFrameWriter.$anonfun$runCommand$1(DataFrameWriter.scala:963) at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$5(SQLExecution.scala:100) at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:160) at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:87) at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:764) at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:64) at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:963) at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:415) at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:399) at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:288) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:282) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:238) at java.lang.Thread.run(Thread.java:748) Caused by: com.amazonaws.services.s3.model.AmazonS3Exception: null (Service: Amazon S3; Status Code: 400; Error Code: InvalidRequest; Request ID: tx0000000000000000002b3-00604055fa-1ea62-sg; S3 Extended Request ID: 1ea62-sg-sg; Proxy: null), S3 Extended Request ID: 1ea62-sg-sg at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1828) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1412) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1374) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1145) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:802) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:770) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:744) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:704) at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:686) at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:550) at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:530) at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5212) at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5158) at com.amazonaws.services.s3.AmazonS3Client.access$300(AmazonS3Client.java:398) at com.amazonaws.services.s3.AmazonS3Client$PutObjectStrategy.invokeServiceCall(AmazonS3Client.java:6113) at com.amazonaws.services.s3.AmazonS3Client.uploadObject(AmazonS3Client.java:1817) at com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1777) at org.apache.hadoop.fs.s3a.S3AFileSystem.putObjectDirect(S3AFileSystem.java:1545) at org.apache.hadoop.fs.s3a.S3AFileSystem.lambda$createEmptyObject$13(S3AFileSystem.java:2788) at org.apache.hadoop.fs.s3a.Invoker.once(Invoker.java:109) ... 44 more Versions - Spark 3.0.1 Hadoop 3.2 A: Finally the job worked in both Client and Cluster mode Cluster Mode via Spark Submit ./spark-submit \ --master k8s://https://xxxx:6443 \ --deploy-mode cluster \ --name prateek-ceph-pyspark \ --conf spark.kubernetes.namespace=jupyter \ --conf spark.executor.instances=1 \ --conf spark.executor.cores=3 \ --conf spark.executor.memory=55g \ --conf spark.kubernetes.container.image=spark-executor-3.0.1 \ --conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \ --conf spark.kubernetes.authenticate.executor.serviceAccountName=spark \ --conf spark.kubernetes.container.image.pullPolicy=Always \ --conf spark.kubernetes.container.image.pullSecrets=gcr \ --conf spark.kubernetes.authenticate.submission.caCertFile=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt \ --conf spark.kubernetes.authenticate.submission.oauthTokenFile=/var/run/secrets/kubernetes.io/serviceaccount/token \ --conf spark.hadoop.fs.s3a.access.key=<ACCESS_KEY> \ --conf spark.hadoop.fs.s3a.secret.key=<SECRET_KEY> \ --conf spark.hadoop.fs.s3a.aws.credentials.provider=org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider \ --conf spark.hadoop.fs.s3a.endpoint=http://xxxx:8080 \ --conf spark.hadoop.fs.s3a.connection.ssl.enabled=false \ --conf spark.hadoop.fs.s3a.path.style.access=true \ --conf spark.eventLog.enabled=false \ s3a://ceph-bucket/scripts/Ceph_PySpark.py Client Mode in Jupyter Notebook - Spark Config with AWS Credential Provider - org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("prateek-pyspark-ceph") \ .config("spark.kubernetes.driver.master", "k8s://https://xxxx:6443") \ .config("spark.kubernetes.namespace", "jupyter") \ .config("spark.kubernetes.container.image", "spark-executor-3.0.1") \ .config("spark.kubernetes.container.image.pullPolicy" ,"Always") \ .config("spark.kubernetes.container.image.pullSecrets" ,"gcr") \ .config("spark.kubernetes.authenticate.driver.serviceAccountName", "spark") \ .config("spark.kubernetes.authenticate.executor.serviceAccountName", "spark") \ .config("spark.kubernetes.authenticate.submission.caCertFile", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") \ .config("spark.kubernetes.authenticate.submission.oauthTokenFile", "/var/run/secrets/kubernetes.io/serviceaccount/token") \ .config("spark.hadoop.fs.s3a.access.key", "xxxxx") \ .config("spark.hadoop.fs.s3a.secret.key", "xxxxx") \ .config("spark.hadoop.fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider") \ .config("spark.hadoop.fs.s3a.endpoint", "{​​​​​​​}​​​​​​​:{​​​​​​​}​​​​​​​".format("http://xxxx", "8080")) \ .config("spark.hadoop.fs.s3a.connection.ssl.enabled", "false") \ .config("spark.hadoop.fs.s3a.path.style.access", "true") \ .config("spark.executor.instances", "2") \ .config("spark.executor.cores", "6") \ .config("spark.executor.memory", "55g") \ .getOrCreate() Spark Config with AWS Credential Provider - com.amazonaws.auth.EnvironmentVariableCredentialsProvider from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("prateek-pyspark-ceph") \ .config("spark.kubernetes.driver.master", "k8s://https://xxxx:6443") \ .config("spark.kubernetes.namespace", "jupyter") \ .config("spark.kubernetes.container.image", "spark-executor-3.0.1") \ .config("spark.kubernetes.container.image.pullPolicy" ,"Always") \ .config("spark.kubernetes.container.image.pullSecrets" ,"gcr") \ .config("spark.kubernetes.authenticate.driver.serviceAccountName", "spark") \ .config("spark.kubernetes.authenticate.executor.serviceAccountName", "spark") \ .config("spark.kubernetes.authenticate.submission.caCertFile", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") \ .config("spark.kubernetes.authenticate.submission.oauthTokenFile", "/var/run/secrets/kubernetes.io/serviceaccount/token") \ .config("spark.hadoop.fs.s3a.aws.credentials.provider", "com.amazonaws.auth.EnvironmentVariableCredentialsProvider") \ .config("spark.hadoop.fs.s3a.endpoint", "{​​​​​​​}​​​​​​​:{​​​​​​​}​​​​​​​".format("http://xxxx", "8080")) \ .config("spark.hadoop.fs.s3a.connection.ssl.enabled", "false") \ .config("spark.hadoop.fs.s3a.path.style.access", "true") \ .config("spark.executor.instances", "2") \ .config("spark.executor.cores", "6") \ .config("spark.executor.memory", "55g") \ .getOrCreate() To solve the issue in Writing to Ceph in Client Mode, add all properties related to fs.s3a.committer.staging.* mentioned here - https://hadoop.apache.org/docs/current/hadoop-aws/tools/hadoop-aws/committers.html in your core-site.xml file in both Driver and Executor image
{ "language": "en", "url": "https://stackoverflow.com/questions/66468333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flash not working on Chrome, FF, Safari, but it is working on IE I made the huge mistake of getting a template instead of just doing the development my self. Now I've narrowed down the issue- first, I thought it was an issue with the actual flash file. Now I'm realizing it's every time I change the images in the HTML editor which just makes no logical sense to me. This is the code for the flash file: <body id="page1" onload="new ElementMaxHeight()"> <div id="main"> <!-- header --> <div id="header"> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="download.macromedia.com/pub/shockwave/cabs/flash/…; width="940" height="417"></object><!----> <![endif]--> </div> <!-- content --> <div id="content"> Again, it works great on IE, but nothing else, which is a twist I haven't seen online. Appreciate any feedback you can offer. A: Im sure this answer is here already but i will post a generic code i always use. Just place the whole block and change related values, swf properties. <object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="950" height="377"> <param name="movie" value="myMovie.swf"> <param name="quality" value="high"> <param name="wmode" value="direct" > <param name="swfversion" value="6.0.65.0"> <!-- This param tag prompts users with Flash Player 6.0 r65 and higher to download the latest version of Flash Player. Delete it if you don’t want users to see the prompt. --> <param name="expressinstall" value="Scripts/expressInstall.swf"> <param name="SCALE" value="noborder"> <!-- Next object tag is for non-IE browsers. So hide it from IE using IECC. --> <!--[if !IE]>--> <object type="application/x-shockwave-flash" data="myMovie.swf" width="950" height="377"> <!--<![endif]--> <param name="quality" value="high"> <param name="wmode" value="direct" > <param name="swfversion" value="6.0.65.0"> <param name="expressinstall" value="Scripts/expressInstall.swf"> <param name="SCALE" value="noborder"> <!-- The browser displays the following alternative content for users with Flash Player 6.0 and older. --> <div> <h4>Content on this page requires a newer version of Adobe Flash Player.</h4> <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p> </div> <!--[if !IE]>--> </object> <!--<![endif]--> </object>
{ "language": "en", "url": "https://stackoverflow.com/questions/18966985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Div Alignment when using twitter Favorite animation I saw an example for Twitter Favorite animation and I used in my design for testing and now i have problem with alignment for the icons and I don't know how to fix it? Can anyone explain things to me, please? Below you will the actual code use and I need all the icon with the text to be in one column some thing similar to twitter icon but very basic one. /* when a user clicks, toggle the 'is-animating' class */ $(".heart").on('click touchstart', function(){ $(this).toggleClass('is_animating'); }); /*when the animation is over, remove the class*/ $(".heart").on('animationend', function(){ $(this).toggleClass('is_animating'); }); .postfooter { display: flex; justify-content: flex-start; color: #b3b3b3; margin-top: 30px; font-size: 25px; } .postfooter .fa { margin-left: 40px; } .heart { cursor: pointer; height: 70px; width: 70px; background-image:url( 'https://abs.twimg.com/a/1446542199/img/t1/web_heart_animation.png'); background-position: left; background-repeat:no-repeat; background-size:2900%; } .heart:hover { background-position:right; } .is_animating { animation: heart-burst .8s steps(28) 1; } @keyframes heart-burst { from {background-position:left;} to { background-position:right;} } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> <!-- Font-Awesome CDN --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <!-- jQuery CDN --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> </head> <body> <div class="postfooter"> <div><i class="fa fa-reply" aria-hidden="true"> 2</i></div> <div><i class="fa fa-retweet" aria-hidden="true"> 30</i></div> <div><div class="heart"></div> 16</div> </div> </body> </html> A: The reason why your elements aren't aligning is because the div element containing your heart animation is a block-level element (versus the i elements with the font-awesome icons, which are inline). To fix that part, you just have to add display: inline-block to the heart element. The height of your heart element is also 70px, so to align the other elements, you'll also need to add height: 70px and line-height: 70px; to your post-footer. Finally, to adjust for the fact that the heart element is much wider than the other elements, you can wrap the heart counts in a span and give it a negative margin. /* when a user clicks, toggle the 'is-animating' class */ $(".heart").on('click touchstart', function(){ $(this).toggleClass('is_animating'); }); /*when the animation is over, remove the class*/ $(".heart").on('animationend', function(){ $(this).toggleClass('is_animating'); }); .postfooter { display: flex; justify-content: flex-start; color: #b3b3b3; margin-top: 30px; font-size: 25px; height: 70px; line-height: 70px; } .postfooter .fa { margin-left: 40px; } .heart { display: inline-block; cursor: pointer; height: 70px; width: 70px; background-image:url( 'https://abs.twimg.com/a/1446542199/img/t1/web_heart_animation.png'); background-position: left; background-repeat:no-repeat; background-size:2900%; } .heart-text { margin-left: -20px; } .heart:hover { background-position:right; } .is_animating { animation: heart-burst .8s steps(28) 1; } @keyframes heart-burst { from {background-position:left;} to { background-position:right;} } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> <!-- Font-Awesome CDN --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <!-- jQuery CDN --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> </head> <body> <div class="postfooter"> <div><i class="fa fa-reply" aria-hidden="true"> 2</i></div> <div><i class="fa fa-retweet" aria-hidden="true"> 30</i></div> <div class="heart"></div><span class="heart-text">16</span> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/49116776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSL connection failed when loading JS SDK I followed the info from this post : here to load the JS SDK into my page. Here is the page : https://www.tkwk.be/client/babyboom/www/ It works great (SSL connection is valid) until I use the SDK. The problem is that when I try to use the function setAutoGrow() just before my /head I got an error. <script type="text/javascript"> window.fbAsyncInit = function() { FB.Canvas.setAutoGrow(); } </script> The page at about:blank displayed insecure content from http://static.ak.facebook.com/connect/canvas_proxy.php?version=3#behavior=p&method=setSize&params=%7B%22height%22%3A892%2C%22width%22%3A1630%2C%22frame%22%3A%22iframe_canvas%22%7D. However I did load the JS SDK with https like this : <div id="fb-root"></div><script src="https://connect.facebook.net/en_US/all.js"></script> <script> FB._https = true; FB._https = (window.location.protocol == "https:"); FB.init({ appId : 'XXXXXXXXXXX', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); </script> I would like to understand where I made a mistake. Thanks in advance for your time.
{ "language": "en", "url": "https://stackoverflow.com/questions/9044894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I can not configure e-mail Jenkins Extension Shortly: I'm using "E-mail Notification" on my Jenkins, its setuped on my local machine. I can not configure emial notifications. My configuration: * *SMTP server: smtp.gmail.com *Default user e-mail suffix: *Use SMTP Authentication: Checked *User Name: My Gmail mail (i turn off only safe app) *Password: **** *Use SSL: Checked *SMTP Port: 465 Failed to send out e-mail sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source) at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source) at java.security.cert.CertPathBuilder.build(Unknown Source) Caused: sun.security.validator.ValidatorException: PKIX path building failed at sun.security.validator.PKIXValidator.doBuild(Unknown Source) at sun.security.validator.PKIXValidator.engineValidate(Unknown Source) at sun.security.validator.Validator.validate(Unknown Source) at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source) at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source) at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source) Caused: javax.net.ssl.SSLHandshakeException at sun.security.ssl.Alerts.getSSLException(Unknown Source) at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source) at sun.security.ssl.Handshaker.fatalSE(Unknown Source) at sun.security.ssl.Handshaker.fatalSE(Unknown Source) at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source) at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source) at sun.security.ssl.Handshaker.processLoop(Unknown Source) at sun.security.ssl.Handshaker.process_record(Unknown Source) at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:507) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900) Caused: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638) at javax.mail.Service.connect(Service.java:295) at javax.mail.Service.connect(Service.java:176) at javax.mail.Service.connect(Service.java:125) at javax.mail.Transport.send0(Transport.java:194) at javax.mail.Transport.send(Transport.java:124) at hudson.tasks.Mailer$DescriptorImpl.doSendTestMail(Mailer.java:613) at java.lang.invoke.MethodHandle.invokeWithArguments(Unknown Source) at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:396) at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:408) at org.kohsuke.stapler.interceptor.RequirePOST$Processor.invoke(RequirePOST.java:77) at org.kohsuke.stapler.PreInvokeInterceptedFunction.invoke(PreInvokeInterceptedFunction.java:26) at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:212) at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:145) at org.kohsuke.stapler.MetaClass$11.doDispatch(MetaClass.java:535) at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58) at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:747) at org.kohsuke.stapler.Stapler.invoke(Stapler.java:878) at org.kohsuke.stapler.MetaClass$4.doDispatch(MetaClass.java:280) at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58) at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:747) at org.kohsuke.stapler.Stapler.invoke(Stapler.java:878) at org.kohsuke.stapler.Stapler.invoke(Stapler.java:676) at org.kohsuke.stapler.Stapler.service(Stapler.java:238) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:873) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1623) at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:154) at hudson.plugins.locale.LocaleFilter.doFilter(LocaleFilter.java:42) at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:151) at jenkins.telemetry.impl.UserLanguages$AcceptLanguageFilter.doFilter(UserLanguages.java:128) at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:151) at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:157) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610) at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:99) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84) at hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87) at jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87) at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87) at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:135) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87) at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87) at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87) at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249) at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67) at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87) at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:90) at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610) at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610) at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610) at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:540) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132) at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1701) at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1345) at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:480) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1668) at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1247) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132) at org.eclipse.jetty.server.Server.handle(Server.java:502) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:370) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:267) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103) at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:117) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:333) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:310) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:168) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:126) at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:366) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:765) at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:683) at java.lang.Thread.run(Unknown Source) I think everythink is ok, email should be send. A: Go to https:///systemInfo >> javax.net.ssl.trustStore. This is the truststore where the certificate should be added. You can open the keystore with keytool or if you prefer a GUI take a look at Keystore Explorer The default password of the truststore is changeit.
{ "language": "en", "url": "https://stackoverflow.com/questions/57296545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: (standard_in) 1: syntax error I am new to bash and linux and can't understand why do i have this error ((standard_in) 1: syntax error) in my code. #!/bin/bash file_data=$(<merge.bmp) counter=0 file_size=$(stat -c%s "merge.bmp") touch file1.bmp touch file2.bmp while [ $counter -lt 10 ]; do if [ `echo "$counter % 2" | bc` -eq 0 ]; then var=`xxd -p -l1 -s $counter merge.bmp` hex_var=$(echo "obase=16; $var" | bc) else var=`xxd -p -l1 -s $counter merge.bmp` hex_var=$(echo "obase=16;$var" | bc) fi let counter=counter+1 done echo "DONE!" A: That's the error coming out of the tool bc you had used for arithmetic evaluation. I suspect the variable assignment, $var leading to echo "obase=16; $var" | bc has a malformed/empty value which bc did not like. If you are using the bash shell, you could very well use its over arithmetic evaluation using the $((..)) construct as for (( counter=0; counter<10; counter++ )); do if (( counter % 2 == 0 )); then var=$(xxd -p -l1 -s "$counter" merge.bmp) printf -v hex_var '%x' "$var" fi done The %x applies the necessary decimal to hex conversion needed. Moreover you are doing the same action in both if and else clause. Also remove the outdated back-ticks syntax for command substitution, rather use $(..).
{ "language": "en", "url": "https://stackoverflow.com/questions/48238631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL query help as attached format I have a MySQL table which is as like this: # Structure for table "audit" # DROP TABLE IF EXISTS `audit`; CREATE TABLE `audit` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `item` varchar(255) DEFAULT NULL, `amount` varchar(255) DEFAULT NULL, `myDate` date DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1; # # Data for table "audit" # INSERT INTO `audit` VALUES (1,'audit','0','2015-12-23'), (2,'fs_delete','4206','2015-12-23'), (3,'log_print','27443','2015-12-23'), (4,'sys_error','10102','2015-12-23'), (5,'sys_info','150','2015-12-23'), (6,'sys_proxy','30','2015-12-23'), (7,'users','2','2015-12-23'), (8,'audit','7','2015-12-22'), (9,'fs_delete','4206','2015-12-22'), (10,'log_print','27443','2015-12-22'), (11,'sys_error','10102','2015-12-22'), (12,'sys_info','150','2015-12-22'), (13,'sys_proxy','30','2015-12-22'), (14,'users','2','2015-12-22'); I would like to have a output like the image below A: I think you need a query like this: SELECT `myDate` , MAX(CASE WHEN `item` = 'audit' THEN `amount` END) AS `audit` , MAX(CASE WHEN `item` = 'fs_delete' THEN `amount` END) AS `fs_delete` , MAX(CASE WHEN `item` = 'log_print' THEN `amount` END) AS `log_print` , MAX(CASE WHEN `item` = 'sys_error' THEN `amount` END) AS `sys_error` , MAX(CASE WHEN `item` = 'sys_info' THEN `amount` END) AS `sys_info` FROM `audit` GROUP BY `myDate`; [SQL Fiddle Demo]
{ "language": "en", "url": "https://stackoverflow.com/questions/34468908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null. But app still renders Hi im fairly new to Meteor and react and am working on a customer portal. I have adapted the meteor react tutorial to work how i need it to work and am using Flow Router for routing. Everything currently works as it should except i am still getting this error Uncaught Error: AppMount(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null., no matter what i do. Here is my code for routing aswell as most of the code for the main homepage: main.jsx import AppMount from '/imports/ui/AppMount' import "./routes" Meteor.startup(() => { render(<AppMount />, document.getElementById('root')) }) AppMount.jsx const AppMount = props => { return (props.content); } export default AppMount App.jsx const App = () => { const user = useTracker(() => Meteor.user()); const { tasks, isLoading } = useTracker(() => { const noDataAvailable = { tasks: [] }; if (!Meteor.user()) { return (noDataAvailable); } const handler = Meteor.subscribe('tasks'); if (!handler.ready()) { return ({ ...noDataAvailable, isLoading: true }); } const tasks = TasksCollection.find( userFilter, { sort: { status: 1 }, } ).fetch(); return ({ tasks }); }); return( <div className="app"> <Header /> <div className="main"> {user ? ( <Fragment> <div className="menu"> {user.admin && ( <Fragment> <button className="addUser" onClick={newUser} > Add New User </button> <button className="addTask" onClick={addTask} > Add Task </button> </Fragment> )} <button className="changePass" onClick={changePass} > Change Password </button> <button className="user" onClick={logout} > Logout: {user.username} </button> </div> {isLoading && <div className="loading">loading..</div>} <ul className="tasks"> {tasks.map(task => ( <Task key={task._id} task={task} onCheckboxClick={toggleChecked} onDeleteClick={deleteTask} advanceStage={advanceStage} revertStage={revertStage} /> ))} </ul> </Fragment> ) : ( <LoginForm /> )} </div> </div> ); } export default App routes.jsx FlowRouter.route('/', { name: 'Home', action() { mount(AppMount, { content: <App /> }) } }) I know this question has been asked before but i believe i have tried every solution to no avail. Any help is appreciated. A: props.content need {} const AppMount = props => { return {props.content}; }
{ "language": "en", "url": "https://stackoverflow.com/questions/65712896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: CI return just Validation_error and not the entire form page I have a view with both login and register forms on the same page. I would like to return just the error message and not refresh the entire page. How can I do that? public function signup() { $this->form_validation->set_rules('user_name', 'User name', 'min_length[4]|is_unique[ts_user.user_name]|xss_clean'); $this->form_validation->set_rules('user_twitter_id', 'User Twitter ID', 'is_unique[ts_user.user_twitter_id]|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'required|min_length[8]'); $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[ts_user.email]'); if($this->input->post('submit') == TRUE) { if($this->form_validation->run()) { $twitterid = $this->input->post('user_twitter_id'); $username = $this->input->post('user_name'); $email = $this->input->post('email'); $password = $this->input->post('password'); $this->Usermodel->add_user($twitterid, $username, $email, $password); echo 'Successful.'; } else { echo validation_errors(); /*$this->load->view('registration_view');*/ } } } A: Do not use post, use ajax sample: var paperData = 'name=' + sourceFileName + '&' + 'file=' + uploadFileName; var url = encodeURI('/Paper/Create?' + paperData); ajax ({ block: false, url: url, success: function (r) { if (r.success) { var html='<tr><td class="tac">'; html = html + r.displayName; html = html + '</td>'; html = html + '<td class="tac">'; html = html + r.type; html = html + '</td>'; html = html + '<td>'; html = html + '<a class="showPaperEditor" href="/Paper/Edit/'; html = html + r.paperID; html = html + '" w="570" h="340" >修改</a>'; html = html + '<span class="cd">┊</span>' ; html = html + '<a class="a-ajax-delPaper" href="/Paper/Delete/'; html = html + r.paperID; html = html + '">删除</a>'; html = html + '</td></tr>'; $('#tbPaperList').append(html); } else { alert(r.message); //$.unblockUI(); } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/11112658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What setting causes ContextLoaderListener's (root context) to be the 'parent' context over DispatcherServlet's context? First came into this problem by wondering how I was supposed to autowire/inject a service layer level bean from the ContextLoaderListener's application context INTO a bean from DispatcherServlet's context. Let's say for a random simple situation, a PuppyService needs to be autowired/injected into PuppyResource on the actual resource/controller level. The Puppy Service along with the Puppy Repository and any Puppy Entities would be beans auto-loaded into the root/ContextLoaderListener's context from a @Configuration class that does a component-scan in some other package to grab the beans and load them... At the same time, the Puppy RESOURCE would be more on the webMvc level and loaded into DispatcherServlet's context. From what I just read, and now hopefully understand, the root context is actually the 'parent' context of the context created by DispatcherServlet. This means that beans that live inside the root context can actually be autowired/injected into any bean that lives inside the context created by DispatcherServlet. I literally just learned about this concept of 'nested' contexts. Is this accurate? If this is accurate, then where does the configuration get set to make the root context the 'parent' context? Currently, when I configure the servlet/listener, I do it via a custom implementation of WebApplicationInitializer, wherein I simply create two contexts, load them each respectively into a DispatcherServlet instance, and a ContextLoaderListener instance, then register each of those respectively into the servlet. I'm guessing somewhere in there, the ContextLoaderListener's application context automatically gets set to the 'parent'. Could someone briefly explain this? Thank you. A: The behavior is built into the DispatcherServlet. The javadoc defines the root application context. Only the root application context as loaded by ContextLoaderListener, if any, will be shared. The javadoc of ContextLoaderListener also states Bootstrap listener to start up and shut down Spring's root WebApplicationContext. And, assuming you use the DispatcherServlet constructor that receives a WebApplicationContext, If the given context does not already have a parent, the root application context will be set as the parent. you'll get this behavior automatically. Again from the javadoc, This constructor is useful in Servlet 3.0+ environments where instance-based registration of servlets is possible through the ServletContext.addServlet(java.lang.String, java.lang.String) API. which is what the common AbstractDispatcherServletInitializer uses to set up your Spring MVC application.
{ "language": "en", "url": "https://stackoverflow.com/questions/42722299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: undefined reference when writing/reading Static thread_local class member? #include <iostream> #include <thread> class A{ public: static thread_local long l ; int value ; A(int a = 2){ value = a; } int foo(){ A::l = 3; return 3; } }; A a; int main(){ // A::l = 3; a.foo(); return 0; } above code on compiling gives error can someone help to resolve them? when i remove the reads and writes to static thread_local this seems to compile . does it needs some special libraries or linkers to work properly . I need to keep static thread_local to get same features as threadLocal class in java
{ "language": "en", "url": "https://stackoverflow.com/questions/55069128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: A problem when releveling a factor to the default order? I have this df df = data.frame(x = 1:3) converted to a factor df$x = factor(df$x) the levels by default are str(df) now let's make level 2 as the reference level df$x = relevel(df$x,ref=2) everything till now is ok. but when deciding to make the level 1 again as the default level it's not working df$x = relevel(df$x,ref=2) str(df) df$x = relevel(df$x,ref=1) str(df) Appreciatethe help. A: From ?relevel, ref: the reference level, typically a string. I'll key off of "typically". Looking at the code of stats:::relevel.factor, one key part is if (is.character(ref)) ref <- match(ref, lev) This means to me that after this expression, ref is now (assumed to be) an integer that corresponds to the index within the levels. In that context, your ref=1 is saying to use the first level by its index (which is already first). Try using a string. relevel(df$x,ref=1) # [1] 1 2 3 # Levels: 2 1 3 relevel(df$x,ref="1") # [1] 1 2 3 # Levels: 1 2 3
{ "language": "en", "url": "https://stackoverflow.com/questions/74492068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Not able to post data on aws http api? In my lambda function when i return this def lambda_handler(event, context): return json.dumps("{'result':'abcde'}") it is returning the expected result, but when i return this def lambda_handler(event, context): return event["payloadData"] It gave "message": "Internal Server Error" I am posting data using postman curl --location --request POST 'https://sampleurl.execute-api.us-west-2.amazonaws.com/sms' \ --form 'payloadData="9876543210"' my cors header from aws Access-Control-Allow-Origin * Access-Control-Allow-Headers * Access-Control-Allow-Methods POST OPTIONS * cloudwatch log { "requestId": "Be7tojFFPHcEMQg=", "ip": "157.39.109.241", "requestTime": "25/Jun/2021:13:26:34 +0000", "httpMethod": "POST", "routeKey": "POST /sms", "status": "500", "protocol": "HTTP/1.1", "responseLength": "35" } A: I was getting the post data but it was not in event["payloadData"]. It was inside event["body"] which is base64 encoded. So i use this to get the posted data base64.b64decode(str(event["body"])).decode('utf-8')
{ "language": "en", "url": "https://stackoverflow.com/questions/68131342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: none.xml:1: parser error : Extra content at the end of the document in android studio In Android studio after running the following code, it says"none.xml:1: parser error : Extra content at the end of the document" what is the problem? its the code that i copied from https://developer.android.com/training/basics/firstapp/building-ui.html the code is here : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_my"> <EditText android:id="@+id/edit_message" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/edit_message" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" /> </LinearLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/38354583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does .livequery() work when it only receives one parameter? I was visiting https://github.com/brandonaaron/livequery trying to find the syntax of .livequery(). From what I can see there in the official documentation, .livequery() can receive two or three parameters: // selector: the selector to match against // matchedFn: the function to execute when a new element is added to the DOM that matches $(...).livequery( selector, matchedFn ); // selector: the selector to match against // matchedFn: the function to execute when a new element is added to the DOM that matches // unmatchedFn: the function to execute when a previously matched element is removed from the DOM $(...).livequery( selector, matchedFn, unmatchFn ); However, in the source code I am examining, I see .livequery() receiving only one parameter. For example: $('.js-truncate').livequery(function() { .................................. }); From what I understand and based on what I see in the official documentation, the first parameter of .livequery() is always "selector". What does it mean when .livequery() receives a single parameter, which is this parameter in my case?: function(){.......}. Thank you. A: It is irrelevant for me now because from now on I will use .on, since I upgraded jQuery.
{ "language": "en", "url": "https://stackoverflow.com/questions/46209774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nslcd lookup failed: No results returned I'd like to authenticate my users with my LDAP Directory. I've configured nslcd to do it, but it fails. nslcd debug mode indicates this : nslcd: [b0dc51] DEBUG: ldap_simple_bind_s("uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr","***") (uri="ldap://net.ch-havre.fr") nslcd: [b0dc51] DEBUG: ldap_result(): end of results (0 total) nslcd: [b0dc51] uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr: lookup failed: No results returned getent passwd seb -> OK getent shadow seb -> OK Thanks you for answering. My search base is defined in nslcd.conf as : uid nslcd gid ldap ldap_version 3 binddn cn=UnixBind,dc=Unix,dc=ch-havre,dc=fr bindpw XXXXXX base group ou=Group,dc=unix,dc=ch-havre,dc=fr base passwd ou=Users,dc=unix,dc=ch-havre,dc=fr base shadow ou=Users,dc=unix,dc=ch-havre,dc=fr ssl no tls_cacertdir /etc/openldap/cacerts uri ldap://net.ch-havre.fr base dc=ch-havre,dc=fr Is there something wrong ? This is the debug mode output : nslcd: [b71efb] DEBUG: connection from pid=20820 uid=0 gid=0 nslcd: [b71efb] <passwd="seb"> DEBUG: myldap_search(base="dc=unix,dc=ch-havre,dc=fr", filter="(&(objectClass=posixAccount)(uid=seb))") nslcd: [b71efb] <passwd="seb"> DEBUG: ldap_result(): uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr nslcd: [b71efb] <passwd="seb"> DEBUG: ldap_result(): end of results (1 total) nslcd: [e2a9e3] DEBUG: connection from pid=20820 uid=0 gid=0 nslcd: [e2a9e3] <passwd="seb"> DEBUG: myldap_search(base="dc=unix,dc=ch-havre,dc=fr", filter="(&(objectClass=posixAccount)(uid=seb))") nslcd: [e2a9e3] <passwd="seb"> DEBUG: ldap_result(): uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr nslcd: [e2a9e3] <passwd="seb"> DEBUG: ldap_result(): end of results (1 total) nslcd: [45e146] DEBUG: connection from pid=20820 uid=0 gid=0 nslcd: [45e146] <passwd="seb"> DEBUG: myldap_search(base="dc=unix,dc=ch-havre,dc=fr", filter="(&(objectClass=posixAccount)(uid=seb))") nslcd: [45e146] <passwd="seb"> DEBUG: ldap_result(): uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr nslcd: [45e146] <passwd="seb"> DEBUG: ldap_result(): end of results (1 total) nslcd: [5f007c] DEBUG: connection from pid=20820 uid=0 gid=0 nslcd: [5f007c] <passwd="seb"> DEBUG: myldap_search(base="dc=unix,dc=ch-havre,dc=fr", filter="(&(objectClass=posixAccount)(uid=seb))") nslcd: [5f007c] <passwd="seb"> DEBUG: ldap_result(): uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr nslcd: [5f007c] <passwd="seb"> DEBUG: ldap_result(): end of results (1 total) nslcd: [d062c2] DEBUG: connection from pid=20820 uid=0 gid=0 nslcd: [d062c2] <authc="seb"> DEBUG: nslcd_pam_authc("seb","sshd","***") nslcd: [d062c2] <authc="seb"> DEBUG: myldap_search(base="dc=unix,dc=ch-havre,dc=fr", filter="(&(objectClass=posixAccount)(uid=seb))") nslcd: [d062c2] <authc="seb"> DEBUG: ldap_result(): uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr nslcd: [d062c2] <authc="seb"> DEBUG: myldap_search(base="uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr", filter="(objectClass=*)") nslcd: [d062c2] <authc="seb"> DEBUG: ldap_initialize(ldap://net.ch-havre.fr) nslcd: [d062c2] <authc="seb"> DEBUG: ldap_set_rebind_proc() nslcd: [d062c2] <authc="seb"> DEBUG: ldap_set_option(LDAP_OPT_PROTOCOL_VERSION,3) nslcd: [d062c2] <authc="seb"> DEBUG: ldap_set_option(LDAP_OPT_DEREF,0) nslcd: [d062c2] <authc="seb"> DEBUG: ldap_set_option(LDAP_OPT_TIMELIMIT,0) nslcd: [d062c2] <authc="seb"> DEBUG: ldap_set_option(LDAP_OPT_TIMEOUT,0) nslcd: [d062c2] <authc="seb"> DEBUG: ldap_set_option(LDAP_OPT_NETWORK_TIMEOUT,0) nslcd: [d062c2] <authc="seb"> DEBUG: ldap_set_option(LDAP_OPT_REFERRALS,LDAP_OPT_ON) nslcd: [d062c2] <authc="seb"> DEBUG: ldap_set_option(LDAP_OPT_RESTART,LDAP_OPT_ON) nslcd: [d062c2] <authc="seb"> DEBUG: ldap_simple_bind_s("uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr","***") (uri="ldap://net.ch-havre.fr") nslcd: [d062c2] <authc="seb"> DEBUG: ldap_result(): end of results (0 total) nslcd: [d062c2] <authc="seb"> uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr: lookup failed: No results returned nslcd: [d062c2] <authc="seb"> DEBUG: ldap_unbind() nslcd: [d062c2] <authc="seb"> DEBUG: myldap_search(base="dc=unix,dc=ch-havre,dc=fr", filter="(&(objectClass=shadowAccount)(uid=seb))") nslcd: [d062c2] <authc="seb"> DEBUG: ldap_result(): uid=seb,ou=Users,dc=unix,dc=ch-havre,dc=fr Sebastien
{ "language": "en", "url": "https://stackoverflow.com/questions/47388441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prioritize two change events in select element I have two change events handler for one select elemet. Let's call the functions Func1 and Func2. When I initialize these handlers I do the Func1 and then Func2 but when the change event happens in select element the Func2 get called before Func1. Is there any way to prioritize this two functions. Just to let you know the initializations for each function is in different scripts. This is the layout of my code Script1: $("select#myDropdownlist").change(function(){ $(this).parents('form:first').submit(); // form submit sends post request to update an object which is in session } Script2: $("select#myDropdownlist").change(function(){ Send an ajax request and return json result based on the changes happened to the object in script1 function } Although I initialized these by sequence it doesn't call the function in order. Because it calls Func2 first the object is not updated yet so result is not correct, it will then call Func1 and object will be updated which is too late as the Func2 has already returned the result based on previous version of object. Please also note that Script1 is very generic and it's supposed to work for any form data entry page, where the Script2 is specific to a particular page and I want to do an extra thing once the select element is changed only in a page. This means I cannot call Func2 inside Func2. Any help would be highly appreciated Regards Behnam Divsalar A: The simple answer to order functions after an event would be to add a single event handler function that runs the 2 functions one after the other. $("select#myDropdownlist").change(function(){ callFirstFunction(); callSecondAjaxFunction(); } A: How about putting the contents of the first function in a method: $("select#myDropdownlist").change(function(){ submitPostFunction1(); } submitPostFunction1 = function() { //do function 1 stuff here } then in your more specific function - function2: $("select#myDropdownlist").change(function(){ $("select").unbind(); submitPostFunction1(); //do function 2 stuff $("select").bind("change", function() { submitPostFunction1(); }) } keep in mind that i used $("select") in function 2 because you said it was a more generic call, so that means you wont be using the id in the first function call. A: Events are not specified to fire in any specific order. If you want a specific order, you need to either invoke them from a meta handler, or chain them by calling one from the other. The meta handler is more flexible in the long run though. $("select#myDropdownlist").change(function(){ firstHandler(); secondHandler(); } or function firstHandler() { ... secondHandler(); } function secondHandler() { ... } $("select#myDropdownlist").change(firstHandler);
{ "language": "en", "url": "https://stackoverflow.com/questions/5327712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JLabel translation I have a JLabel (with an icon) and I would like to translate this JLabel when the JLabel is clicked. I have added a mouseListener to the JLabel however I didn't come up with anything on how I can execute a translation from coordinates (x, y) to cordinates (x', y') class MyMouseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e){ final JLabel label = (JLabel) e.getSource(); System.out.println("Player hit label -> " + label.getName() ); // Code for translating JLabel } } A: As far as translating (ie moving) your JLabel: First, you must make sure that the layout manager of its parent is set to null, or uses a customized layoutmanager that can be configured to do your translation. Once you have that in place, it's a simple matter: public void mouseClicked(MouseEvent ae) { JLabel src = (JLabel) ae.getSource(); src.setLocation(src.getLocation().x + delta_x, src.getLocation().y + delta_y); src.getParent().repaint(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/32996279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Checking if 2 nodes on a graph are connected recursively C# I'm trying to create a simple implementation of Depth-First Search recursively. Here is the graph I've set up, searching for a path between Node 1 and Node 5: int[][] graph = new int[5][]; graph[0] = new int[] { 1, 2 }; graph[1] = new int[] { 1, 3 }; graph[2] = new int[] { 2, 4 }; graph[3] = new int[] { 3, 4 }; graph[4] = new int[] { 4, 5 }; if (FindNode(graph, 1, 5)) { //Success } Node 1 is connected to Nodes 2 and 3, Node 2 to Node 4, Node 3 to Node 4, and Node 4 to 5. Here is the recursion method: public static Boolean FindNode(int[][] graph, int start, int end) { if (start == end) { return true; } for (int i = 0; i < graph.Length; i++) { if (graph[i][0] == start) { start = graph[i][1]; if (FindNode(graph, start, end)) { return true; } } } return false; } Essentially it's looking for the starting value in the 'left column' of the graph data, and then changes the starting node to be its associated node. The code works as intended for this graph example (i.e. it finds the path 1 -> 2 -> 4 -> 5), but when it has to go back up the recursive loop it can't find the solution (e.g. if graph[4] was {3,5}). I'm not too familiar with recursion so I'm not sure how to fix it. I'm not too concerned about optimising it to ignore previously visited nodes. I would like to return the path as a list (e.g. 1,2,4,5). Thanks A: The logic in your answer is correct but displaying the path would require you to push the successful links onto a stack or onto the beginning of a list. If you can only add to the end of a list (as is the case with trying to just Console.WriteLine each step) then you can do this without remembering (or returning) the path, but you have to be clever by building path in reverse order. (find the last step of the chain first) If you have a link from n -> end, and there is a path from start -> n. Then you can display the link from n -> end. In so determining that there is a path from start -> n, you will have displayed all those links already. using System; class Program { public static Boolean FindNode(int[][] graph, int start, int end) { if (start == end) { return true; } for (int i = 0; i < graph.Length; i++) { if (graph[i][1] == end) { if (FindNode(graph, start, graph[i][0])) { Console.WriteLine("{0} -> {1}", graph[i][0], end); return true; } } } return false; } static void Main(string[] args) { int[][] graph = new int[5][]; graph[0] = new int[] { 1, 2 }; graph[1] = new int[] { 1, 3 }; graph[2] = new int[] { 2, 4 }; graph[3] = new int[] { 3, 4 }; graph[4] = new int[] { 4, 5 }; if (FindNode(graph, 1, 5)) { //Success } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/73857783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to clear GridView while working with Firestore? The problem is that I can't refresh my gridView and when I make changes in Firestore, my gridView doesn't clear and just adds new values(images) from Firestore. I have tried lots of methods that I could find on "stackoverflow" but with no success. Maybe the problem is with ImageAdapter or with how I call addSnapshotListener, I really don't know. Right now I just want that I can refresh my gridView when data changes on Firestore, but in best case scenario I want that, when I get new values from Firestore, it only updates that part of gridView where was the image, and not the whole gridView. public class MainActivity extends AppCompatActivity { private FirebaseFirestore db; private ArrayList<Items> arrayList; private ImageAdapter imageAdapter; private GridView gridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView = findViewById(R.id.gridViewList); db = FirebaseFirestore.getInstance(); arrayList = new ArrayList<>(); //arrayList.clear(); getUrls(); imageAdapter = new ImageAdapter(MainActivity.this, arrayList); gridView.setAdapter(imageAdapter); } private void getUrls(){ gridView.setAdapter(null); db.collection("images").addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(QuerySnapshot value, FirebaseFirestoreException e) { if (e != null){ Toast.makeText(getApplicationContext(), "No images returned", Toast.LENGTH_SHORT).show(); return; } for (DocumentSnapshot document : value){ refresh(); if (document.get("imageUrl") != null){ arrayList.add(new Items(document.get("imageUrl").toString())); refresh(); } } } }); } public void refresh() { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { imageAdapter.notifyDataSetChanged(); gridView.invalidate(); } }); } public class ImageAdapter extends BaseAdapter { private ImageView imageView; private Context context; private LayoutInflater inflater; private ArrayList<Items> list; public ImageAdapter(Context context, ArrayList<Items> list){ this.context = context; this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null){ inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.image_layout, parent, false); imageView = convertView.findViewById(R.id.singleImageView); } /** https://futurestud.io/tutorials/glide-caching-basics */ Glide.with(context).load(list.get(position).getImageUrl()).apply(RequestOptions.skipMemoryCacheOf(true).centerCrop()).into(imageView); return convertView; } A: The FirebaseUI-Android/Firestore project has an adapter that does what you want. This does the heavy lifting of managing a RecyclerView for you. In order to have a layout like in GridView, you can create an instance of GridLayoutManager in onCreate and pass that to RecyclerView.setLayoutManager If you want to hack it yourself, the QuerySnapshot has a property documentChanges that you can check for REMOVED - cf. View changes between snapshots. To get an idea of how it would be implemented with a GridView you can look at the source code of RecyclerView.Adatper - epecially the notifyItemXXX methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/48694545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Run Web Application in Virtual Directory I am trying to run my web application for test purposes in a virtual directory. I have done this steps from this MS Site * *In Visual Studio, open an existing Web application project, or create a new one. *In the Project menu, click Properties, and then click Web. *Click Use Local IIS Web server. *Enter a URL for the project, and then click Create Virtual Directory. But after this configuration I get a HTTP-Error 500.19 - Internal Server Error Details: There are duplicate entries in the web.config File But the web.config file hasn't changed. Without the Virtual Directory the site is starting up as expected. any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/28234540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IO Error 22 python infile1 = open("D:/p/non_rte_header_path.txt","r") infile2 = open("D:/p/fnsinrte.txt","r") for line in infile1: for item in infile2: eachfile = open(line,"r") For the above code I am getting the below error. infile1 contains paths of may files like D:/folder/Src/em.h but here \n is automatically at the end of the path.I am not sure why it happens. Please help. IOError: [Errno 22] invalid mode ('r') or filename: 'D:/folder/Src/em.h\n' A: Everyone has provided comments telling you what the problem is but if you are a beginner you probably don't understand why it's happening, so i'll explain that. Basicly, when opening a file with python, each new line (when you press the Enter Key) is represented by a "\n". As you read the file, it reads line by line, but unless you remove the "\n", it your line variable will read thethingsonthatline\n This can be useful to see if a file contains multiple lines, but you'll want to get rid of it. Edchum and alvits has given a good way of doing this ! Your corrected code would be : infile1 = open("D:/p/non_rte_header_path.txt","r") infile2 = open("D:/p/fnsinrte.txt","r") for line in infile1: for item in infile2: eachfile = open(line.rstrip('\n'), "r")
{ "language": "en", "url": "https://stackoverflow.com/questions/31179293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jHipster - simplify generation of the new APP if the DB already exists does any tool exist that can simplify generation of the new APP if the DB already exists? I can create JDL file for new app manually base on existing DB - but I prefer to automate the process. This DB is part of old Spring Roo app. Thank you. A: The spring Roo 1.x version provides the "Database Reverse Engineering" functionality. This add-on allows you to create an application tier of JPA 2.0 entities based on the tables in your database. DBRE will also incrementally maintain your application tier if you add or remove tables and columns. After generate the entities, you could execute the necessary web mvc commands to generate the complete application. However, remember that the Spring Roo 1.x is not beeing maintained, because uses old technologies. See more about the DBRE process here: http://docs.spring.io/spring-roo/reference/html/base-dbre.html Hope it helps, A: There's a JHipster module that is being developed for this purpose: https://github.com/bastienmichaux/generator-jhipster-db-helper It is probably not ready yet but could be a good start.
{ "language": "en", "url": "https://stackoverflow.com/questions/45292041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a socket that is accessible across different networks Below I have two scripts that work when I bind the server.py to my computers IPV4 address and connect the client.py to that same address. The next step I'm trying to take is the ability to use this socket across different networks. I thought that it would be as simple as changing the value of SERVER to my public IP address (which can be found by clicking this link). When I make that change, I get this error upon running server.py: Traceback (most recent call last): File "C:\Users\gmbra\Downloads\Python Programs\Concepts\Sockets\server.py", line 13, in <module> server.bind(ADDRESS) OSError: [WinError 10049] The requested address is not valid in its context server.py import socket import threading PORT = 5050 # SERVER = '192.168.0.30' SERVER = socket.gethostbyname(socket.gethostname()) # Change this to the public IP address to allow access across multiple networks ADDRESS = (SERVER, PORT) HEADER = 64 # The number of bytes expected to get from the client FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET is the type of addresses we are looking for server.bind(ADDRESS) def handle_client(conn, address): print(f"[NEW CONNECTION] {address} connected.") while True: msg_length = conn.recv(HEADER).decode(FORMAT) # This line also blocks until it receives a message if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == DISCONNECT_MESSAGE: conn.close() break print(f'[{address}] {msg}') conn.send("Message Received".encode(FORMAT)) def start(): server.listen() print(f'[LISTENING] Server is listening on {SERVER}.') while True: conn, address = server.accept() # This line will wait until it finds a connection. thread = threading.Thread(target=handle_client, args=(conn, address)) thread.start() print(f"[ACTIVE CONNECTIONS] {threading.active_count() - 1}.") print("[STARTING] Server is starting...") start() client.py import socket HEADER = 64 PORT = 5050 FORMAT = 'utf-8' DISCONNECT_MESSAGE = '!DISCONNECT' SERVER = "192.168.0.30" ADDRESS = (SERVER, PORT) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDRESS) # The pickle module could be used to send objects instead of strings. def send(msg): message = msg.encode(FORMAT) # For some reason we have to send a byte string first with the integer size of the message, concatenated with spaces # until it hits the length of the header. send_length = str(len(message)).encode(FORMAT) send_length += b' '*(HEADER - len(send_length)) client.send(send_length) client.send(message) print(client.recv(2048).decode(FORMAT)) while True: message_ = input('Message: ') send(message_) if message_ == "!DISCONNECT": break What must I do to make this work across different networks? A: The server socket can bind only to an IP that is local to the machine it is running on (or, to the wildcard IP 0.0.0.0 to bind to all available local IPs). Clients running on the same network can connect to the server via any LAN IP/Port the server is bound to. However, when the server machine is not directly connected to the Internet, but is running behind a router/proxy, the server socket cannot bind to the network's public IP. So, for what you are attempting, you need to bind the server socket to its local LAN IP (or wildcard) and Port, and then configure the network router to port-forward inbound connections from its public WAN IP/Port to the server's private LAN IP/Port. Then, clients running on other networks can connect to your public WAN IP/Port, and then be forwarded to the server. If the router supports UPnP (Universal Play-by-play) and it is enabled, the server code can programmably setup the port forwarding rules dynamically. Otherwise, the rules need to be configured manually in the router's configuration by an admin.
{ "language": "en", "url": "https://stackoverflow.com/questions/68825572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OrientDB: How can I filter Edge by node in orientdb How can I filter the edges by node condition? Below is my query, I would like to further filter the path by ending node with id 222 SELECT $path as path FROM ( TRAVERSE bothE(),bothV() FROM (select * from Node where (id in ['111'])) WHILE $depth <= 6 ) where @rid in (select @rid from Node where (id in ['222'])) However, the query only returns one path. But I know, there are several paths.
{ "language": "en", "url": "https://stackoverflow.com/questions/50034689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: regular expressions in Java i attempted to port the code in this answer to Java: PHP VIN number validation code i understand that String.matches in Java is a bit temperamental and i'm very unfamiliar with regular expressions. here is the code: public boolean validateVIN(String vin) { vin = vin.toLowerCase(); if(!vin.matches("/^[^\\Wioq]{17}$/")) { //the offending code, always fails Log.e("vininfo", "did not pass regex"); return false; } int[] weights = { 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 }; //array positions coorespond to the 26 letters of the alphabet int[] transliterations = { 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 0, 7, 0, 9, 2, 3, 4, 5, 6, 7, 8, 9 }; int sum = 0; String checkdigit = "."; for(int i=0; i < vin.length(); i++) { //add transliterations * weight of their positions to get the sum int temp = 0; temp = vin.charAt(i); if(temp < 58) { sum += (temp-48)*weights[i]; Log.e("vinsum.num", String.valueOf(sum)); } else { sum += transliterations[temp-97]*weights[i]; Log.e("vinsum.chr", String.valueOf(sum)); } } if(checkdigit.equals("10")) { checkdigit = "x"; } else { //find checkdidgit by taking the mod of the sum checkdigit = String.valueOf(sum % 11); } Log.i("vininfo", "checkdigit: "+checkdigit+" ... VIN[8]: "+vin.substring(8,9)); return (checkdigit.equals(vin.substring(8, 9))); } anyone familiar with a proper way to use this regex in Java? A: Remove the slashes from the regex. In other words: if(!vin.matches("^[^\\Wioq]{17}$")) { A: Try this at home: class Vin { public static void main( String ... args ) { String vin = "1M8GDM9A_KP042788"; if(!vin.matches("[^\\Wioq]{17}")) { //the offending code, always fails System.out.println("vininfo did not pass regex"); } else { System.out.println("works"); } } } Prints: $java Vin works You don't need the /^ and $/
{ "language": "en", "url": "https://stackoverflow.com/questions/5021461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP Composer Autoloader Simple Structure I have Composer working and I'd like to use its autoloader to load my classes, but it's not working. Here's my directory structure. I'm keeping it really simple to start with. index.php composer.json Vendor controllers/webgl.php Inside webgl.php I have: namespace controllers; class webgl { public function lesson1() { } } In index.php I have: require('vendor/autoload.php'); //require_once('controllers/webgl.php'); $webglController = new \controllers\webgl; And my composer.json defines this for autoloading: "autoload": { "psr-4": { "controllers\\": "controllers/" } } If I uncomment the second require, the script works, otherwise I get "Fatal error: Class 'controllers\webgl' not found in /vagrant/index.php on line 5". I thought that the folder structure, class namespace and class name all conformed to psr-4. But I must be misunderstanding something. I've read loads of similar questions but none have been able to sort it for me. Can anyone tell me why my class isn't loading and what I should do to fix it? A: Did you define an autoload directive? You need to add this to your composer.json file: "autoload": { "psr-4": { "controllers\\": "controllers/" } } to point the autoloader in the right direction and then run composer update from the terminal in your project directory. Now the class will load without explicitly requiring its file. A: Make sure you run at least composer dump-autoload after making changes to your composer.json. composer install or composer update will also do it. From your question and the comments it seems like you didn't run the command after you added the autoloading definition for your own code.
{ "language": "en", "url": "https://stackoverflow.com/questions/30467332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android generic SQLite database i developed a small java.lang.reflect.InvocationHandler that intercepts method calls (from a json webservice) and cache the results to a local SQLite db. if there is no internet connection results are read from local cache. everything works fine; my problem is the following: every method intercepted can return a different entity, and i save using reflection each entity on a different table. i don't know in advance all the tables i need to create, so every time i create a SQLiteOpenHelper that "create table if not exists {ENTITY_NAME}", and every time i increase the database version by 1 so the method onUpgrade is called. this works on development environment but i don't like that at all. someone can recommend a better solution to update the database with new tables? thank you A: Try mYourDbHelper.getWritableDatabase().execSQL("CREATE TABLE ....") from where you need to create another table
{ "language": "en", "url": "https://stackoverflow.com/questions/11365452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I use extensions in incognito I wanna use python selemium incognito with extensions but none worked so far Anyone got a fix? I tried: options.add_extension('plugin.crx') #options.add_argument("--incognito") #options.add_argument("user-data-dir=C:\\Users\\Maxva\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 9") options.add_experimental_option('excludeSwitches', ['enable-logging']) driver = webdriver.Chrome(options=options) #driver.get('chrome://extensions/?id=lncaoejhfdpcafpkkcddpjnhnodcajfg') #driver.execute_script("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()") A: My favourite trick is to use the keyboard: options.add_argument("--incognito") options.add_extension('Google-Translate.crx') driver.get("chrome://extensions") time.sleep(1) action = ActionChains(driver) # Open the extension: for _ in range(2): action.send_keys(Keys.TAB).perform() action.send_keys(Keys.RETURN).perform() # Flip the switch that enables it in incognito for _ in range(4): action.send_keys(Keys.TAB).perform() action.send_keys(Keys.RETURN).perform()
{ "language": "en", "url": "https://stackoverflow.com/questions/71067430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }