| Docker Compose local directory not mounted in remote deployment Posted: 18 Apr 2021 08:22 AM PDT I'm using docker-compose (on windows) to bring up a mongoDB along with a couple of nodeJS processes (on a remote CentOS machine via SSH). The nodeJS containers are supposed to have the code in my project directory mounted into /home/node/app so they can execute it with the command node web/run. However, when I use docker context to deploy this group of containers to my remote host via SSH, I get an error saying the script at /home/node/app/web/run is not found, suggesting my code was not copied into/mounted into the container. You can see that I'm mounting the current directory (my project) below: web: image: node:15.12.0 user: node working_dir: /home/node/app volumes: - ./:/home/node/app:ro ports: - 80:80 command: node web/run depends_on: - events-db Am I misunderstanding how volumes work in Docker? What are the best practices for getting my code into a container so it can be executed?  |
| Loops on dataframes & replace Posted: 18 Apr 2021 08:22 AM PDT I need to add a new column to my dataframe (Titanic dataset) call Range, with the range of every passenger on the Titanic, following this table: Kids 11 years Young 18 years Adult 50 years Old 50 years I created a new column and full it with NaN. Then, I have tried a loop to itinerate the age and replace the value of the column, but the column fills all the rows with 'Adult'. Why can this be happening? for i in df["Age"]: if (i < 11.0): df['Range'].replace(['NaN'],'Niño') elif (i < 18.0): df['Range'].replace(['NaN'],'Joven') elif (i < 50.0): df['Range'].replace(['NaN'],'Adulto') elif (i >= 50.0): df['Range'].replace(['NaN'],'Mayor') Thanks a lot!  |
| How to check if a letter is greater another letter in JS Posted: 18 Apr 2021 08:22 AM PDT I am trying to work out an efficient way on how to determine how you can check if a letter is greater than another letter in Javascript. for example, I want to check if K is greater than J in the alphabet. return true if it is.  |
| Get the invalid yup item's index from error Posted: 18 Apr 2021 08:22 AM PDT I'm currently processing a form with Formik and Yup that contains more than 700 complex entries. I want to print exactly the item which was affected. E.g: If item #548 was invalid, I'd like to get the item index (which should be 547) and then print it out to the user. I tried using ${path} interpolation in Yup, which almost does what I want, but I'd like to get only the index or be able to transform the output before it goes out of Yup (Or I'd have to modify the other components, and I don't want it to feel like a hack). Here's my schema: const toGradeSchema = yup.lazy((_toGrade: any) => { const toGrade = _toGrade as ToGradeInput | undefined; const isGradeSet = toGrade?.gradeId || toGrade?.section; const gradeId = yup .string() .test('gradeId', 'Debe de colocar el grado', (val?: any) => { return (!isGradeSet && !val) || (val && isGradeSet); }); const section = yup .string() .oneOf(sectionList) .test('gradeId', 'Debe de colocar la sección', (val?: any) => { return (!isGradeSet && !val) || (val && isGradeSet); }); const base = yup.object().shape({ gradeId, section, }); return base; }); const newStudentsSchema = yup.array().of( yup .object() .shape({ name: yup.object().shape({ firstName: yup .string() .required('El primer nombre es requerido ${path}'), lastName: yup.string().required('El apellido es requerido'), fullName: yup.string().notRequired(), }), email: yup .string() .email('El correo electrónico es inválido') .required('Debe de colocar un correo electrónico ${path}'), password: yup .string() .required(() => 'Debe de colocar una contraseña ${path}') .test( 'password is valid', 'La contraseña debe de contener por lo menos una letra en mayúscula, una en minúscula y al menos un dígito', (pass: string | undefined | null) => { if (!pass) { return false; } return validatePassword(pass); }, ), gender: yup.mixed().oneOf(genderValues), // The order in the attendance that must not change birthDate: yup.date().notRequired(), allergies: yup.string().notRequired(), diseases: yup.string().notRequired(), toGrade: toGradeSchema, }) .notRequired(), ); const existingStudentSchema = yup.array().of( yup.object().shape({ studentId: yup.string().required('Debe de colocar el ID del estudiante'), toGrade: toGradeSchema, }), ); export const bulkStudentCreateSchema = yup.object().shape({ students: yup.object().shape({ newStudents: newStudentsSchema, existingStudents: existingStudentSchema, }), }); Any ideas?  |
| Google API mail merge to pdf with email Posted: 18 Apr 2021 08:22 AM PDT I am working on a project The current code and document i have only send an email of what the data in the row is. I would like that the data in columns B - G be merged to a PDF and then it is sent with the email template to an email address in column H. I am currently stuck on how to add the code for creating the PDF Here is the Link to the folder with the google sheets data document FOLDER LINK below is the current code function sendEmails() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var dataSheet = ss.getSheets()[0]; var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 4); var templateSheet = ss.getSheets()[1]; var emailTemplate = templateSheet.getRange("A1").getValue(); // Create one JavaScript object per row of data. objects = getRowsData(dataSheet, dataRange); // For every row object, create a personalized email from a template and send // it to the appropriate person. for (var i = 0; i < objects.length; ++i) { // Get a row object var rowData = objects[i]; // Generate a personalized email. // Given a template string, replace markers (for instance ${"First Name"}) with // the corresponding value in a row object (for instance rowData.firstName). var emailText = fillInTemplateFromObject(emailTemplate, rowData); var emailSubject = "Tutorial: Simple Mail Merge"; MailApp.sendEmail(rowData.emailAddress, emailSubject, emailText); } } // Replaces markers in a template string with values define in a JavaScript data object. // Arguments: // - template: string containing markers, for instance ${"Column name"} // - data: JavaScript object with values to that will replace markers. For instance // data.columnName will replace marker ${"Column name"} // Returns a string without markers. If no data is found to replace a marker, it is // simply removed. function fillInTemplateFromObject(template, data) { var email = template; // Search for all the variables to be replaced, for instance ${"Column name"} var templateVars = template.match(/\$\{\"[^\"]+\"\}/g); // Replace variables from the template with the actual values from the data object. // If no value is available, replace with the empty string. for (var i = 0; i < templateVars.length; ++i) { // normalizeHeader ignores ${"} so we can call it directly here. var variableData = data[normalizeHeader(templateVars[i])]; email = email.replace(templateVars[i], variableData || ""); } return email; } ////////////////////////////////////////////////////////////////////////////////////////// // // The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects' // tutorial. // ////////////////////////////////////////////////////////////////////////////////////////// // getRowsData iterates row by row in the input range and returns an array of objects. // Each object contains all the data for a given row, indexed by its normalized column name. // Arguments: // - sheet: the sheet object that contains the data to be processed // - range: the exact range of cells where the data is stored // - columnHeadersRowIndex: specifies the row number where the column names are stored. // This argument is optional and it defaults to the row immediately above range; // Returns an Array of objects. function getRowsData(sheet, range, columnHeadersRowIndex) { columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1; var numColumns = range.getEndColumn() - range.getColumn() + 1; var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns); var headers = headersRange.getValues()[0]; return getObjects(range.getValues(), normalizeHeaders(headers)); } // For every row of data in data, generates an object that contains the data. Names of // object fields are defined in keys. // Arguments: // - data: JavaScript 2d array // - keys: Array of Strings that define the property names for the objects to create function getObjects(data, keys) { var objects = []; for (var i = 0; i < data.length; ++i) { var object = {}; var hasData = false; for (var j = 0; j < data[i].length; ++j) { var cellData = data[i][j]; if (isCellEmpty(cellData)) { continue; } object[keys[j]] = cellData; hasData = true; } if (hasData) { objects.push(object); } } return objects; } // Returns an Array of normalized Strings. // Arguments: // - headers: Array of Strings to normalize function normalizeHeaders(headers) { var keys = []; for (var i = 0; i < headers.length; ++i) { var key = normalizeHeader(headers[i]); if (key.length > 0) { keys.push(key); } } return keys; } // Normalizes a string, by removing all alphanumeric characters and using mixed case // to separate words. The output will always start with a lower case letter. // This function is designed to produce JavaScript object property names. // Arguments: // - header: string to normalize // Examples: // "First Name" -> "firstName" // "Market Cap (millions) -> "marketCapMillions // "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored" function normalizeHeader(header) { var key = ""; var upperCase = false; for (var i = 0; i < header.length; ++i) { var letter = header[i]; if (letter == " " && key.length > 0) { upperCase = true; continue; } if (!isAlnum(letter)) { continue; } if (key.length == 0 && isDigit(letter)) { continue; // first character must be a letter } if (upperCase) { upperCase = false; key += letter.toUpperCase(); } else { key += letter.toLowerCase(); } } return key; } // Returns true if the cell where cellData was read from is empty. // Arguments: // - cellData: string function isCellEmpty(cellData) { return typeof(cellData) == "string" && cellData == ""; } // Returns true if the character char is alphabetical, false otherwise. function isAlnum(char) { return char >= 'A' && char <= 'Z' || char >= 'a' && char <= 'z' || isDigit(char); } // Returns true if the character char is a digit, false otherwise. function isDigit(char) { return char >= '0' && char <= '9'; } THANK YOU. I HOPE YOU WILL ASSIST ME  |
| x86 ASM: useless conditional jump? Posted: 18 Apr 2021 08:21 AM PDT I am looking at the following piece of x86 assembly code (Intel syntax): movzx eax, al and eax, 3 cmp eax, 3 ja loc_6BE9A0 In my understanding, this should equal something like this in C: eax &= 0xFF; eax &= 3; if (eax > 3) loc_6BE9A0(); This does not seem to make much sense since this condition will never be true (because eax will never be greater than 3 if it got and-ed with 3 before). Am I missing something here or is this really just an unnecessary condition? And also: the movzx eax, al should not be necessary either if it gets and-ed with 3 right after that, is it? I am asking this because I am not so familiar with assembly language and so I am not entirely sure if I am missing something here.  |
| Error during execution of npx react-native run-android Posted: 18 Apr 2021 08:21 AM PDT I am quite new to React native. I was trying to run the emulator but it shows "failed to launch emulator" and I am not sure how to resolve the error. What am I supposed to do to resolve the error? .................................................................................................................................................................................................................. D:\hiban_work\react\AwesomeProject>npx react-native run-android info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag. Jetifier found 903 file(s) to forward-jetify. Using 4 workers... info Starting JS server... 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. info Launching emulator... 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. 'C:\Users\Hanim' is not recognized as an internal or external command, operable program or batch file. error Failed to launch emulator. Reason: Could not start emulator within 30 seconds.. warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch. info Installing the app... Starting a Gradle Daemon (subsequent builds will be faster) > Task :app:checkDebugDuplicateClasses FAILED > :app:checkDebugAarMetadata > Resolve files of 16 actionable tasks: 14 executed, 2 up-to-date FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:checkDebugDuplicateClasses'. > Could not resolve all files for configuration ':app:debugRuntimeClasspath'. > Failed to transform swiperefreshlayout-1.0.0.aar (androidx.swiperefreshlayout:swiperefreshlayout:1.0.0) to match attributes {artifactType=enumerated-runtime-classes, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}. > Execution failed for AarToClassTransform: C:\Users\Hanim Omer\.gradle\caches\modules-2\files-2.1\androidx.swiperefreshlayout\swiperefreshlayout\1.0.0\4fd265b80a2b0fbeb062ab2bc4b1487521507762\swiperefreshlayout-1.0.0.aar. > error in opening zip file * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 4m 56s error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081 FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:checkDebugDuplicateClasses'. > Could not resolve all files for configuration ':app:debugRuntimeClasspath'. > Failed to transform swiperefreshlayout-1.0.0.aar (androidx.swiperefreshlayout:swiperefreshlayout:1.0.0) to match attributes {artifactType=enumerated-runtime-classes, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}. > Execution failed for AarToClassTransform: C:\Users\Hanim Omer\.gradle\caches\modules-2\files-2.1\androidx.swiperefreshlayout\swiperefreshlayout\1.0.0\4fd265b80a2b0fbeb062ab2bc4b1487521507762\swiperefreshlayout-1.0.0.aar. > error in opening zip file * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 4m 56s at makeError (D:\hiban_work\react\AwesomeProject\node_modules\execa\index.js:174:9) at D:\hiban_work\react\AwesomeProject\node_modules\execa\index.js:278:16 at processTicksAndRejections (node:internal/process/task_queues:94:5) at async runOnAllDevices (D:\hiban_work\react\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:5) at async Command.handleAction (D:\hiban_work\react\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:186:9) info Run CLI with --verbose flag for more details.  |
| javascript object property assignment between different objects Posted: 18 Apr 2021 08:21 AM PDT I read a snippet and confusing and could not find the rules or principle to explain that,the output is Malibu,why not London,the adress: sherlock.address in let john = { surname: 'Watson', address: sherlock.address }; is to assign the value ofsherlock.adress to john.address,but not overwrite sherlock.adresswithjohn.address.How could I fiddle my hair. let sherlock = { surname: 'Holmes', address: { city: 'London' } }; let john = { surname: 'Watson', address: sherlock.address }; john.surname = 'Lennon'; john.address.city = 'Malibu'; console.log(sherlock.address.city); //  |
| Quartz scheduler not working when i host the application on iis with c# Posted: 18 Apr 2021 08:21 AM PDT I have created an application which is web form application.I am using Quartz.net. In that I have class RequestToken which is as follows ***public partial class RequestToken : System.Web.UI.Page { public void Page_Load(object sender, EventArgs e) { Method1(); Method2(); } public void Method1() { } public void Method2() { } } public class job : IJob { public void Execute(IJobExecutionContext context) { RequestToken rs = new RequestToken(); rs.Page_Load(null, EventArgs.Empty); } }*** Then I have another class Jobsceduler.cs ***public class JobScheduler { public static void Start() { IScheduler scheduler = (IScheduler)StdSchedulerFactory.GetDefaultScheduler(); scheduler.Start(); IJobDetail Jobs = JobBuilder.Create<job>().Build(); ITrigger trigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(10,00)) ) .Build(); scheduler.ScheduleJob(Jobs, trigger); } } and in Global.asax void Application_Start(object sender, EventArgs e) { JobScheduler.start(); }*** Scheduler runs perfectly on given time Issues in above code 1)It runs two times in local that is first on pageload() and second time after scheduler runs. - when hosted on iis it requires classname to append to the url means the site should be like this "www.site.com/RequestToken.aspx" is it due to I have single page in my application that is RequestToken.aspx?
Should i need to remove the pageLoad() from the above code? should I need to add default.aspx and move the above code in that page to host in IIS? Can anybody please provide the solution .  |
| Limit maximum number of items in array jsonschema Posted: 18 Apr 2021 08:20 AM PDT I have a json-schema (draft-07) of type array to store multiple types of data like { "$schema": "http://json-schema.org/draft-07/schema#", "type": "array", "items": { "type": "object", "required": [ "type", "data" ], "additionalProperties": false, "properties": { "type": { "type": "string", "enum": [ "banner_images", "description_box", "button" ] }, "data": { "type": "object" } }, "allOf": [ { "if": { "properties": { "type": { "const": "banner_images" } } }, "then": { "properties": { "data": { "$ref": "components/banner_images.json" } } } }, { "if": { "properties": { "type": { "const": "description_box" } } }, "then": { "properties": { "data": { "$ref": "components/description_box.json" } } } }, { "if": { "properties": { "type": { "const": "button" } } }, "then": { "properties": { "data": { "$ref": "components/button.json" } } } } ] } } Which validates the following data [ { "type": "banner_images", "data": { "images": [ { "url": "https://example.com/image.jpg" } ] } }, { "type": "description_box", "data": { "text": "Description box text" } }, { "type": "button", "data": { "label": "Click here", "color": { "label": "#ff000ff", "button": "#00ff00", "border": "#00ff00" }, "link": "https://example.com" } } ] As of now, the user can provide any number of the components from banner_images, description_box, and button. I want to limit each component based on the component type - banner_images -> 1
- description_box -> 5
- button -> 10
There is an option to set the length of the items in array type https://json-schema.org/understanding-json-schema/reference/array.html#id7 But how can I limit the length of the items based on the type?  |
| How can a thread in a critical region experiences an unhandled exception? Posted: 18 Apr 2021 08:20 AM PDT I'm reading a book which says: A thread that is in a critical region is a thread that has entered a thread synchronization lock that must be released by the same thread. When a thread is in a critical region, the CLR believes that the thread is accessing data that is shared by multiple threads in the same AppDomain. After all, this is probably why the thread took the lock. If the thread is accessing shared data, just terminating the thread isn't good enough, because other threads may then try to access the shared data that is now corrupt, causing the AppDomain to run unpredictably or with possible security vulnerabilities. So, when a thread in a critical region experiences an unhandled exception, the CLR first attempts to upgrade the exception to a graceful AppDomain unload in an effort to get rid of all of the threads and data objects that are currently in use. my question is, how can a thread in a critical region experiences an unhandled exception? Because when the thread entered a lock, the thead is suspended and waits for other thread to release the lock, if the thread is at idle(suspended), it doesn't execute any code, then how it is going to experience an unhandled exception?  |
| How I can provide callback functions inside a Runnable that affects the Current activity Posted: 18 Apr 2021 08:20 AM PDT I have the following class: package com.example.vodafone_fu_h300s.logic; import com.example.vodafone_fu_h300s.logic.exceptions.CsrfTokenNotFound; import com.example.vodafone_fu_h300s.logic.exceptions.SettingsFailedException; import com.example.vodafone_fu_h300s.logic.lambdas.ExceptionHandler; import com.example.vodafone_fu_h300s.logic.lambdas.LoginHandler; import com.example.vodafone_fu_h300s.logic.lambdas.RetrieveSettingsHandler; import com.example.vodafone_fu_h300s.logic.lambdas.SettingsRetrievalFailedHandler; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import java.util.regex.Pattern; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.FormBody.Builder; import java.security.MessageDigest; public class Η300sCredentialsRetriever { private String url; private OkHttpClient httpClient; private String username; private String password; private LoginHandler loginHandler; private ExceptionHandler exceptionHandler; private RetrieveSettingsHandler settingsHandler; private SettingsRetrievalFailedHandler failedHandler; private String session_id; public Η300sCredentialsRetriever() { this.exceptionHandler = (Exception e)->{}; this.loginHandler = (boolean loginStatus)->{}; this.settingsHandler = (H300sVoipSettings settings)->{}; this.failedHandler = ()->{}; this.setHttpClient(new OkHttpClient()); } public void setSettingsHandler(RetrieveSettingsHandler handler){ this.settingsHandler = handler; } public void setFailedHandler(SettingsRetrievalFailedHandler handler){ this.failedHandler = handler; } public void setExceptionHandler(ExceptionHandler handler){ this.exceptionHandler= handler; } public void setLoginHandler(LoginHandler handler){ this.loginHandler=handler; } public void setUrl(String url){ url = "http://"+url.replaceAll("http(s?)://",""); this.url = url; } public String getUrl(){ return this.url; } public void setHttpClient(OkHttpClient client) { this.httpClient = client; } public void setUsername(String username){ this.username = username.trim(); } public void setPassword(String password){ this.password = password.trim(); } public String getSessionId() { return this.session_id; } public String retrieveCSRFTokenFromHtml(String htmlPageUrl) throws IOException { if(htmlPageUrl==null || htmlPageUrl.trim().equals("")){ return ""; } Pattern csrfRegex = Pattern.compile("var csrf_token\\s*=\\s*'.+'"); Matcher match = csrfRegex.matcher(htmlPageUrl); if(match.find()){ String matched = match.group(); matched=matched.replaceAll("var|csrf_token|'|\\s|=",""); return matched; } return ""; } public String retrieveUrlContents(String url, String csrfToken, String referer) throws Exception { url = this.url.replaceAll("/$","")+"/"+url.replaceAll("^/",""); csrfToken=(csrfToken == null)?"":csrfToken; if(!csrfToken.equals("")){ long unixtime = System.currentTimeMillis() / 1000L; // AJAX Calls also require to offer the _ with a unix timestamp alongside csrf token url+="?_="+unixtime+"&csrf_token="+csrfToken; } Request.Builder request = new Request.Builder() .url(url) .header("User-Agent","Mozila/5.0 (X11;Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0") .header("Accept","text/html,application/xhtml+html;application/xml;q=0.9,image/webp,*/*;q=0.8") .header("Upgrade-Insecure-Requests","1") .header("Sec-GPC","1"); String session_id = this.getSessionId(); session_id = session_id==null?"":session_id; if(!session_id.equals("")){ request.header("Cookie","login_uid="+Math.random()+"; session_id="+session_id); } referer = (referer==null)?"":referer; if(!referer.trim().equals("")){ request.header("Referer",referer); } Response response = this.httpClient.newCall(request.build()).execute(); int code = response.code(); if( code != 200){ throw new Exception("The url "+url+" returned code "+code); } String responseBody = response.body().string(); return responseBody; } public String retrieveUrlContents(String url, String csrfToken) throws Exception { return retrieveUrlContents(url,csrfToken,""); } public String retrieveUrlContents(String url) throws Exception { return retrieveUrlContents(url,""); } public String retrieveCsrfTokenFromUrl(String url,String referer) throws CsrfTokenNotFound { try { String html = retrieveUrlContents(url,"",referer); return retrieveCSRFTokenFromHtml(html); } catch (Exception e) { exceptionHandler.handle(e); throw new CsrfTokenNotFound(url); } } public boolean login() { if( username == null || username.equals("") || password == null || password.equals("")){ return false; } try { this.session_id = null; String token = this.retrieveCsrfTokenFromUrl("/login.html",null); if(token == null){ return false; } if(token.trim().equals("")){ return false; } String challengeJson = this.retrieveUrlContents("/data/login.json"); if(challengeJson == null){ return false; } if(challengeJson.trim().equals("")){ return false; } JSONObject json = (JSONObject) (new JSONArray(challengeJson)).get(0); String challenge = json.getString("challenge"); if(challenge == null){ return false; } if(challenge.trim().equals("")){ return false; } MessageDigest md = MessageDigest.getInstance("SHA-256"); String stringToDigest = password+challenge; byte []hash = md.digest(stringToDigest.getBytes(StandardCharsets.UTF_8)); BigInteger number = new BigInteger(1, hash); StringBuilder hexString = new StringBuilder(number.toString(16)); String loginPwd = hexString.toString(); RequestBody requestBody = new Builder() .add("LoginName", username) .add("LoginPWD", loginPwd) .add("challenge",challenge) .build(); long unixTime = System.currentTimeMillis() / 1000L; Request request = new Request.Builder() .url(this.url+"/data/login.json?_="+unixTime+"&csrfToken="+token) .post(requestBody) .header("Cookie","login_uid="+Math.random()) .header("Referer","http://192.158.2.1/login.html") .header("X-Requested-With","XMLHttpRequest") .header("Content-Type","application/x-www-form-urnencoded; charset=UTF-8") .header("User-Agent","Mozila/5.0 (X11;Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0") .header("Origin","http://192.168.2.1") .build(); Call call = this.httpClient.newCall(request); Response response = call.execute(); String responseString = response.body().string(); String cookies = response.header("Set-Cookie"); if(cookies == null || cookies.trim().equals("")){ return false; } cookies=cookies.replaceAll("path=/|session_id=|;",""); this.session_id=cookies; return responseString.equals("1"); } catch (Exception e){ exceptionHandler.handle(e); return false; } } public H300sVoipSettings retrieveVOIPSettings() throws Exception { H300sVoipSettings settings; String csrfToken = retrieveCsrfTokenFromUrl("/overview.html",this.url+"/login.html"); if(csrfToken == null || csrfToken.trim().equals("")){ throw new SettingsFailedException(); } String contents = retrieveUrlContents("/data/phone_voip.json",csrfToken,this.url+"/phone.html"); if(contents == null || contents.trim().equals("")){ throw new SettingsFailedException(); } try{ settings = H300sVoipSettings.createFromJson(contents); } catch (Exception e){ this.exceptionHandler.handle(e); throw new SettingsFailedException(); } return settings; } public void retrieveVoipCredentials() { try { boolean loginStatus = login(); loginHandler.loginCallback(loginStatus); if (loginStatus) { H300sVoipSettings settings = retrieveVOIPSettings(); settingsHandler.retrieveSettings(settings); } } catch (SettingsFailedException f){ failedHandler.handler(); exceptionHandler.handle(f); } catch (Exception e){ exceptionHandler.handle(e); } } } That its main purpoce it to perform a sequence of HttpCalls and retrieve the voip credentials of an H300s Sercomm router. This class is run from the following activity: package com.example.vodafone_fu_h300s.screens; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.text.TextWatcher; import com.example.vodafone_fu_h300s.R; import com.example.vodafone_fu_h300s.logic.H300sVoipSettings; import com.example.vodafone_fu_h300s.logic.Η300sCredentialsRetriever; import kotlin.reflect.KFunction; public class ConnectIntoRouterActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher { private CredentialsRetriever retriever; private EditText url; private EditText admin; private EditText password; private Button submit; private class CredentialsRetriever extends Η300sCredentialsRetriever implements Runnable { private ConnectIntoRouterActivity activity; public CredentialsRetriever(ConnectIntoRouterActivity activity) { super(); this.activity = activity; this.setExceptionHandler((Exception e) -> { Log.e("Η300s",ConnectIntoRouterActivity.class+e.getMessage()); }); this.setLoginHandler((boolean loginStatus)->{ if(!loginStatus){ Log.e("Η300s",ConnectIntoRouterActivity.class+" Login Failed"); this.activity.getSubmit().setEnabled(true); } }); this.setSettingsHandler((H300sVoipSettings settings)->{ this.activity.getSubmit().setEnabled(true); Intent displaySettings = new Intent(this.activity, DisplaySettingsActivity.class); displaySettings.putExtra("settings",settings); startActivity(displaySettings); }); } public void run() { this.retrieveVoipCredentials(); } } public Button getSubmit() { return this.submit; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_connect_into_router); Intent activityIntent = getIntent(); String menu_url = activityIntent.getStringExtra("router_url"); Button submit = (Button)findViewById(R.id.connect_btn); submit.setOnClickListener(this); this.submit = submit; this.retriever = new CredentialsRetriever(this); this.url = (EditText)findViewById(R.id.menu_url); url.setText(menu_url); url.addTextChangedListener(this); this.admin = (EditText)findViewById(R.id.username); admin.setText("admin"); admin.addTextChangedListener(this); this.password = (EditText)findViewById(R.id.password); password.addTextChangedListener(this); } private void onUpdateForm() { String menu_url = this.url.getText().toString(); String admin = this.admin.getText().toString(); String password = this.password.getText().toString(); if(menu_url.equals("")||admin.equals("")||password.equals("")){ Button submit = (Button)findViewById(R.id.connect_btn); submit.setEnabled(false); return; } Button submit = (Button)findViewById(R.id.connect_btn); submit.setEnabled(true); this.retriever.setUrl(menu_url); this.retriever.setUsername(admin); this.retriever.setPassword(password); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { onUpdateForm(); } @Override public void onClick(View v){ Button submit = (Button)findViewById(R.id.connect_btn); submit.setEnabled(false); Thread thread = new Thread(this.retriever); thread.start(); } } But once I press submit on the following form that activity renders:  I get the following error: class com.example.vodafone_fu_h300s.screens.ConnectIntoRouterActivityOnly the original thread that created a view hierarchy can touch its views. I also tried the following: package com.example.vodafone_fu_h300s.screens; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.text.TextWatcher; import com.example.vodafone_fu_h300s.R; import com.example.vodafone_fu_h300s.logic.H300sVoipSettings; import com.example.vodafone_fu_h300s.logic.Η300sCredentialsRetriever; import kotlin.reflect.KFunction; public class ConnectIntoRouterActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher { private CredentialsRetriever retriever; private EditText url; private EditText admin; private EditText password; private Button submit; private class CredentialsRetriever extends Η300sCredentialsRetriever implements Runnable { private ConnectIntoRouterActivity activity; public CredentialsRetriever(ConnectIntoRouterActivity activity) { super(); this.activity = activity; this.setExceptionHandler((Exception e) -> { Log.e("Η300s",ConnectIntoRouterActivity.class+e.getMessage()); }); this.setLoginHandler((boolean loginStatus)->{ if(!loginStatus){ Log.e("Η300s",ConnectIntoRouterActivity.class+" Login Failed"); this.activity.getSubmit().setEnabled(true); } }); this.setSettingsHandler((H300sVoipSettings settings)->{ this.activity.getSubmit().setEnabled(true); Intent displaySettings = new Intent(this.activity, DisplaySettingsActivity.class); displaySettings.putExtra("settings",settings); startActivity(displaySettings); }); } public void run() { this.retrieveVoipCredentials(); } } public Button getSubmit() { return this.submit; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_connect_into_router); Intent activityIntent = getIntent(); String menu_url = activityIntent.getStringExtra("router_url"); Button submit = (Button)findViewById(R.id.connect_btn); submit.setOnClickListener(this); this.submit = submit; this.retriever = new CredentialsRetriever(this); this.url = (EditText)findViewById(R.id.menu_url); url.setText(menu_url); url.addTextChangedListener(this); this.admin = (EditText)findViewById(R.id.username); admin.setText("admin"); admin.addTextChangedListener(this); this.password = (EditText)findViewById(R.id.password); password.addTextChangedListener(this); } private void onUpdateForm() { String menu_url = this.url.getText().toString(); String admin = this.admin.getText().toString(); String password = this.password.getText().toString(); if(menu_url.equals("")||admin.equals("")||password.equals("")){ Button submit = (Button)findViewById(R.id.connect_btn); submit.setEnabled(false); return; } Button submit = (Button)findViewById(R.id.connect_btn); submit.setEnabled(true); this.retriever.setUrl(menu_url); this.retriever.setUsername(admin); this.retriever.setPassword(password); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { onUpdateForm(); } @Override public void onClick(View v){ Button submit = (Button)findViewById(R.id.connect_btn); submit.setEnabled(false); runOnUiThread(this.retriever); } } But I get the following error: E/Η300s: class com.example.vodafone_fu_h300s.screens.ConnectIntoRouterActivityOnly the original thread that created a view hierarchy can touch its views. So how I can run an thread and provide Callbacks for any event such as In case that an error occurs of an Event for example a sucessfull credentials retrieval?  |
| Is it possible to upload folder with Paramiko? Posted: 18 Apr 2021 08:20 AM PDT I'm trying to upload a folder from my local pc to my synology NAS with SSH and Paramiko. It's working perfectly for files, but not for folders. Here is my code : # imports import paramiko import os # connection variables ip_address = "xxx.xxx.xxxx.xxx" username = "xxxxxxxx" password = "xxxxxx" local_user = os.getenv("USERNAME") # session Windows variable remote_path = f"/homes/lmeyer/{local_user}" # absolute remote path print(remote_path) local_path = "d:" # absolute local path print(local_path) # SSH connection ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=ip_address,username=username,password=password) print("Connection OK >", ip_address) # SFTP connection sftp = ssh_client.open_sftp() # folder creation with the Windows session variable sftp.mkdir(remote_path) # folder upload on the server sftp.put(f"{local_path}/images",f"{remote_path}/imgs") sftp.close() ssh_client.close() If I try to upload toto.txt with : sftp.put(f"{local_path}/toto.txt",f"{remote_path}/toto2.txt") it works perfectly. But if I try to do it as expected in my code, it give me a permission error : Traceback (most recent call last): File "D:\Programmation\Python\RecupData\RecupData.py", line 23, in <module> sftp.put(f"{local_path}/images",f"{remote_path}/imgs") File "C:\Users\Louis\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\sftp_client.py", line 758, in put with open(localpath, "rb") as fl: PermissionError: [Errno 13] Permission denied: 'd:/images' Is there a fix to get folders uploading ? Thanks a lot  |
| Missing required parameters for [Route: Kategori.destroy] [URI: Model/Kategori/{Kategori}] Posted: 18 Apr 2021 08:20 AM PDT I use the resource route all sections are successful only on route Category.destroy this is not successful. after I overcome the white screen appears  |
| My sh script always run after entrypoint DOCKERFILE Posted: 18 Apr 2021 08:22 AM PDT I tried to set up a wordpress solution (installing by myself and not using an official image). I have one container with apache, php and mariadb-client (to interrogate mariadb-server from another container) I have another container with mariadb on it. I use wp-cli to configure wordpress website but when i build my docker image, I can't execute the command (inside sh file) which is wp core config --allow-root --dbname=$MYSQL_DATABASE --dbuser=$MYSQL_USER --dbpass=$MYSQL_PASSWORD --dbhost=172.20.0.2 --dbprefix=wp --path=/var/www/html/wordpress because my mariadb container isn't up. So I tried to run this script with entrypoint parameters and when I do my docker-compose up, my script is played and I have the message: apache-php_SDV | Success: Generated 'wp-config.php' file. apache-php_SDV | Error: The 'wp-config.php' file already exists. My script is played every second, I tried to use CMD before and it doesn't work, it's like CMD wasn't run I have the same result if I want to put CMD after ENTRYPOINT, I can run my script only when both containers are up. I also tried to use command on my docker-compose.yml but not helpful. Does anyone have a solution?  |
| Laravel Error - Controller not found, but it is there Posted: 18 Apr 2021 08:21 AM PDT I kept getting this error  As you guys can see I have that file in my project.  I also tried restarting my local MAMP server and clear the cache php artisan view:clear php artisan route:clear php artisan cache:clear php artisan config:clear I also did ⚡️ mybabies composer dumpauto Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi Discovered Package: facade/ignition Discovered Package: fideloper/proxy Discovered Package: fruitcake/laravel-cors Discovered Package: laravel/sail Discovered Package: laravel/tinker Discovered Package: nesbot/carbon Discovered Package: nunomaduro/collision Package manifest generated successfully. Generated optimized autoload files containing 4683 classes Please let me know what else I can do. route Route::get('/', function(){ return Redirect::to('/baby/signin'); }); Route::get('/baby/signin','BabyAccountController@signin');  |
| firebase - Log in again after the user has registered for the first time Posted: 18 Apr 2021 08:21 AM PDT Hi everyone I have such a problem, After a user signs up for my site, for the first time, I want to log in with the user one more time. I want that after he registers, connect again. I tried to do it asynchronously, but it does not always work, sometimes I try to log in before the user is registers, I do not know why it does not work. I want there to be a login only after registration, to force it. handleSubmit = async () => { const newUserData = { email: 'test@mail.com', password: '123456', confirmPassword: '123456', handle: 'test' }; await signupUser(newUserData); await signinChat(newUserData); } export const signupUser = (newUserData) => (dispatch) => { axios .post('/signup', newUserData) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }); }; //basically call to this function to signup exports.signup = (req, res) => { const newUser = { email: req.body.email, password: req.body.password, confirmPassword: req.body.confirmPassword, handle: req.body.handle, }; db.doc(`/users/${newUser.handle}`) .get() .then((doc) => { if (doc.exists) { return res.status(400).json({ handle: "this handle is already taken" }); } else { return firebase .auth() .createUserWithEmailAndPassword(newUser.email, newUser.password); } }) .then((data) => { userId = data.user.uid; return data.user.getIdToken(); }) .then((idToken) => { token = idToken; const userCredentials = { handle: newUser.handle, email: newUser.email, }; const userPreferences = { handle: newUser.handle }; return db.doc(`/users/${newUser.handle}`).set(userCredentials); }) .then(() => { return res.status(201).json({ token }); }) .catch((err) => { console.error(err); if (err.code === "auth/email-already-in-use") { return res.status(400).json({ email: "Email is already is use" }); } else { return res .status(500) .json({ general: "Something went wrong, please try again" }); } }); }; export const signinChat = (user) => { return async (dispatch) => { const db = firebase.firestore(); firebase.auth() .signInWithEmailAndPassword(user.email, user.password) .then(data => { console.log(data); const currentUser = firebase.auth().currentUser; const name = `${user.handle}`; currentUser.updateProfile({ displayName: name, }) .then(() => { db.collection('users') .doc(data.user.displayName) .update({ isOnline: true, }) .then(() => { const loggedInUser = { handle: user.handle, uid: data.user.uid, email: user.email } localStorage.setItem('user', JSON.stringify(loggedInUser)); console.log('User logged in successfully...!'); }) .catch(error => { console.log(error); }); }); }) .catch(error => { console.log(error); }) } }  |
| R package "feather" give me error "Error in check_dots_empty(action = signal) : unused argument (action = signal)" Posted: 18 Apr 2021 08:23 AM PDT I start getting a very strange error from the "feather" package in R: Let say I write and read file write_feather(mtcars, 'm') read_feather('m') The last one gives me Error in check_dots_empty(action = signal) : unused argument (action = signal) I reinstalled the package, restarted sessions, and still have no idea how to fix it. R version 3.6.1 (2019-07-05) Please, help me  |
| Why does an IF condition with no statements inside removes the border of an element? Posted: 18 Apr 2021 08:22 AM PDT I can't tell if this is a bug or not. function moncheck() { if($(".mon").attr("style", "border")) { } $(this).attr("style", "border: 1px solid red") } $(".mon").on("click", moncheck) .mon { width:100px; margin: 5px; } .mon:hover { border: 1px solid; cursor: pointer; } <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <link rel="stylesheet" href="jquery-ui-1.12.1.custom/jquery-ui.min.css"> <script src="jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script> <script src="jquery-ui-1.12.1.custom/jquery-ui.min.js"></script> <div id="monlist"> <img src="https://cloudinary-a.akamaihd.net/ufn/image/upload/u7cdzxvxu69pmubmtltc.jpg" class="mon"> <img src="https://fyf.tac-cdn.net/images/products/large/F-898.jpg" class="mon"> <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/close-up-of-tulips-blooming-in-field-royalty-free-image-1584131616.jpg?crop=0.630xw:1.00xh;0.186xw,0&resize=640:*" class="mon"> </div> As you can see, the if condition has no statements, and you click on an image, it gets a red border, then when you click on another image, what is expected to happen is for that second image to also get a red border, and now both images should have a red border, since at no point was the border of the first image removed. Yet, it does get removed because of the if condition. If you go ahead and comment out the if condition, you will see that the border remains on all images as you click. Why? Example: function moncheck() { imgurl = this.src; //if($(".mon").attr("style", "border")) { //} $(this).attr("style", "border: 1px solid red") } $(".mon").on("click", moncheck) .mon { width:100px; margin: 5px; } .mon:hover { border: 1px solid; cursor: pointer; } <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <link rel="stylesheet" href="jquery-ui-1.12.1.custom/jquery-ui.min.css"> <script src="jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script> <script src="jquery-ui-1.12.1.custom/jquery-ui.min.js"></script> <div id="monlist"> <img src="https://cloudinary-a.akamaihd.net/ufn/image/upload/u7cdzxvxu69pmubmtltc.jpg" class="mon"> <img src="https://fyf.tac-cdn.net/images/products/large/F-898.jpg" class="mon"> <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/close-up-of-tulips-blooming-in-field-royalty-free-image-1584131616.jpg?crop=0.630xw:1.00xh;0.186xw,0&resize=640:*" class="mon"> </div> This does not happen if I use css, instead of attr. if($(".mon").css("border")) { } This will result in each img retaining the border. Why? And another behavior I can't explain is the removal of the hover effect when I remove the border on click. function moncheck() { if($(".mon").css("border")) { $(".mon").css("border", "none") } $(this).css("border", "1px solid red") } $(".mon").on("click", moncheck) .mon { width:100px; margin: 5px; } .mon:hover { border: 1px solid; cursor: pointer; } <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <link rel="stylesheet" href="jquery-ui-1.12.1.custom/jquery-ui.min.css"> <script src="jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script> <script src="jquery-ui-1.12.1.custom/jquery-ui.min.js"></script> <div id="monlist"> <img src="https://cloudinary-a.akamaihd.net/ufn/image/upload/u7cdzxvxu69pmubmtltc.jpg" class="mon"> <img src="https://fyf.tac-cdn.net/images/products/large/F-898.jpg" class="mon"> <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/close-up-of-tulips-blooming-in-field-royalty-free-image-1584131616.jpg?crop=0.630xw:1.00xh;0.186xw,0&resize=640:*" class="mon"> </div> As you can see, when I use css to remove the border, the hover effect is removed as well. Why? The hover should not be removed.  |
| Tailwind css height issue Posted: 18 Apr 2021 08:21 AM PDT When I navigate to Shop route, this screen has created a white space at the top of the page. <div className="h-screen bg-black text-white flex flex-col text-center justify-center items-center uppercase "> <div className="text-2xl md:text-3xl lg:text-4xl font-bold mb-3"> shop coming soon </div> <Link to="/" className="whitespace-nowrap text-base border-solid border-white border-b-2" > go back to home page </Link> </div> Can anyone tell me how to resolve and explain why?   |
| 2d Fourier Transforms: FFT vs Fourier Optics Posted: 18 Apr 2021 08:21 AM PDT I am trying to use programming to increase my understanding of Fourier optics. I know that physically and mathematically the Fourier transform of a Fourier transform is inverted -> F{F{f(x)} = f(-x). I am having two problems 1) The second transform doesn't return anything like the original function except in the simple gaussian case (which makes it even more confusing), and 2) there seems to be some scaling factor that requires me to "zoom in" and distort the transformed image to a point that it is much less helpful (as illustrated below).  #%% Playing with 2d Fouier Transform import numpy as np from scipy import fftpack import matplotlib.pyplot as plt import LightPipes wavelength = 792*nm size = 15*mm N = 600 w0=3*mm # Fields sq = np.zeros([100,100]) sq[25:75, 25:75] = 1 F=Begin(size,wavelength,N) I0 = Intensity(0,GaussBeam(F, w0, LG=True, n=0, m=0)) I1 = Intensity(0,GaussBeam(F, w0, LG=False, n=0, m=1))+Intensity(0,GaussBeam(F, w0, LG=False, n=1, m=0)) # Plot transforms f = sq F = np.fft.fftshift(fftpack.fft2(f)) F_F = np.fft.fftshift(fftpack.fft2(np.abs(F))) plt.subplot(331), plt.imshow(f) plt.title(r'f'), plt.xticks([]), plt.yticks([]) plt.subplot(332), plt.imshow(np.abs(F)) plt.title(r'F\{f\}'), plt.xticks([]), plt.yticks([]) plt.subplot(333), plt.imshow(np.abs(F_F)) plt.title('F\{F\{f\}\}'), plt.xticks([]), plt.yticks([]) f = I0 F = np.fft.fftshift(fftpack.fft2(f)) F_F = np.fft.fftshift(fftpack.fft2(np.abs(F))) plt.subplot(334), plt.imshow(f) plt.title(r'f'), plt.xticks([]), plt.yticks([]) plt.subplot(335), plt.imshow(np.abs(F)) plt.title(r'F\{f\}'), plt.xticks([]), plt.yticks([]) plt.subplot(336), plt.imshow(np.abs(F_F)) plt.title('F\{F\{f\}\}'), plt.xticks([]), plt.yticks([]) f = I1 F = np.fft.fftshift(fftpack.fft2(f)) F_F = np.fft.fftshift(fftpack.fft2(np.abs(F))) plt.subplot(337), plt.imshow(f) plt.title(r'f'), plt.xticks([]), plt.yticks([]) plt.subplot(338), plt.imshow(np.abs(F)) plt.title(r'F\{f\}'), plt.xticks([]), plt.yticks([]) plt.subplot(339), plt.imshow(np.abs(F_F)) plt.title('F\{F\{f\}\}'), plt.xticks([]), plt.yticks([]) plt.tight_layout() plt.show()  |
| SCRAPY PAGINATION: Infinite Scrolling Pagination Posted: 18 Apr 2021 08:20 AM PDT I'm trying to fetch the data from the website. I have managed to scrape the data from the first page of the website. But for the next page website loads data using AJAX, for that, I set headers but couldn't able to get the data from the next page. If we send requests to the website without headers the same data we get. So maybe I didn't set headers in the right way to move to the next page. I used CRUL for headers. Where I did wrong?  class MenSpider(scrapy.Spider): name = "MenCrawler" allowed_domains = ['monark.com.pk'] #define headers and 'custom_constraint' as page headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36', 'accept-language': 'en-PK,en-US;q=0.9,en;q=0.8', 'key':'274246071', 'custom_constraint':'custom-filter page=1', 'view' : 'ajax', '_':'1618681277011' } #send request def start_requests(self): yield scrapy.Request( url = 'https://monark.com.pk/collections/t-shirts', method = 'GET', headers=self.headers, callback=self.update_headers ) #response def update_headers(self,response): #extract all the 12 URLS from the page urls = response.xpath('//h4[@class="h6 m-0 ff-main"]/a/@href').getall() for url in urls: yield response.follow(url=url, callback=self.parse) #extract the infinite text as 'LOADING' load = response.xpath('//div[@class="pagination"]//span/text()').get() #Use if Condition for pagination if load == 'LOADING': page = 1 #define page no as key form dictionary key = self.headers['custom_constraint'] current_page = key.split('=')[-1] next_pag = page+int(current_page) filters = 'custom-filter page='+str(next_pag) self.headers['custom_constraint'] = filters #request againg to page for next page BUT THIS IS NOT WORKING FOR ME yield scrapy.Request( url = 'https://monark.com.pk/collections/t-shirts', method = 'GET', headers=self.headers, callback=self.update_headers ) def parse(self, response): ........  |
| PHP - feedback form not working on the site [closed] Posted: 18 Apr 2021 08:20 AM PDT I have a feedback form on my site which isn't working in the sense that I can fill it out and it seems to be connecting to the DB but the info doesn't go through the DB, I'm not sure where I'm going wrong. Below is the DB connections using PHP <div> <?php require_once('config.php'); echo isset($_POST['create']); if(isset($_POST['create'])){ $qone = $_PSOT['qone']; $qtwo = $_PSOT['qtwo']; $qthree = $_PSOT['qthree']; $qfour = $_PSOT['qfour']; $message = $_POST['message']; $sql = "INSERT INTO feedbackform (qone , qtwo , qthree , qfour , message) VALUES (?,?,?,?,?)"; $stmtinsert = $db->prepare($sql); $names=array( $qone , $qtwo , $qthree , $qfour , $message); $result = $stmtinsert->execute($names); if ($result){ echo 'successfully saved'; }else { echo 'there were errors'; } //echo $qone , " " , $qtwo , " " , $qthree , " " , $qfour , " " , $message ; } ?> </div>  |
| Ruby: bracket notation for immediate call of returned procedure Posted: 18 Apr 2021 08:21 AM PDT In Ruby, when I'm doing an immediate callback of a returned Proc, I normally use #call: def multiplier(factor) Proc.new { |number| factor * number } end puts multiplier(10).call(5) # 50 But I've just run across this bracket shorthand, which has the same result as far as I can see: def multiplier(factor) Proc.new { |number| factor * number } end puts multiplier(10)[5] # 50 This strikes me as very similar to JavaScript's immediate call of a returned function: const multiplier = (factor) => (number) => factor * number; console.log(multiplier(10)(5)); // 50 But I've never seen the syntax before, and I can't seem to find it documented anywhere. Is this just syntax sugar for using #call, or is there more to it? And I can't seem to find any doc on it. Is there some somewhere?  |
| How To Crop An Image Following Its Outline Border With Python Posted: 18 Apr 2021 08:21 AM PDT I basically have thousands of images of characters with black outlines, all of these images either have a white background or some graphic background, usually just a wood texture behind. What I want is to create a function (opencv/pil/whatever) that will allow me to just autocrop these images, basically remove everything outside the character's outline.  On The left is the original, uncropped image, on the right is the cropped image. Is this even possible?  |
| Spring Webflux Webclient Blocks on SSL Connection Posted: 18 Apr 2021 08:22 AM PDT Blockhound detected a blocking call in WebClient for an SSL connection, specifically at java.io.FileInputStream.readBytes(FileInputStream.java) where, I believed, it read the trust store for CA certificates. Does WebClient have an alternative/fix to this? Or, this is not an issue? Thanks I am using Adopt JDK 1.8.0-275 and Spring Boot 2.3.2.RELEASE Update 1 I tried the suggestion in https://github.com/reactor/reactor-netty/issues/1550, WebClient.builder().clientConnector(new ReactorClientHttpConnector(HttpClient.create().compress(true).secure())).build(); but it didn't work as expected. I didn't the other suggestion to use SslContext instead of SslContextBuilder because I don't know how to do it.  |
| Pyinstaller gives Fatal error failed to execute script bot Posted: 18 Apr 2021 08:21 AM PDT Fatal error The program works fine as a Python script (.py file) but doesn't work when I convert it to a Windows Executable file (.exe file) using Pyinstaller. Pyinstaller keeps giving me the error: Fatal error detected. Failed to execute script bot. I looked at some other posts but they didn't help me. Note: I did pyinstaller -w -F --onefile bot.py.  |
| How to devise this solution to Non-Constructible Change challenge from Algoexpert.io Posted: 18 Apr 2021 08:22 AM PDT I'm working through algoexpert.io coding challenges and I'm having trouble undersatnding the suggested solution to one of the questions titled Non-Constructible Change Here's the challenge question: Given an array of positive integers representing the values of coins in your possession, write a function that returns the minimum amount of change (the minimum sum of money) that you cannot create. The given coins can have any positive integer value and aren't necessarily unique (i.e., you can have multiple coins of the same value). For example, if you're given coins = [1, 2, 5], the minimum amount of change that you can't create is 4. If you're given no coins, the minimum amount of change that you can't create is 1. // O(nlogn) time, O(n) size. function nonConstructibleChange(coins) { coins = coins.sort((a, b) => a - b); // O(nlogn) time operation let change = 0; for (coin of coins) { if (coin > change + 1) return change + 1; change += coin; } return change + 1; } My problem I am not completely sure how did the author of the solution come up with the intuition that if the current coin is greater than `change + 1`, the smallest impossible change is equal to `change + 1`. I can see how it tracks, and indeed the algorithm passes all tests, but I'd like to know more about a process I could use to devise this rule. Thank you for taking the time to read the question!  |
| Typescript - flat a JSON model using Class-transformer Posted: 18 Apr 2021 08:20 AM PDT I am trying to use the class transformer in typescript (node.js): https://github.com/typestack/class-transformer I would like to flat a JSON using only 1 model , 1 Dto that will go to the DB if I have the following json : { "data":{"test":"123"} "name":"x" } the DB service should receive the following object: { "test":"123", "name":"x" } This what I tried to define but it's not working : @Expose() export class Dto{ name:string, @Expose({name: "data.test"}) test: string } the result on the test field is undefined how can I achieve that? I don't want to create a "mediator" model  |
| How to set null for DateTimePicker Posted: 18 Apr 2021 08:21 AM PDT I'm using DateTimePicker(@react-native-community/datetimepicker). How to set null as default value for DateTimePicker? Because in the first time , value of DateTimePicker should be null. When I set it to null ,get the following error : Invariant Violation: A date or time should be specified as 'value'. <DateTimePicker testID="dateTimePicker" timeZoneOffsetInMinutes={0} value={null} mode='date' is24Hour={true} display="default" onChange={onChange} />  |
No comments:
Post a Comment