How do i find locations of a word in a sentence in objective c? Posted: 14 Feb 2022 10:48 AM PST How do i find locations of a specific word in a sentence in objective c? Lets say i have the following NSString NSString *stringOfHashTags = "mr#hello Mr.#hello" I am using NSString word=@"hello"; NSRange termsRange = [stringOfHashTags rangeOfString:[word substringFromIndex:[word rangeOfString:@"#"].location]]; to find the location of a word that starts with # but if the word exists two or more times in the sentence it only returns the first location. Any help appreciated. |
possibly speed up matrix multiplications in loop Posted: 14 Feb 2022 10:48 AM PST I asked a question here with the details: https://math.stackexchange.com/questions/4381785/possibly-speed-up-matrix-multiplications In short, I am trying to create a P x N matrix, X, with typical element: \sum_{j,k;j,k \neq i} w_{jp} A_{jk} Y_{kp}, where w is P x N, A is N x N and Y is P x N. See the link above for a markup version of that formula. I'm providing a mwe here to see how I can correct the code (the calculations seem correct, just incomplete see below) and more importantly speed this up however possible: w = np.matrix([[2,1,0],[3,7,0.5]]) A = np.matrix([[2,1,0],[9,0,8],[1,2,5]]) Y = np.matrix([[6,2,-1],[11,8,-7]]) N=w.shape[1] P=w.shape[0] X = np.zeros((P, N)) for p in range(P) : for i in range(N-1): for j in range(N-1): X[p,i] = np.delete(w,i,1)[i,p]*np.delete(np.delete(A,i,0),i,1)[i,j]*np.delete(Y.T,i,0)[j,p] The output looks like: array([[ -2. , 0. ], [-56. , 0.]]) If we set (i,p) = to the (1,1) element of X_{ip}, the value can be understood using the formula provided above: sum_{j,k;j,k \neq i} w_{j1} A_{jk} Y_{k1} = w_12 A_22 Y_12 = 1 * -1 * 2 = -2 as it is in the output. the (1,2) element of X_{ip} should be: sum_{j,k;j,k \neq i} w_{j2} A_{jk} Y_{k2} = w_22 A_22 Y_22 = 7 * -1 * 8 = -56 as it is in the output. But I am not getting the correct answer for the final column of X because my range is to (N-1) not N because I received an IndexError out of bounds when it is N . More importantly, here N=P=2, but I have large N and P and the code, as is, takes a very long time to run. Any suggestions would be greatly appreciated. |
How do I hide file paths after running c++ code in VS Code? Posted: 14 Feb 2022 10:48 AM PST After building and running my c++ program,every time it just shows things that I would like not to show. Here's what it's showing me: "PS C:\Users\Mark\source\repos\1> &'c:\Users\Mark.vscode\extensions\ms-vscode.cpptools-1.8.4\debugAdapters\bin\WindowsDebugLauncher.exe' '--stdin=Microsoft-MIEngine-In-ta2kewy2.cn1' '--stdout=Microsoft-MIEngine-Out-qv5pglbb.dak' '--stderr=Microsoft-MIEngine-Error-ldagpyaf.4fq' '--pid=Microsoft-MIEngine-Pid-3j5kfycx.05f' '--dbgExe=C:/msys64/mingw64/bin/gdb.exe' '--interpreter=mi'" Is there any way to remove that and just have only this ? PS C:\Users\Mark\source\New Folder\1> |
HttpRequest to Azure DevOps using the AzureDevOps connector in Power apps - canvas Posted: 14 Feb 2022 10:48 AM PST Im trying to make a http-request through the HttpRequest method on the AzureDevOps connector. The parameters are i feel like i have tried every combination of formatting but still get errors. Specificly on the last part {Headers:Table; Body:Text; IsBase64:Boolean}. Im making a GET request but i seems like the last params are requried. |
Folllow Up - XML parse to PHP Posted: 14 Feb 2022 10:48 AM PST I have 2 separate sections of code that I'd like to combine. This is the first section, I would like to get the information from the first record only using curl. $channel_id = $_GET["goChannelId"]; $feed = curl_get_contents("https://www.youtube.com/feeds/videos.xml?channel_id=$channel_id"); $xml = new SimpleXmlElement($feed); $count = count($xml->entry); for ($i=0; $i < 1; $i++) { $url = $xml->entry[$i]->link->attributes(); I appreciated that I got a response from member Auirio. It also works great. Where I need assistance using his code together. This is the code provided as the answer, explaining that the namespace is required. $xml = simplexml_load_file('./feed.xml','SimpleXMLElement',LIBXML_NONET|LIBXML_COMPACT|LIBXML_NOBLANKS); $ns = $xml->getNamespaces(true); foreach($ns as $prefix=>$namespace){ $xml->registerXPathNamespace($prefix,$namespace); } print_r($xml->xpath('//media:statistics')); The print outputs as an array. Can this be converted to just an echo value? how to get namespace into the first section ( curl) along with the other entry (non-media node). Having no knowledge can I get help getting these as echo code: <entry> echo title echo published </entry> <media:group> <media:thumbnail url echo url </media:group> <media:community> <media:starRating count echo count <media:statistics views echo views </media:community> This is a sample of the XML: https://www.youtube.com/feeds/videos.xml?channel_id=UCDkcjwvWxUqWUmkDEIQrkuQ Any help is appreciated |
Postman return dat, but WebResponse freezing on server Posted: 14 Feb 2022 10:47 AM PST I'm trying to get a json string via WebRequest using the code below (it tries to call a file that will return the json for me which is in the application). It worked on my machine but when I deployed to the user server, I got the error the operation is timed out When I test through a postman it returns the data. The problem comes with WebResponse when it needs to get the data, but depending on the timeout it hits it every time. I set the link to request.Timeout = 30 minutes, 1 hour, 3 days, but each time it reaches WebResponse and does not go through. WebResponse response = request.GetResponse(); On my computer when I test it works, it slowly takes the data, but it works. When I test it on the server it freezing to WebResponse. I tried with other URLs again it doesn't work. In the URL I can write a filter to get my first 500 entries and then everything is OK, but when I want to get all it fails. All records are about 30,000 I tried to with ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3 or ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; or ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls ; |
How to put paragraph into svg background Posted: 14 Feb 2022 10:47 AM PST how can i put some paragraphs into a SVG file? Thanks [ |
PYTHON FOR ANDROID USING KIVY got big error Posted: 14 Feb 2022 10:48 AM PST please help me I am trying to convert kivy python program file to android > Warning: Failed to download any source lists! > Installed packages:=====================] ١٠٠% Computing updates... > Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '-' > at java.base/java.util.Formatter.checkText(Formatter.java:2732) > at java.base/java.util.Formatter.parse(Formatter.java:2718) > at java.base/java.util.Formatter.format(Formatter.java:2655) > at java.base/java.io.PrintStream.format(PrintStream.java:1053) > at java.base/java.io.PrintStream.printf(PrintStream.java:949) > at com.android.sdklib.tool.sdkmanager.TableFormatter.print(TableFormatter.java:72) > at com.android.sdklib.tool.sdkmanager.ListAction.printList(ListAction.java:182) > at com.android.sdklib.tool.sdkmanager.ListAction.execute(ListAction.java:73) > at com.android.sdklib.tool.sdkmanager.SdkManagerCli.run(SdkManagerCli.java:103) > at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:80) > at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48) > # Command failed: /home/alawiii/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager > --sdk_root=/home/alawiii/.buildozer/android/platform/android-sdk --list > # ENVIRONMENT: > # ANDROID_HOME = '/opt/android-sdk' > # COLORFGBG = '15;0' > # COLORTERM = 'truecolor' > # DBUS_SESSION_BUS_ADDRESS = 'unix:path=/run/user/1000/bus' > # DESKTOP_SESSION = 'plasma' > # DISPLAY = ':0' > # D_DISABLE_RT_SCREEN_SCALE = '1' > # GTK2_RC_FILES = '/etc/gtk-2.0/gtkrc:/home/alawiii/.gtkrc-2.0:/home/alawiii/.config/gtkrc-2.0' > # GTK3_MODULES = 'xapp-gtk3-module' > # GTK_MODULES = 'canberra-gtk-module' > # GTK_RC_FILES = '/etc/gtk/gtkrc:/home/alawiii/.gtkrc:/home/alawiii/.config/gtkrc' > # HOME = '/home/alawiii' > # KDE_APPLICATIONS_AS_SCOPE = '1' > # KDE_FULL_SESSION = 'true' > # KDE_SESSION_UID = '1000' > # KDE_SESSION_VERSION = '5' > # KONSOLE_DBUS_SERVICE = ':1.458' > # KONSOLE_DBUS_SESSION = '/Sessions/1' > # KONSOLE_DBUS_WINDOW = '/Windows/1' > # KONSOLE_VERSION = '211202' > # LANG = 'en_US.UTF-8' > # LANGUAGE = 'en_US:ar' > # LC_ADDRESS = 'ar_JO.UTF-8' > # LC_COLLATE = 'en_US.UTF-8' > # LC_CTYPE = 'ar_JO.UTF-8' > # LC_IDENTIFICATION = 'ar_JO.UTF-8' > # LC_MEASUREMENT = 'en_US.UTF-8' > # LC_MESSAGES = 'ar_JO.UTF-8' > # LC_MONETARY = 'en_US.UTF-8' > # LC_NAME = 'ar_JO.UTF-8' > # LC_NUMERIC = 'en_US.UTF-8' > # LC_PAPER = 'ar_JO.UTF-8' > # LC_TELEPHONE = 'ar_JO.UTF-8' > # LC_TIME = 'en_US.UTF-8' > # LOGNAME = 'alawiii' > # MAIL = '/var/spool/mail/alawiii' > # MOTD_SHOWN = 'pam' > # PAM_KWALLET5_LOGIN = '/run/user/1000/kwallet5.socket' > # PATH = '/home/alawiii/.buildozer/android/platform/apache-ant-1.9.4/bin:/home/alawiii/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/opt/android-sdk/platform-tools:/opt/android-sdk/tools:/opt/android-sdk/tools/bin:/var/lib/flatpak/exports/bin:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/var/lib/snapd/snap/bin' > # PROFILEHOME = '' > # PWD = '/home/alawiii/PycharmProjects/pythonProject/KIVY_PR/New_Folder' > # QT_AUTO_SCREEN_SCALE_FACTOR = '0' > # QT_LINUX_ACCESSIBILITY_ALWAYS_ON = '1' > # SAL_USE_VCLPLUGIN = 'gen' > # SESSION_MANAGER = 'local/alawiii-linux:@/tmp/.ICE-unix/48246,unix/alawiii-linux:/tmp/.ICE-unix/48246' > # SHELL = '/bin/bash' > # SHELL_SESSION_ID = '19439f6a76884520b8630c7a13919994' > # SHLVL = '1' > # SYSTEMD_EXEC_PID = '1348' > # TERM = 'xterm-256color' > # USER = 'alawiii' > # WINDOWID = '98566151' > # XAUTHORITY = '/home/alawiii/.Xauthority' > # XCURSOR_SIZE = '24' > # XCURSOR_THEME = 'Vimix-cursors' > # XDG_CONFIG_DIRS = '/home/alawiii/.config/kdedefaults:/etc/xdg' > # XDG_CURRENT_DESKTOP = 'KDE' > # XDG_DATA_DIRS = '/home/alawiii/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share:/usr/share:/var/lib/snapd/desktop' > # XDG_RUNTIME_DIR = '/run/user/1000' > # XDG_SEAT = 'seat0' > # XDG_SEAT_PATH = '/org/freedesktop/DisplayManager/Seat0' > # XDG_SESSION_CLASS = 'user' > # XDG_SESSION_DESKTOP = 'KDE' > # XDG_SESSION_ID = '5' > # XDG_SESSION_PATH = '/org/freedesktop/DisplayManager/Session3' > # XDG_SESSION_TYPE = 'x11' > # XDG_VTNR = '1' > # OLDPWD = '/home/alawiii/PycharmProjects/pythonProject/KIVY_PR/New_Folder' > # LESS_TERMCAP_mb = '\x1b[01;32m' > # LESS_TERMCAP_md = '\x1b[01;32m' > # LESS_TERMCAP_me = '\x1b[0m' > # LESS_TERMCAP_se = '\x1b[0m' > # LESS_TERMCAP_so = '\x1b[01;47;34m' > # LESS_TERMCAP_ue = '\x1b[0m' > # LESS_TERMCAP_us = '\x1b[01;36m' > # LESS = '-R' > # PKGFILE_PROMPT_INSTALL_MISSING = '1' > # LS_OPTIONS = '--color=auto' > # LS_COLORS = 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.webp=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:' > # P9K_SSH = '0' > # P9K_TTY = 'old' > # _P9K_TTY = '/dev/pts/3' > # _ = '/home/alawiii/.local/bin/buildozer' > # > # Buildozer failed to execute the last command > # The error might be hidden in the log above this error > # Please read the full log, and search for it before > # raising an issue with buildozer itself. > # In case of a bug report, please add a full log with log_level = 2 I followed this instruction but didn't help: https://quadropoly.com.au/kivy-and-admob-for-android-api-27/ |
Regex to match/replace leading tabs without lookbehind Posted: 14 Feb 2022 10:48 AM PST I am trying to match each \t in the leading whitespace of a line so I can replace them with two spaces. This is trivial with an unbounded (i.e., variable-length) lookbehind. text.replace(/(?<=^\s*)\t/gm, ' ') Unfortunately, this code is running on iOS, and for some reason, Safari and iOS have yet to implement lookbehinds, let alone unbounded lookbehinds. I know there are workarounds for lookbehinds, but I can't seem to get the ones I've looked at to work. I would rather not capture any characters aside from each tab, but if there's no other way, I could capture characters around the tabs in capture groups and add $1 , etc, to my replacement string. Example test code const text = ` \t\ta \t b \t \t c\td \te ` const expected = ` a b c\td \te ` // throws error in iOS, which does not support lookbehinds // const regex = /(?<=^\s*)\t/gm; const regex = /to-do/gm; const result = text.replace(regex, ' ') console.log(`Text: ${text}`) console.log(`Expected: ${expected}`) console.log(`Result: ${result}`) console.log(JSON.stringify([ expected, result ], null, 2)) if (result === expected) { console.info('Success! 😃') } else { console.error('Failed 😞') } Update A less than ideal workaround would be to use two regexes and a replacer function. const text = ` \t\ta \t b \t \t c\td \te ` const expected = ` a b c\td \te ` const result = text.replace(/^\s*/gm, m => m.replace(/\t/g, ' ')) if (result === expected) { console.info('Success! 😃') } else { console.error('Failed 😞') } Again, less than ideal. I'm a purist. |
Check string elements in an array to manipulate Posted: 14 Feb 2022 10:47 AM PST I have the following array returning from a service indexLabelServices = [ ' Pear', ' Apple', ' Banana',' Peach',' Orange',' Cherry' ] For each element of the array i want to give a different label ( translation ) This is my code const convertServicesLabels = (indexLabelServices) => { let label=""; for (let index = 0; index < indexLabelServices.length; ++index) { const element = indexLabelServices[index]; if(element === " Pear){ label=Pera; }else if(element ===" Apple"){ label=Mela; }else if(element ===" Banana"){ label=Platano; }else if(element ===" Peach"){ label=Pesca }else if(element ===" Orange"){ label=Arancia; }else if(element ===" Cherry"){ label=Ciliegia; } } return label; } The result i have with this method is that the only the element Orange is translated to Arancia , not others element get transalated. What am i doing wrong? How can i manipulate/translate any element of the array indexLabelServices ? |
How can i avoid the Binding error and get the code right Posted: 14 Feb 2022 10:48 AM PST |
Counting String Values in Pivot Across Multiple Columns Posted: 14 Feb 2022 10:47 AM PST I'd like to use Pandas to pivot a table into multiple columns, and get the count of their values. In this example table: LOCATION | ADDRESS | PARKING TYPE | AAA0001 | 123 MAIN | LARGE LOT | AAA0001 | 123 MAIN | SMALL LOT | AAA0002 | 456 TOWN | LARGE LOT | AAA0003 | 789 AVE | MEDIUM LOT | AAA0003 | 789 AVE | MEDIUM LOT | How do I pivot out this table to show total counts of each string within "Parking Type"? Maybe my mistake is calling this a "pivot?" Desired output: LOCATION | ADDRESS | SMALL LOT | MEDIUM LOT | LARGE LOT | AAA0001 | 123 MAIN | 1 | 0 | 1 | AAA0002 | 456 TOWN | 0 | 0 | 1 | AAA0003 | 789 AVE | 0 | 2 | 0 | Currently, I have a pivot going, but it is only counting the values of the first column, and leaving everything else as 0s. Any guidance would be amazing. Current Code: pivot = pd.pivot_table(df, index=["LOCATION"], columns=['PARKING TYPE'], aggfunc=len) pivot = pivot.reset_index() pivot.columns = pivot.columns.to_series().apply(lambda x: "".join(x)) |
error trying to create order in paypal with guzzle and laravel Posted: 14 Feb 2022 10:48 AM PST I am trying to create an order in paypal with laravel and guzzle and it throws me this error: GuzzleHttp\Exception\ClientException Client error: POST https://api-m.sandbox.paypal.com/v2/checkout/orders resulted in a 400 Bad Request response: {"name":"INVALID_REQUEST","message":"Request is not well-formed, syntactically incorrect, or violates schema.","debug_id (truncated...) my controller code: $accessToken = $this->getAccessToken(); $client = new Client(['base_uri' => 'https://api-m.sandbox.paypal.com/v2/checkout/']); $headers = [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $accessToken, ]; $params = [ 'intent' => 'CAPTURE', 'purchase_units' => [ 'amount' => [ 'currency_code' => 'USD', 'value' => '100.00' ] ] ]; //dd($params); $response = $client->request('POST', 'orders', [ 'headers' => $headers, 'form_params' => $params ]); |
How to use if, then statements in R? Posted: 14 Feb 2022 10:49 AM PST I am learning R and looking to distinguish if a specific family member in my dataset is under the age of 18 at the time of testing. I want to be able to check the year of birth if a participant meets certain criteria, and my thought was to do an if statement. I'm not sure if this is the best way to go about it. Example dataframe: # sample dataframe data <- data.frame( ID = c(1, 2, 3, 4), relationship = c(1, 4, 6, 2, 5), relatechild = c(2, 8, 9, 4), year_dob = c(1994, 2001, 1987, 2005) ) I want to create a column in a new dataframe that prints the 'year_dob' if 'relationship' is 3:6 and 'relatechild' is 7:9. I was thinking this might be an option but ideally would print as a new column with the birth year, only if it meets the criteria. if(data$relationship = 3:6 && data$relatechild = 7:9) print(data$year_dob) |
Powershell: How to access iterated object in catch-block Posted: 14 Feb 2022 10:47 AM PST I'm trying to simplify the situation as much as possible. I have a set of files in that needs to be processed in a certain order because some of them are dependant on each other. But I don't have any reliable means to find out if a file has its dependencies fullfilled before processing it. - What i do have is an external function that throws an error if I try to process a file too early. Thats why I'm trying to iterate though those files until all of them have been processed. (those files contain so called "extensions" if you wonder about the variable names.) What I'm trying to do is, catching the Files that are not able to get published to the server, yet in the "catch" area and start the while loop over with the remaining set until all files are processed or the script reached its deadloop limiter of 20 loops. $path = 'C:\abcd' $ExtList = (Get-ChildItem $path -Filter '*.app' -Recurse).FullName $i = 0 #stop deadloop while (($ExtList.Count -gt 0) -and ($i -lt 20)) { $i++ [array]$global:FailedExt = @() [array]$global:FailedExtError = @() $ExtList | % { try { Publish-Extension -Path $_ } catch { $global:FailedExt += $_ $global:FailedExtError += $Error[0] } } #Set ExtList to list of remaining Extensions $ExtList = $global:FailedExt } if ($global:FailedExt.Count -gt 0) { #dependencies weren't the Problem $ErrorMsg = "Could not publish the following Extensions:`n`n" for ($i = 0; $i -lt $FailedExt.Count; $i++) { $ErrorMsg += "Error in: " + ($global:FailedExt[$i]) + ":`n" $ErrorMsg += " - Error: " + ($global:FailedExtError[$i]) + "`n`n" } throw $ErrorMsg } MY Problem: Apparently the value of $_ in the catch-block isn't the same as in the try-block because i get This error output: Could not publish the following Extensions: Error in: Cannot bind parameter 'Path' to the target. Exception setting "Path": "Illegal characters in path.": - Error: Cannot bind parameter 'Path' to the target. Exception setting "Path": "Illegal characters in path." Error in: Cannot bind parameter 'Path' to the target. Exception setting "Path": "Illegal characters in path.": - Error: Cannot bind parameter 'Path' to the target. Exception setting "Path": "Illegal characters in path." Error in: Cannot bind parameter 'Path' to the target. Exception setting "Path": "Illegal characters in path.": - Error: Cannot bind parameter 'Path' to the target. Exception setting "Path": "Illegal characters in path." And then, on the second iteration, the script tries to use the Error-Message as a Path to the file I'm trying to publish. - Which results in a set of "illegal characters in path"-Messages. p.s. If you know any other improvements to my code, let me know (I'm new to PS) |
Numpy scalable diagonal matrices Posted: 14 Feb 2022 10:49 AM PST Assuming I have the variables: A = 3 B = 2 C = 1 How can i transform them into diagonal matrices in the following form: np.diag([1, 1, 1, 0, 0, 0]) Out[0]: array([[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) np.diag([0,0,0,1,1,0]) Out[1]: array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]]) np.diag([0,0,0,0,0,1]) Out[2]: array([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1]]) I would like this to be scalable, so for instance with 4 variables a = 500, b = 20, c = 300, d = 200 the size of the matrix will be 500 + 20 + 300 + 200 = 1020 . What is the easiest way to do this? |
Scala TwoSum can't get Array[Int] Posted: 14 Feb 2022 10:48 AM PST can you please halp me with my solution. I write some method it get some Array[Int], and target and find summ Example: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. def twoSum(nums: Array[Int], target: Int) : Array[Int] = { val numSorted = nums.sorted for (i <- 0 until numSorted.length) { for (j <- i + 1 until numSorted.length) { val l = numSorted(i) + numSorted(j) if (l == target) { Array(nums.indexOf(numSorted(i)), nums.indexOf(numSorted(j))) } } } } val nums = Array(2, 7, 11, 15) val target = 9 twoSum(nums,target) my code is worked without method twoSum , but when I put it into method it get ERROR type mismatch; found : Unit required: Array[Int] |
Select data across multiple token parsers Posted: 14 Feb 2022 10:48 AM PST I'm working on a feature to allow string subtraction like so: "Hello" - "l" = "Heo" . I want to be able to quantify the removals like so: "Hello" - "l:1" = "Helo" . So my thought is that each individual character without a quantifier implies all (e.g "l" implies "l:*" ) . Characters can also be grouped "Hello" - "{el}" = "Hlo" where here {el} becomes {el}:* , so you can use a quantifier on a grouping too. This means I need to be able to accurately parse "Hello" - "elo" (e:* l:* o:*) or "Hello" - "{He}:1l:1o" ({He}:1 l:1 o:*) . public static class StringSubtractionTokenizer { private static Tokenizer<SyntaxToken> Tokenizer { get; } = new TokenizerBuilder<SyntaxToken>() .Match(Character.EqualTo('{'), SyntaxToken.OpenCurlyBrace) .Match(Character.EqualTo('}'), SyntaxToken.CloseCurlyBrace) .Match(Character.EqualTo(':'), SyntaxToken.Colon) .Match(Character.EqualTo('*'), SyntaxToken.Asterisk) .Match(Numerics.Natural, SyntaxToken.Number) .Match(Character.AnyChar, SyntaxToken.Character) .Build(); public static Result<TokenList<SyntaxToken>> TryTokenize(string source) => Tokenizer.TryTokenize(source); } public class StringSubtractionValue : Expression { public StringSubtractionValue(char[] values, int quantity) { Values = values; Quantity = quantity; } public char[] Values { get; } public int Quantity { get; } } public class StringSubtractionParser { private static TokenListParser<SyntaxToken, StringSubtractionValue> Character { get; } = Token.EqualTo(SyntaxToken.Character) .Select(c => new StringSubtractionValue(c.Span.ToString().ToCharArray(), 0)); private static TokenListParser<SyntaxToken, StringSubtractionValue> QuantifiedCharacter { get; } = Token.EqualTo(SyntaxToken.Character) .Then(character => Token.EqualTo(SyntaxToken.Colon) .Then(_ => Token.EqualTo(SyntaxToken.Number).Or(Token.EqualTo(SyntaxToken.Asterisk)) .Select(quantity => new StringSubtractionValue(character.Span.ToString().ToCharArray(), quantity.Span.ToString() == "*" ? 0 : int.Parse(quantity.Span.ToString()))))); private static TokenListParser<SyntaxToken, StringSubtractionValue> CharacterGroup { get; } = Token.EqualTo(SyntaxToken.OpenCurlyBracket) .Then(_ => Token.EqualTo(SyntaxToken.Character).AtLeastOnce() .Then(characters => Token.EqualTo(SyntaxToken.CloseCurlyBracket) .Select(_ => new StringSubtractionValue(characters.Select(c => c.Span.ToString().ToCharArray().FirstOrDefault()).ToArray(), 0)))); private static TokenListParser<SyntaxToken, StringSubtractionValue> QuantifiedCharacterGroup { get; } = Token.EqualTo(SyntaxToken.OpenCurlyBracket) .Then(_ => Token.EqualTo(SyntaxToken.Character).AtLeastOnce() .Then(characters => Token.EqualTo(SyntaxToken.CloseCurlyBracket) .Then(_ => Token.EqualTo(SyntaxToken.Colon) .Then(_ => Token.EqualTo(SyntaxToken.Number).Or(Token.EqualTo(SyntaxToken.Asterisk)) .Select(quantity => new StringSubtractionValue(characters.Select(c => c.Span.ToString().ToCharArray().FirstOrDefault()).ToArray(), quantity.Span.ToString() == "*" ? 0 : int.Parse(quantity.Span.ToString()))))))); private static TokenListParser<SyntaxToken, StringSubtractionValue> Value { get; } = QuantifiedCharacterGroup.Or(CharacterGroup).Or(QuantifiedCharacter).Or(Character); private static TokenListParser<SyntaxToken, StringSubtractionValue> Source { get; } = Value.AtEnd(); } The above parser is able to do what I want for everything singularly, but I'm not sure how to select a StringSubtractionValue[] here. e.g "Hello" - "e" returns a StringSubtractionValue with Values e and Quantity 0 (numeric translation for all here). However "Hello" - "el" errors on unexpected l . So I'm not sure how to get back an array of these matches. |
adb dpm set-device-owner not working when installed outside of android studio Posted: 14 Feb 2022 10:47 AM PST I am having an issue with trying to set the device owner on my android device. If I install the app from within android studio by hitting the play button, I am able to add and remove device owner with adb shell dpm set-device-owner package/.receiver without any issues. I can do this from within android studio or via cmd. When I install the app from using the apk and manually installed or using adb outside of android studio, I can no longer set the device owner. I always get the error Not allowed to set the device owner because there are already some accounts on the device This is what makes no sense, as there are no accounts on the device. I can go back into android studio, install the app over the top of it and run the adb command again and it works just fine without doing anything else. I am lost here because there error seems incorrect, but I have no idea why installing from the apk outside of android studio is not working. Edit: Some notes - I have the manifest pointing to the xml with properly defined
- The app works fine when installing from android studio and setting device owner, I am getting all the expected permissions
- When I install from the output apk, I am no longer able to set device owner (previous was cleared, even tried on a fresh recovery of the phone. Accounts settings is empty with no accounts listed)
|
Play Developer Console Error (Android Version 12 Issue) Posted: 14 Feb 2022 10:48 AM PST You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without 'android:exported' property set. This file can't be installed on Android 12 or higher. See: developer.android.com/about/versions/12/behavior-changes-12#exported |
Is it possible to trigger an Ansible Tower playbook using Grafana? Posted: 14 Feb 2022 10:48 AM PST This is more a question for gaining knowledge and choosing if we are heading to the correct solution. I have my application being monitored through Grafana and Prometheus. The self healing is currently being worked with by using Ansbile Tower. All the alerts based on application performance is managed through Grafana dashboard. We know want to stitch both Grafana and Ansible playbook such that an alert in Grafana can trigger a playbook in Ansible. I did not see any out of the box integration for the same but would like to know if there is a way i can use Grafana alerts to actually call a REST API or do anything around Grafana to call a playbook in Ansible. Thank you, Anish |
"pydantic\validators.py" : no validator found for <class 'pandas.core.frame.DataFrame'> Posted: 14 Feb 2022 10:48 AM PST Below DataFrame of pandas is not validated by pydantic. How to handle this? from pydantic.dataclasses import dataclass @dataclass class DataFrames: dataframe1: pd.DataFrame = None dataframe2: pd.DataFrame = None This throws the following error: File "pydantic\validators.py", line 715, in find_validators RuntimeError: no validator found for <class 'pandas.core.frame.DataFrame'>, see `arbitrary_types_allowed` in Config |
How to Handle Drop-down for Google form using selenium using python Posted: 14 Feb 2022 10:48 AM PST can someone help me on how to automate the dropdown menu in google form using selenium in python. the problem that I am facing is I am able to locate the drop down menu and select it but I am not able to select the options I have tried select_by_index but it doesn't work. thank you in advance. (I am new to the forum so sorry if I have asked the question in a ambiguous way) drop = Select(browser.find_element_by_class_name('quantumWizMenuPaperselectContent').click()) drop.select_by_index(0) |
JPA query to filter before, after and between optional start and end dates Posted: 14 Feb 2022 10:47 AM PST I'd like to write a JPA Repository query that can findBy with two optional query parameters, startDate and endDate : startDate | endDate | Return | null | null | All | null | endDate | Before End | startDate | null | After Start | startDate | endDate | Between Start and End | How can this be implemented concisely? For example, using a single JPA @Query method with a SQL statement that can handle null or Optional<Date> parameters? EDIT: I'm using PostgreSQL 13. |
Bitbucket Server API: get raw files associated with pull request Posted: 14 Feb 2022 10:48 AM PST Situation: For a repo hosted on Bitbucket server, I have a webhook setup to send a request to an external server whenever a pull request is opened. The server then uses the Bitbucket Server API to get the diff of all files associated with the pr. This works just fine because the server account has read access to the repo with the webhook setup. What I would like to do next is get the raw files associated with the pull request. Issue: In the instance where another user forks this repo, makes changes, and submits the pr, my server does not have read access to this users fork of the repo, and therefore to the files in their modified state. I've looked through the Bitbucket Server documentation, but can't find any way to get the raw files other than to just read from the users repo. This works fine when the pr is from some branch in the main repo to master in the same repo, since the read permission issue does not come into play. One possible solution I think is to use the diff, along with the files presently in the main repo to recreate the modified state of the files, but I would like to avoid this. Any way to do this without having every user submitting a pr to give read access to the server account? Thanks |
MongoDB -Consider defining a bean of type 'org.springframework.data.mongodb.repository.query.MongoEntityInformation' in your configuration Posted: 14 Feb 2022 10:47 AM PST My Student entity class package com.example.entity; import java.io.Serializable; import javax.persistence.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "student") public class StudentMongo implements Serializable { private static final long serialVersionUID = 8764013757545132519L; @Id private Long id; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } My Repository package com.example.repository; import javax.annotation.Resource; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.repository.query.MongoEntityInformation; import org.springframework.data.mongodb.repository.support.SimpleMongoRepository; import org.springframework.stereotype.Repository; import com.example.entity.StudentMongo; @Repository public class StudentMongoRepository extends SimpleMongoRepository<StudentMongo, Long> { @Resource MongoOperations mongoOperations; public StudentMongoRepository(MongoEntityInformation<StudentMongo, Long> metadata, MongoOperations mongoOperations) { super(metadata, mongoOperations); } } My configuration class @Configuration @EnableMongoRepositories(basePackageClasses = {com.example.repository.StudentMongoRepository.class}) public class MongoConfiguration { } Spring boot application When i try to start the application i am getting following application 2017-11-20 09:04:48.937 ERROR 23220 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.example.repository.StudentMongoRepository required a bean of type 'org.springframework.data.mongodb.repository.query.MongoEntityInformation' that could not be found. Action: Consider defining a bean of type 'org.springframework.data.mongodb.repository.query.MongoEntityInformation' in your configuration. Consider defining a bean of type 'org.springframework.data.mongodb.repository.query.MongoEntityInformation' in your configuration How to create EntityInformation bean as said by spring framework Getting above issue while running my application . how to pass entity information suggest me how to use SimpleMongorepository |
Failed to run the WC DB work queue associated with file Posted: 14 Feb 2022 10:48 AM PST Without thinking I added and committed a file through my osx system that had a question mark in it not thinking about how this would impact windows. On windows when I did the update it failed because it was unable to create a file with a ? in it so I went back to my osx system and did an svn rename on the file however on windows this did not help since svn goes through the history of all steps to bring a workspace up to the head revision. Needless to say I am stuck, any ideas how I can fix this? Here is my current svn error log when updating (tried using Tortoise SVN and command line, both are the same): svn: E155009: Failed to run the WC DB work queue associated with 'F:\Devel\bc\dev\trunk\appShare\media\frontend\?_12x15.png', work item 53314 (file-install appShare/media/frontend/?_12x15.png 1 0 1 1) svn: E720123: Can't move 'F:\Devel\bc\dev\trunk\.svn\tmp\svn-68A36D23' to 'F:\Devel\bc\dev\trunk\appShare\media\frontend\?_12x15.png': The filename, directory name, or volume label syntax is incorrect. Each time I do this I have to delete the records in the WORK_QUEUE table in wc.db and then do a cleanup before svn will let me try something else. |
Finish all previous activities Posted: 14 Feb 2022 10:49 AM PST My application has the following flow screens : Home->screen 1->screen 2->screen 3->screen 4->screen 5 Now I have a common log out button in each screens (Home/ screen 1 / screen 2 /screen 3/ screen 4 / screen 5 ) I want that when user clicks on the log out button(from any screen), all the screens will be finished and a new screen Log in will open . I have tried nearly all FLAG_ACTIVITY to achieve this. I also go through some answers in stackoverflow, but not being able to solve the problem. My application is on Android 1.6 so not being able to use FLAG_ACTIVITY_CLEAR_TASK Is there any way to solve the issue ? |
What is the convention for word separator in Java package names? Posted: 14 Feb 2022 10:48 AM PST How should one separate words in package names? Which of the following are correct? com.stackoverflow.my_package (Snake Case using underscore) com.stackoverflow.my-package (Kebab Case using hyphens) com.stackoverflow.myPackage (Camel Case ) com.stackoverflow.MyPackage (Pascal Case ) What is the general standard? |
Java packages com and org Posted: 14 Feb 2022 10:48 AM PST What are the meaning of the packages org and com in Java? |
No comments:
Post a Comment