| Leading white space truncated by "set /p x=" Posted: 10 Jul 2021 08:01 AM PDT A script to manage incoming files generates an audit trail that logs transaction sets made up of a header record, several transaction records and a trailer record. A single line is written with delimiters, a string for the header, one each for the transactions and finally the trailer. Its fairly simple and the code snippet below describes it perfectly. There is, however, a flaw in the ointment, and one that's been around since XP transitioned out: sometimes the id in the transaction has a leading space, and cmd strips this out. dbenham posted its awfulness here and I'm hoping someone might have chanced on a solution to the bug? feature? issue. The following example shows this, with the first line having leading spaces, and the second replacing the leading and trailing spaces with an underscore by way of contrast, and to see what happens during expansion. The leading space is truncated, the trailing space retained. A delimiter is sent after each string. wrapping the set command in quotes makes no difference. TEST OUTPUT: no 1 line:header:leading space:leading trailing spaces :leadingtrailing pipe : no 2 line:header:_leading char:_leading trailing chars__:_leadingtrailing pipe_: SAMPLE CODE: type nul>file.txt >>file.txt (<nul set /p x=no 1 line) &&rem first line >>file.txt (<nul set /p x=:) &&rem delimiter >>file.txt (<nul set /p x=header) >>file.txt (<nul set /p x=:) (<nul set /p x= leading space)1>>file.txt &&rem leading space >>file.txt (<nul set /p x=:) (<nul set /p "x= leading trailing spaces ")1>>file.txt &&rem leading space, trailing space >>file.txt (<nul set /p x=:) echo|set /p=" leadingtrailing pipe ">>file.txt >>file.txt (<nul set /p x=:) >>file.txt echo:&&rem force a newline to begin line no 2. >>file.txt (<nul set /p x=no 2 line) &&rem writes to index 1 >>file.txt (<nul set /p x=:) >>file.txt (<nul set /p "x=header") &&rem no leading, no trailing >>file.txt (<nul set /p x=:) (<nul set /p "x=_leading char")1>>file.txt &&rem leading '_' >>file.txt (<nul set /p x=:) (<nul set /p "x=_leading trailing chars__")1>>file.txt &&rem leading, trailing '_' >>file.txt (<nul set /p x=:) echo|set /p="_leadingtrailing pipe_">>file.txt >>file.txt (<nul set /p x=:) rem no newline to avoid a trailing carriage return CODE EXPANSION: (where the leading white space is stripped out) (set /p x= leading space 0<nul ) 1>>file.txt && rem leading space (set /p "x= leading trailing spaces " 0<nul ) 1>>file.txt && rem leading and trailing'_' My workaround is to replace any leading spaces in the header id with underscores, and then restore the spaces after the run completes. This works fine because none of the incoming records have an underscore in their id. It would be nice, though, to be able to remove the work-around.  |
| How to tween animate a text? From Opacity =1 to 0 and back to 1 with one button Posted: 10 Jul 2021 08:01 AM PDT I've made the quote fade out and in if the previous quote is from another category. However, I'm unable to replicate that if the quote is from the same category. How do I make the quote fade out and in if the quote is from the same category? Any guidance is appreciated thanks! AnimationController animationController; Animation<double> opacityAnimation; double opacity1 = 0.0; ///same for opacity2 and opacity3 String convoTopic1 = ConvoTopics1[Random().nextInt(ConvoTopics1.length)]; void generateConvoTopic1() { setState(() { getQuotes1 = Quotes1[Random().nextInt(Quotes1.length)]; }); } ///I would have the same for Quotes2 and Quotes 3 @override void initState() { super.initState(); animationController = AnimationController(vsync: this, duration: Duration(seconds: 3)); opacityAnimation = TweenSequence( [ TweenSequenceItem<double>( tween: Tween<double>(begin: 1.0, end: 0.0).chain( CurveTween(curve: Curves.easeInOutBack), ), weight: 50), TweenSequenceItem<double>( tween: Tween<double>(begin: 0.0, end: 1.0).chain( CurveTween(curve: Curves.easeInOutBack), ), weight: 50), ], ).animate(animationController); animationController.forward(); } @override void dispose() { animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold ... AnimatedOpacity( opacity: opacity1, duration: Duration(seconds: 1), child: Text(Quotes1), ElevatedButton( ... onPressed: () { getQuotes1(); ///This returns randomized quote from the list. opacity1 = opacity1 == 1.0 ? opacityAnimation.value : 1.0; opacity2 = 0.0; opacity3 = 0.0; }, ), repeat for quotes2 and quotes3 ... } }  |
| Php 7.4.3 Class not found Posted: 10 Jul 2021 08:01 AM PDT This is my project path configuration ./create.php /Install/Install.php create.php <?php use Install\Install; echo "Starting"; $install = new Install(); This gives me the error PHP Fatal error: Uncaught Error: Class 'Install\Install' not found in /project/create.php:6 Install.php <?php namespace Install; class Install { //whatever } Can someone explain me what is happening there ? Obviously I guess that using a require_once line with my filename would probably fix the issue...but I thought using namespace and use import could prevent me from doing that like we do in classic framework like symfony / magento ? I've seen some post speaking about autoloading, but i'm a little bit lost. Haven't been able to find a clear explanation on the other stack topic neither.  |
| Can we create an e-commerce website with blockchain instead of a database Posted: 10 Jul 2021 08:01 AM PDT Hello I am student of computer Science (7th semester) I learned node.js from Udemy and now in my university final year project I want to create e-commerce website with blockchain not with any database, I just started learning blockchain, is it possible to use blockchain for storing data, retrieving data instead of using any database?  |
| Building an auto-design tool using multi-task learning methods Posted: 10 Jul 2021 08:01 AM PDT I am currently working as a MLE for a startup in the e-commerce space and have recently been tasked with developing a ML model to personalize landing/web pages based on user account data as well as text data that the user provides beforehand. Without getting too deep into the company jargon and weeds my inputs are as follows: BERT embeddings generated from the long form text provided by user Account info and standard headers from http requests My target output is generating a series of parameters/categories that go into a config file (json) that set the formatting of the page, there are roughly ~30 of these, each having roughly ~10 options within, ex: "border color: #fffffff" or " positonalElement4: #000000" and so on... I have existing configs that have been previously generated (randomly) but selected by a user. My question for the sub is as follows: How would you recommend architecting a system that can learn these parameters? My current approach is to utilize multi-task learning to build a unified trunk (backbone) and have a head for each param. This will result in roughly 30 heads. Does this seem doable / reasonable? If anyone knows of any other projects that have been done that are similar to this use case please let me know, any research papers or github links would be appreciated.  |
| How to obtain values of variables passed to ejs in a linked javascript file in electron Posted: 10 Jul 2021 08:01 AM PDT I am trying to build an electron app. An EJS file has variable values passed to it from the main process. I want to obtain these variables in the javascript file linked to renderer process. I tried the following : <script> var details = <%= details %> </script> But I recieve an error expression expected. How can I do this? I am new to electron and nodejs, any help is appreciated. Thanks!  |
| How do I properly integrate a modular boost build into my CMake project using FetchContent? Posted: 10 Jul 2021 08:01 AM PDT CMake FetchContent is a great way to manage build dependencies, by integration the dependency into your build and build it from source along with your own sources. I would like to do this with Boost, too. I am encouraged by the fact that CMake support for Boost is steadily improving. Of course since Boost is a large package, and one rarely uses all Boost libraries in a project, it would be rather wasteful to pull the entire Boost sources into one's own build. Given the modularity of the Boost project, using git submodules, it would be much more intelligent and efficient to only fetch the sources for the libraries actually used, and FetchContent supports this via its GIT_SUBMODULES option. However, this doesn't seem to cater for dependencies between the Boost libraries. Do I need to handle this manually, or is there a more intelligent solution? Furthermore, how do I control installation in this scenario? Many Boost libraries are header-only, and I don't want the headers included in my installation, since I'm only using them for my build. Is there a way to tell CMake that I don't want anything installed from what I fetch with FetchContent? I have read Craig Scott's book, and of course the CMake documentation, but there's not much information about this sort of problem. But maybe I'm trying something that I shouldn't be doing. Have others tried this, and can show me how it's done properly?  |
| Retrieve Label binded value from slider ListView - XAML Posted: 10 Jul 2021 08:00 AM PDT I have a listview which displays a label value, bound from a slider. Then I'm iterating through the listview in code behind, but how to access the label bound? XAML <ListView.ItemTemplate> <DataTemplate> <ViewCell Height="90"> <StackLayout Orientation="Horizontal" VerticalOptions="Center" HeightRequest="1200" > <Grid BackgroundColor="White" x:Name="grid" HeightRequest="1000" WidthRequest="700" Margin="0,0,0,5" > <Grid.RowDefinitions> <RowDefinition Height="30"/> <RowDefinition Height="60"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="150"/> <ColumnDefinition Width="60"/> <ColumnDefinition Width="160"/> </Grid.ColumnDefinitions> <Label Grid.Column="1" Grid.Row="0" x:Name="measure" BackgroundColor="White" HeightRequest="40" WidthRequest="50" FontSize="14" Margin="15,0,0,0" BindingContext="{x:Reference slider} " Text="{Binding Value, StringFormat='{0:F2}', Mode=TwoWay}" VerticalOptions="EndAndExpand" > </Label> CODE BEHIND CS foreach (myListViewModel x in logList.ItemsSource.Cast<myListViewModel>()) { var list = x; } Model - how can I bind the slider measure to my model value MeasurementAmount? decimal _MeasurementAmount; public decimal MeasurementAmount { get => _MeasurementAmount; set { if (_MeasurementAmount == value) return; _MeasurementAmount = value; } }  |
| Filling data in Pandas Series with help of a function Posted: 10 Jul 2021 08:00 AM PDT I want to fill values of a column on a certain condition, as in the example in the image:  What's the reason for the TypeError? How can I go about it?  |
| Query for only nested associated records Posted: 10 Jul 2021 08:00 AM PDT I have the follow set up in my models: class Project < ApplicationRecord has_many :plans end class Plan < ApplicationRecord belongs_to :project has_many :documents end class Document < ApplicationRecord belongs_to :plan end I'm trying to make a query in which I can easily return all nested associated records. For example, I want to be able to do something like: Project.documents and get all documents for a project. I've tried this with an includes like so: Project.includes({plans: [:documents]}) but that doesn't appear to give me what I want when I call Project.documents. I really only want all documents for a project, so don't really need to include plans. Is there an easy way todo this in Rails 6?  |
| How to nest and group results in Gremlin (CosmosDB) Posted: 10 Jul 2021 07:59 AM PDT I am connecting vertices like so: {user} --> owns --> {computer} --> controls --> {program} --> has --> {features} I want to list all the computers, programs and features accessible to a user. Preferably in the following JSON format: { userName: Foo, id: XX-1, ownedComputers: [ { computerName: Office-1, computerType: PC installedPrograms: [ { programID: XX-1, programName: FizzBuz programFeatures: [ { access: remote-connection, sudo: required, } }, { programID: XX-1, programName: FizzBuz programFeatures: [ { access: remote-connection, sudo: required, } }, ] }, ... {computer #2} ... ] } My query looks like this: g.V().has('user', 'id','XX-1').as('selectedUser').out('owns').as('ownedComputers').out('controls').as('installedPrograms').out('has').as('programFeatures').select('selectedUser','ownedComputer','installedPrograms','programFeatures').unfold().dedup() The current result looks like this: [ { selectedUser: { } }, { ownedComputers: { #1 } }, { installedPrograms: { #1 } }, { programFeatures: { #1 } }, { ownedComputers: { #2 } }, { installedPrograms: { #2 } }, { programFeatures: { #2 } }, { installedPrograms: { #3 } }, { programFeatures: { #3 } }, ] My query doesn't get me over the line because: - no pretty JSON -- not sure how to use map() and valueMap() to get rid of all unwanted ids.
- installedPrograms are just listed after the ownedComputer, I want them grouped and nested as shown above in my preferred format -- haven't figured out how to use store() or group().
- similarly for programFeatures, these should be grouped together and then nested under installedPrograms.
Any help would be greatly appreciated!  |
| Why is Azure devops delegated permission asking for admin consent when the portal says it is not required? Posted: 10 Jul 2021 07:59 AM PDT I am trying to acquire azure devops token with Itokenacquisition of Microsoft identity web library. I am able to generate the token when scope is present in enabletokenacquisitiontocalldownstreamapi In startup file And when I am already logged in to the app. The moment I log out of the app and log in again it asks for admin consent. Not sure about the behaviour. While signing in for the second time it includes ado scope.  |
| Upload XmlDocument to endpoint Posted: 10 Jul 2021 07:59 AM PDT im trying to upload an XmlDocument to an endpoint but i must be doing something wrong because it returns "Bad Request", here is what i have tried: the endpoing we are talking about is this one (Validar Semilla): link to the swagger if i manually upload the file in the swagger test it works, so my xml is in good shape. snippet 1: var httpClient = new HttpClient(); var someXmlString = MyXMLDoc.InnerXml; var stringContent = new StringContent(someXmlString, Encoding.UTF8, "multipart/form-data"); var respone = await httpClient.PutAsync("/someurl", stringContent); snippet 2: public static string postXMLData(string destinationUrl, string requestXml) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl); byte[] bytes; bytes = System.Text.Encoding.ASCII.GetBytes(requestXml); request.ContentType = "multipart/form-data; encoding='utf-8'"; request.ContentLength = bytes.Length; request.Method = "POST"; Stream requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); HttpWebResponse response; response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { Stream responseStream = response.GetResponseStream(); string responseStr = new StreamReader(responseStream).ReadToEnd(); return responseStr; } return null; } Sample XML File: <?xml version="1.0" encoding="utf-8"?> <SemillaModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <valor>lWVzKj0dStSuFkR3nXx2mrf2R2q9J+x6JVuPk8jmx0Bwr8DUmI1A9+eld/lot8MNNhC17k8fLeQLGKXW2naiLXXJ41rf0GNS6vlz0CGvuMaCDKElzpnR4NNBBo6XRNcoCEEaA+3H0kBItG1W+bU0pA==</valor> <fecha>2021-07-10T10:46:28.4448582-04:00</fecha> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /> <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" /> <Reference URI=""> <Transforms> <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" /> <DigestValue>VBFrBAoKPWRlOQO6RgVkY/3Jh6nNERnG2uGK+thFd24=</DigestValue> </Reference> </SignedInfo> <SignatureValue>ValuesIDoNotFeelSafeSharing</SignatureValue> <KeyInfo> <X509Data> <X509Certificate>ValuesIDoNotFeelSafeSharing</X509Certificate> </X509Data> </KeyInfo> </Signature> </SemillaModel> I'm new to XML, what am i doing wrong? any article that could help me?  |
| Group by and get latest record in group Posted: 10 Jul 2021 08:00 AM PDT i have a table named messages like this :  I want query for where reciever_id equal 1 and group by sender_id and get latest record. I USED QUERY : SELECT `t`.* FROM( SELECT * FROM messages WHERE reciever_id = 1 ORDER BY created_at DESC ) `t` GROUP BY `sender_id` ORDER BY `id`  AND ALSO : SELECT message, MAX(created_at) FROM messages WHERE reciever_id = 1 GROUP BY sender_id ORDER BY created_at  Date's column created_at in picture exactly are the latest and id's also ordered and are latest also.  |
| mysql1 return empty list in dart Posted: 10 Jul 2021 07:59 AM PDT I have simple database like this: database example and here is my code: import 'package:mysql1/mysql1.dart'; void main()async{ var settings = ConnectionSettings( host: 'localhost', port: 3306, user: 'user1', password: 'user1', db: 'test' ); var conn = await MySqlConnection.connect(settings); var result = await conn.query('select * from user;'); print('$result'); await conn.close(); } result: result  |
| Accept only objects in a method and return new object Posted: 10 Jul 2021 08:01 AM PDT I want to create a method that only takes objects of the class it is is defined in, manipulates it and returns a new object of the same class. For example: class fraction(): def__init__(self, counter, denominator): self.counter=counter self.denominator=denominator def add(self,(object of class fraction)) (addition of object the method from called in and the object which is called in the method return (new object of the class fraction) Does anyone have an idea how to get this done? best regards, David  |
| How to stop the program until the user input EOF? Posted: 10 Jul 2021 07:59 AM PDT I've this difficult assignment where I only have to use for loop.. so we're not allowed to use while or do.. while loop also else statement.. am trying to take the user input until he/she input EOF, so that the program will return the average number. So I wrote the code and ran it but whenever I enter ctrl+z (EOF) the program wont stop or even return the average values :( for (int i = 0; i < 50; i++) { printf("Please enter employee rank: "); if (scanf("%d", &newnum[i]) != EOF) { sum += newnum[i]; counter++; avg = sum / counter; if (newnum[i] < 8) { summ += newnum[i]; ccoun++; avgle = summ / ccoun; } } if (newnum[i] == EOF) break; } printf("\n The average rank of all employees : %d \n", avg); printf("\n The average rank of employees ;ess than 8: %d \n", avg);  |
| Use RegEx to extract specific part from string Posted: 10 Jul 2021 08:01 AM PDT I have string like "Augustin Ralf (050288)" "45 Max Müller (4563)" "Hans (Adam) Meider (056754)" I am searching for a regex to extract the last part in the brackets, for example this results for the strings above: "050288" "4563" "056754" I have tried with var match = Regex.Match(string, @".*(\(\d*\))"); But I get also the brackets with the result. Is there a way to extract the strings and get it without the brackets?  |
| How to make whole List row a NavigationLink in SwiftUI Posted: 10 Jul 2021 08:00 AM PDT I am making a list of questions sets and want the whole row to navigate to next view (every row has a different destination view), but only the area next to the text is tappable. I tried creating a SetRow() outside of List and it was working completely fine, but when its inside of List only the empty area is working. Red is the working area List code here: NavigationView { VStack { SearchBar(input: $searchInput) List(viewModel.filterList(by: searchInput)) { setVM in NavigationLink(destination: SetView(viewModel: QuestionListViewModel( emoji: setVM.questionSet.emoji, title: setVM.questionSet.title, setID: setVM.questionSet.id) )) { SetRow(viewModel: setVM) } .onLongPressGesture(minimumDuration: 1) { selectedSetVM = setVM showDeleteAlert.toggle() } } .listStyle(PlainListStyle()) } and SetRow code here: HStack { Text(viewModel.questionSet.emoji) .font(.system(size: 50)) VStack(alignment: .leading) { Text(viewModel.questionSet.title) .font(.system(size: 20, weight: .semibold, design: .default)) VStack(alignment: .leading) { Text("Questions: \(viewModel.questionSet.size)") .font(.system(size: 15, weight: .light, design: .default)) .foregroundColor(.gray) Text("Updated: \(viewModel.questionSet.lastUpdated, formatter: taskDateFormat)") .font(.system(size: 15, weight: .light, design: .default)) .foregroundColor(.gray) } } Spacer() } .padding(.top, 10)  |
| How can i fix this error Mapper for [description] conflicts with existing mapper:Cannot update parameter [analyzer] from [my_analyzer] to [default] Posted: 10 Jul 2021 08:00 AM PDT am new to elastic search.please help me out with this problem. Am using elastic search version 7.13.2 . I created an index with a custom analyzer and filter like this PUT /analyzers_test { "settings": { "analysis": { "analyzer": { "english_stop":{ "type":"standard", "stopwords":"_english_" }, "my_analyzer":{ "type":"custom", "tokenizer":"standard", "char_filter":["html_strip" ], "filter":[ "lowercase", "trim", "my_stemmer"] } }, "filter": { "my_stemmer":{ "type":"stemmer", "name":"english" } } } } } Then i created a mapping for the document i will have and specified my custom analyzer i created earlier (there is no document in the index yet) like so: PUT /analyzers_test/_mapping { "properties": { "description":{ "type": "text", "analyzer": "my_analyzer" }, "teaser":{ "type": "text" } } } When i try try to create a document like so POST /analyzers_test/1 { "description":"drinking", "teaser":"drinking" } i get the following error { "error" : { "root_cause" : [ { "type" : "illegal_argument_exception", "reason" : "Mapper for [description] conflicts with existing mapper:\n\tCannot update parameter [analyzer] from [my_analyzer] to [default]" } ], "type" : "illegal_argument_exception", "reason" : "Mapper for [description] conflicts with existing mapper:\n\tCannot update parameter [analyzer] from [my_analyzer] to [default]" }, "status" : 400 }  |
| Error with GitHub Action Deploy to Azure Web App Posted: 10 Jul 2021 07:59 AM PDT Just converted to new GitHub App Services Action Build And Deployment Pipeline and getting the following error: Run azure/webapps-deploy@v2 with: app-name: *** slot-name: *** publish-profile: *** package: . Package deployment using ZIP Deploy initiated. Fetching changes. Cleaning up temp folders from previous zip deployments and extracting pushed zip file D:\local\Temp\zipdeploy\gtfnmdqs.zip (19.64 MB) to D:\local\Temp\zipdeploy\extracted Error: Failed to deploy web package to App Service. Error: Deployment Failed with Error: Package deployment using ZIP Deploy failed. Refer logs for more details. App Service Application URL: https://***.azurewebsites.net Nothing in log indicating an error other than failed to deploy. No changes where made to repository (other than new yaml) and not sure if error is because no code changes detected. If so why throw an error vs. a warning? yml is standard generated by Azure: on: workflow_dispatch: branches: [main] jobs: build: runs-on: windows-latest steps: - uses: actions/checkout@v2 - name: Set up .NET Core uses: actions/setup-dotnet@v1 with: dotnet-version: '6.0.x' include-prerelease: true - name: Build with dotnet run: dotnet build --configuration Release - name: dotnet publish run: dotnet publish -c Release -o ${{env.DOTNET_ROOT}}/myapp - name: Upload artifact for deployment job uses: actions/upload-artifact@v2 with: name: .net-app path: ${{env.DOTNET_ROOT}}/myapp deploy: runs-on: windows-latest needs: build environment: name: '***' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: .net-app - name: Deploy to Azure Web App id: deploy-to-webapp uses: azure/webapps-deploy@v2 with: app-name: '***' slot-name: '***' publish-profile: ${{ secrets.AzureAppService_PublishProfile_*** }} package: . Side Note: I have a new App Service that works fine, this is an existing App Service initially using former CI/DI. Disconnected and generated new connection for CI/DI. Not sure if that matters. Azure Log Details:  Deployment seems to be pegging out CPU of service plan which explains why everyone is having increase tier in order to resolve:   Tried shutting down all App Services and deploy with nothing else running but had no effect. Also tried importing publish profile into Visual Studio but that fails as well ...   |
| Customer X Member SQL Database in booking Posted: 10 Jul 2021 08:00 AM PDT I would like to ask you for advice. I am creating Booking ERD diagram for Theatre. My problem is that after booking seat on some performance (for example Mamma Mia), I need to decipher who is Theatre's member and who is customer (in Booking table), because after some viewings (for example 6) he get's some reward (for example discounts for tickets or for friends/family members). And I don't know how to do that. Above I have some basic understanding how I understand it. I had some Ideas to create one booking for customers and one for members, but I believe it creates a bigger chaos. This is My conceptual ERD model  |
| Pyshark does not show \r\n\r\n in the HTTP header and instead shows \r\n Posted: 10 Jul 2021 08:00 AM PDT I am using pyshark to parse .pcap files specifically with HTTP packets. Unlike as in Wireshark, where it shows the \r\n\r\n bytes at the end of the HTTP header, pyshark does not show them and instead shows a single \r\n. Is there any way to properly parse the HTTP layer of the packet to display the \r\n\r\n's? If so, how? I have done a fair amount of searching through the web but the sources are limited and does not answer my question. Also, with pyshark, the headers do not come in the same order as seen on Wireshark. Is there any reason to that as well? Python code #!/bin/env python3 import pyshark packets = [] with pyshark.FileCapture('testing-mutillidae1.pcap') as capture: for pkt in capture: # storing packets in list packets.append(pkt) print(packets[3]) # printing packet details of packet no. 4 HTTP header I have included the full output of the packet on pastebin: https://pastebin.com/qxjxY6Hw . Since it is too long, I have added only the HTTP layer in this question Layer HTTP: GET /mutillidae/index.php?page=add-to-your-blog.php HTTP/1.1\r\n Expert Info (Chat/Sequence): GET /mutillidae/index.php?page=add-to-your-blog.php HTTP/1.1\r\n GET /mutillidae/index.php?page=add-to-your-blog.php HTTP/1.1\r\n Severity level: Chat Group: Sequence Request Method: GET Request URI: /mutillidae/index.php?page=add-to-your-blog.php Request URI Path: /mutillidae/index.php Request URI Query: page=add-to-your-blog.php Request URI Query Parameter: page=add-to-your-blog.php Request Version: HTTP/1.1 Host: 10.0.2.13\r\n User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0\r\n Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n Accept-Language: en-US,en;q=0.5\r\n Accept-Encoding: gzip, deflate\r\n Referer: http://10.0.2.13/mutillidae/index.php\r\n Connection: keep-alive\r\n Cookie: showhints=0; PHPSESSID=511be46cfd6922ff8sqqhtqmbn\r\n Cookie pair: showhints=0 Cache-Control: max-age=0\r\n Full request URI: http://10.0.2.13/mutillidae/index.php?page=add-to-your-blog.php HTTP request 1/1 \r\n Upgrade-Insecure-Requests: 1\r\n Cookie pair: PHPSESSID=511be46cfd6922ff8sqqhtqmbn Here is the screenshot on my wireshark (I cannot post pictures yet)  |
| Why character's face automatically converts into green in Xcode? Posted: 10 Jul 2021 08:00 AM PDT I am using Autodesk Maya for creating models and animations of this character. This character appears and animates perfectly on all other platforms like Unity, 3dsMax, etc. but when I import .dae file in Xcode the face of the character appears green and not showing the perfect texture.  This model has perfect UV's on the face, other faces are used as blend shapes those shows perfect texture. UV's of the main face which appears green.  The face appears in Unity  What changes are required to change green color appearance of face to normal?  |
| Using a variable from a higher scope in a callback Posted: 10 Jul 2021 08:00 AM PDT I am trying to use an object mechanics from the higher scope in a callback. To do that I tried to make object mechanics static. pub fn main() { let mut mechanics : &'static Mechanics = &'static mut Mechanics { val : 13. }; let mut renderer = Render::new( "solution1".to_string() ); renderer.f_on_update = Box::new( || { println!( "mechanics.val : {}", mechanics.val ) }); renderer.update(); } // struct Mechanics { val : f32, } // struct Render { name : String, f_on_update : Box< dyn Fn() >, } // impl Render { fn new( name : String ) -> Self { let f_on_update = || {}; Self { name, f_on_update : Box::new( f_on_update ) } } fn update( &self ) { (self.f_on_update)(); } } But I get the error: error: borrow expressions cannot be annotated with lifetimes --> src/static_solution_1.rs:4:44 | 4 | let mut mechanics : &'static Mechanics = &'static mut Mechanics { val : 13. }; | ^-------^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | annotated with lifetime here | help: remove the lifetime annotation Changing to let mut mechanics : &'static Mechanics = &Mechanics { val : 13. }; Gives the error: error[E0597]: `mechanics` does not live long enough --> src/static_solution_1.rs:8:37 | 6 | renderer.f_on_update = Box::new( || | - -- value captured here | __________________________| | | 7 | | { 8 | | println!( "mechanics.val : {}", mechanics.val ) | | ^^^^^^^^^ borrowed value does not live long enough 9 | | }); | |____- cast requires that `mechanics` is borrowed for `'static` 10 | renderer.update(); 11 | } | - `mechanics` dropped here while still borrowed I do something wrong but have no clue where to look for an answer. Reading about static lifetime didn't help me to overcome the obstacle. Any suggestion?  |
| Is there any simple way to preserve original indices after sorting array without using Comparator? Posted: 10 Jul 2021 08:00 AM PDT I implemented an array in which I've taken one array which is zero-indexed. Consider the array below : Array : X S T U A C D B F H Index : 0 1 2 3 4 5 6 7 8 9 After sorting this array : Array : A B C D F H S T U X Index : 0 1 2 3 4 5 6 7 8 9 Original indices : 4 7 5 6 8 9 1 2 3 0 Earlier A was at index 4 but in the sorted array, it is at index 0 and the same for other values. The output expected from the program is represented as original indices. Instead of printing the elements in the sorted array, I want to print their original indices after they are sorted. Although this code is working properly, But I want to know if there is any other simple technique that we can use to preserve the original array indices without using Comparator. The idea here is to preserve the index and hence I am using Comparator : In this Comparator, I preserved the actual array which is to be sorted. Also, if you notice, the compare method compares the values of the actual array based on the indices supplied to it. The key here is to supply the indices and not the actual values to be sorted. S is the character array to be sorted, indexArray is an auxiliary array. Before sorting, the index array will contain numbers in a sequence 0 – length of the array to be sorted. When I invoked the Arrays.sort method on the index array, it passes the two indices to the compare method and compares the values stored at those indices. ```public class ArrayIndexComparator implements Comparator<Integer> { private final Character[] A; public ArrayIndexComparator(Character[] arr) { this.A = arr; } public int compare(Integer o1, Integer o2) { return A[o1].compareTo(A[o2]); } }``` ```public static void main(String[] args) { Character[] S = new Character[]{'X','S','T','U','A','C','D','B','F','H'}; Integer[] indexArray = new Integer[S.length]; IntStream.range(0, S.length).forEach(val -> indexArray[val] = val); ArrayIndexComparator comp = new ArrayIndexComparator(S); Arrays.sort(indexArray, comp); System.out.println(Arrays.toString(indexArray)); }```  |
| How can I display data between specified dates and get a summation of only those data's? Posted: 10 Jul 2021 08:01 AM PDT So I am using PHP and MySQL(PDO). I have a form that is a lot like the table image below in which the user is gonna input data (almost) every day. Data Entry Example: | Date | Old Case(1) | New Case(2) | Total Case(1+2) | Discharge | Conviction | Acquittal | Other | | 12-06-2021 | 1000 | 500 | 1500 | 30 | 40 | 18 | 0 | | 13-06-2021 | 1500 | 200 | 1700 | 10 | 14 | 23 | 9 | | 14-06-2021 | 1700 | 100 | 1800 | 19 | 33 | 23 | 18 | | 15-06-2021 | 1800 | 200 | 2000 | 32 | 18 | 07 | 21 | And later maybe he would want to get the total number of data between two specified dates which the user would specify.Here is also another question of mine. How will the user specify the dates?. for example, he would select the 'from' date"01-January-2021" and the 'to' date "01-February-2021" after selection he would enter submit button, and then there would be a table shown in the website like below where the total "Discharge" number, total "Conviction", total "Acquittal" and total "Others" numbers between those dates would show. Final Output: | Date(Between Two Dates) | Last Entry Old Case in Date Range(1) | Last Entry New Case in Daterange(2) | Total Case(1+2) | Total Discharge | Total Conviction | Total Acquittal | Total Other | | 12-6-2021 to 15-6-2021 | 1800 | 200 | 2000 | 91 | 105 | 71 | 48 | Now how can I do this function? I am not being able to figure out the function where all the data between selected dates would get total up according to their fields and then display the totaled results! Do I need to use Ajax? DB-FIDDLE(I have never used this before so don't really know how to use it properly.): https://www.db-fiddle.com/f/goPRNPA8Q6QRkn258sdrsd/1 Another Question: I thought I would be able to figure this issue on my own but I couldn't after trying the whole day. So There are three other columns in my database (after updating the colums). They are "Old Case", "New Case" and the total of these two columns "Total Cases". This "Total Case" becomes the "Old Case" for the next entry or date. And in my Final Output, It would show the last entered "Old Case" and "New Case" between the selected "DateRange". But I am not being able to figure out how I can implement this. Can anyone help me, please?  |
| .NET SqlClient - Timeout expired Posted: 10 Jul 2021 07:59 AM PDT Currently i am building an query on a database in .net core. One of the querys has many different filters like the following example: IQueryable<OperatingInstructionDTO> newQuery = this.Database.Set<OperatingInstructionDTO>() .Include(x => x.CurrentState) .Include(x => x.Plant) .Include(x => x.Department) .Include(x => x.Creator) .Where(x => x.Type != null && x.Type.Equals(type) && x.Department.Id == user.Department.Id); if (filter.InstructionTitle != null) newQuery = newQuery.Where(x => x.Title.Contains(filter.InstructionTitle)); if (filter.SelectedStates != null) newQuery = newQuery.Where(x => filter.SelectedStates.Contains(x.CurrentState.Description)); if (filter.SelectedEditors != null && filter.SelectedEditors.Count == 1) { if (filter.SelectedEditors[0].Equals("Eigene")) newQuery = newQuery.Where(x => x.Creator.Email.Equals(user.Email)); else newQuery = newQuery.Where(x => !x.Creator.Email.Equals(user.Email)); } if (filter.OverallTextFilter != null) newQuery = newQuery.Where(x =>x.Content!=null && x.Content.Contains(filter.OverallTextFilter)); newQuery = newQuery.OrderByDescending(x => x.CreationTimestamp).ThenBy(x => x.Title).Take(filter.SelectedNumberOfResults); return newQuery.Select(x => new OperatingInstructionDTO { CreationTimestamp = x.CreationTimestamp, CurrentState = x.CurrentState, Department = x.Department, ParentOperatingInstruction = new OperatingInstructionDTO { }, Plant = x.Plant, Title = x.Title, Id = x.Id, Creator = x.Creator, Type = x.Type }).ToList(); If i set the filter OverallTextFilter the execution is very slow. I know this but this feature is needed for the customer. Because the exection is so slow i get the following error message: System.Data.SqlClient.SqlException HResult=0x80131904 Message=Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Source=Core .Net SqlClient Data Provider StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader() at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext() at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__17`2.MoveNext() at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext() at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at ModulareArbeitsanweisung.Database.Wrapper.InstructionManager.ReadOperationInstructionsWithFilter(UserDTO user, String type, InstructionFilter filter) in C:\Users\adlerlu\Desktop\CUE_GIT_REPO\SWP-Core-Backendservices\Modulare Arbeitsanweisung\ModulareArbeitsanweisung\ModulareArbeitsanweisung\Database\Wrapper\InstructionManager.cs:line 119 at ModulareArbeitsanweisung.Controllers.InstructionController.List(InstructionFilter filter) in C:\Users\adlerlu\Desktop\CUE_GIT_REPO\SWP-Core-Backendservices\Modulare Arbeitsanweisung\ModulareArbeitsanweisung\ModulareArbeitsanweisung\Controllers\InstructionController.cs:line 64 at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters) at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext() Inner Exception 1: Win32Exception: Der Wartevorgang wurde abgebrochen How can i fix this?  |
| GORM query to find all the records of a table which are not null for its contact field given a name field Posted: 10 Jul 2021 08:02 AM PDT I have a table in sqlite which consists of three columns, i.e. Name, Surname and Contact_Number. The scenario is, that I am given any name(which is present in the database) and I have to find all the records which are related with that name and have Contact_Number "NOT NULL". (There can be multiple contact numbers for a name, and they are stored each as a different record, For example: Name Surname Contact_Number Ajay Naik 1234 Ajay Naik 6789 Ajay Naik null So the query in GORM should return Upper two records on the name Ajay.  |
| Jaxb marshaling primitive types Posted: 10 Jul 2021 08:00 AM PDT I have a class with primitive types double and long. While marshaling i have to avoid the variables containing zero value. Tried @XmlJavaTypeAdapter and inside the same tried to return null values- but failed. Is there a way? Searched other threads and cant find a solution  |
No comments:
Post a Comment