When I install somethig from snap have error in kali linux Posted: 02 Sep 2021 07:55 AM PDT I want to download robo3t in kali linux from snap I have an error snap install robo3t-snap error: cannot perform the following tasks: - Mount snap "core" (11606) (snap is unusable due to missing files; contact developer) |
Why do I keep getting database disk image is malformed on android studio Posted: 02 Sep 2021 07:57 AM PDT I keep getting database disk image is malformed when I try getting the details from the second table added to my SQL database on android studio. Here are the code snippet for the tables public static final class CourseInfoEntry implements BaseColumns { public static final String TABLE_NAME = "course_info"; public static final String COLUMN_COURSE_ID = "course_id"; public static final String COLUMN_COURSE_TITLE = "course_title"; public static final String SQL_CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + COLUMN_COURSE_ID + " TEXT NOT NULL UNIQUE, " + COLUMN_COURSE_TITLE + " TEXT NOT NULL)"; } public static final class NoteInfoEntry implements BaseColumns { //Constant for the table name public static final String TABLE_NAME = "note_info"; //Constant for the table columns public static final String COLUMN_COURSE_ID = "course_id"; public static final String COLUMN_NOTE_TITLE = "note_title"; public static final String COLUMN_NOTE_TEXT = "note_text"; //Constant to create the note info table public static final String SQL_CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + COLUMN_NOTE_TITLE + " TEXT NOT NULL, " + COLUMN_NOTE_TEXT + " TEXT, " + COLUMN_COURSE_ID + " TEXT NOT NULL)"; } Here is the code to create the tables from the SQLiteOpenHelper class public static final String DATABASE_NAME = "NoteKeeper.db"; public static final int DATABASE_VERSION = 1; public NoteKeeperOpenHelper(@Nullable Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(NoteKeeperDatabaseContract.CourseInfoEntry.SQL_CREATE_TABLE); db.execSQL(NoteKeeperDatabaseContract.NoteInfoEntry.SQL_CREATE_TABLE); //Adding data to the tables DatabaseDataWorker worker = new DatabaseDataWorker(db); worker.insertCourses(); worker.insertSampleNotes(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } When I check the data for the first table using select * from course_id in the terminal I get this sqlite> select * from course_info; 1|android_intents|Android Programming with Intents 2|android_async|Android Async Programming and Services 3|java_lang|Java Fundamentals: The Java Language 4|java_core|Java Fundamentals: The Core Platform But when I check the data for the second table I get this sqlite> select * from note_info; Error: database disk image is malformed |
android process phone keep stopping and stock contacts and phone app are not installed Posted: 02 Sep 2021 07:55 AM PDT I have old used Samsung Galaxy S II phone with android JB 4.1.2 and it's keep showing errors like: process com.android.acore stopped and process com.android.phone stopped and I can't find contacts or phone apps I tried to install true phone app and I get this error : your stock phone app is either removed or disabled you will be unable to make and receive calls is there any way to get stock phone and contacts app for android 4.1.2 or any way to resolve this problem |
Bootstrap carousel left and right buttons not working Posted: 02 Sep 2021 07:55 AM PDT This is the code for my current carousel. When I click the left or right buttons, nothing happens. I'm not quite sure what the issue is, thank you in advance for your help. <section id="testimonials"> <div id="testimonial-carousel" class="carousel slide" data-ride="false"> <div class="carousel-inner"> <div class="carousel-item active"> <h2>"I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof."</h2> <img class="testimonial-image" src="images/dog-img.jpg" alt="dog-profile"> <em>Pebbles, New York</em> </div> <div class="carousel-item"> <h2 class="testimonial-text">My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.</h2> <img class="testimonial-image" src="images/lady-img.jpg" alt="lady-profile"> <em>Beverly, Illinois</em> </div> </div> <a class="carousel-control-prev" href="#testimonial-carousel" role="button" data-bs-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" href="#testimonial-carousel" role="button" data-bs-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> </section> |
Executing a specific Jupyter Lab Notebook on Windows Startup Posted: 02 Sep 2021 07:55 AM PDT I have a Jupyter Lab Notebook that I want to execute and run all its steps when the windows server boots up (it is on azure and the machine is shut down during non-working hours). Has anyone been able to do this? I want to keep the notebook structure for ease of future changes. Thanks to all in advance |
Ftp Folder to S3 Transfer Posted: 02 Sep 2021 07:55 AM PDT I want to transfer new data that appears in my FTP server folder to an S3 folder. I want to run this operation on Lambda or EC2 (10 times a day). We are talking about transferring a maximum of 50Mb whenever this script will run. The only part I have ready is, the one that figures out what the new data is in the FTP server. What is a cost effective solution to this task? |
Synchronized window post message using promise and custom event Posted: 02 Sep 2021 07:55 AM PDT I'm developing a Chrome extension that fetches data from the DOM. I have two contents scripts, one for the main frame (top-level frame) and another one for an iFrame. I would like to be able to call a method that calls an iframe method and wait for the result. I try to do it by using promises, post-message, and custom events. //main-frame.js window.addEventListener("message", this.frameMessages, false); const iframeElement = document.getElementById('iframeId'); function frameMessages(event){ let dataReadyEvent = new CustomEvent('dataReady'); iframeElement.dispatchEvent(dataReadyEvent); } let getDataAsync= async function getDataFromIFrame(): Promise<String> =>{ return new Promise(function (resolve) { chrome.runtime.sendMessage({service:'getData',frameId:frameId}); iframeElement.addEventListener("dataReady", function dataReady() { resolve(); }); } //The promise is not been waited and there is no result :\ const data = await getDataAsync(); //iframe.js chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if(request.service === 'getData'){ var element = document.getElementById(id); window.parent.postMessage({ message: 'dataFromIFrame', frameGuid: frameGuid, data: element }, "*" ); } } }); |
chrome binary installed by webdrivermanager is not working Posted: 02 Sep 2021 07:55 AM PDT I see in logs that webdrivermanager successfully downloads the chrome binary inside .m2 . However, it is still getting picked from some other location. The same implementation works locally but not in Azure Pipeline. ---------------- TEST STARTED: Verify login [INFO] Running Verify Heading demo General in publish environment [main] INFO io.github.bonigarcia.wdm.WebDriverManager - Reading https://chromedriver.storage.googleapis.com/ to seek chromedriver [main] INFO io.github.bonigarcia.wdm.Downloader - Downloading https://chromedriver.storage.googleapis.com/92.0.4515.107/chromedriver_win32.zip [main] INFO io.github.bonigarcia.wdm.Downloader - Extracting binary from compressed file chromedriver_win32.zip [main] INFO io.github.bonigarcia.wdm.WebDriverManager - Exporting webdriver.chrome.driver as C:\Users\vstsagent\.m2\repository\webdriver\chromedriver\win32\92.0.4515.107\chromedriver.exe Sep 02, 2021 2:38:10 PM org.openqa.selenium.remote.DesiredCapabilities chrome INFO: Using `new ChromeOptions()` is preferred to `DesiredCapabilities.chrome()` [main] INFO net.serenitybdd.core.webdriver.driverproviders.ProvideNewDriver - Instantiating driver [main] INFO net.serenitybdd.core.webdriver.driverproviders.ProvideNewDriver - Driver capabilities: Capabilities {acceptInsecureCerts: false, browserName: chrome, chrome.switches: --incognito, --disable-geol..., goog:chromeOptions: {args: [--incognito, --disable-geolocation, --enable-automation, --test-type], extensions: []}, loggingPrefs: org.openqa.selenium.logging..., platform: ANY, version: } Starting ChromeDriver 91.0.4472.101 (af52a90bf87030dd1523486a1cd3ae25c5d76c9b-refs/branch-heads/4472@{#1462}) on port 23809 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully. [main] ERROR net.thucydides.core.steps.ConsoleLoggingListener - ---------------- - TEST FAILED - ---------------- TEST FAILED WITH ERROR: Verify error icon on missing mandatory fields --------------------------- [main] ERROR net.thucydides.core.steps.ConsoleLoggingListener - TEST FAILED AT STEP Given Sample Web page [main] ERROR net.thucydides.core.steps.ConsoleLoggingListener - Could not instantiate new WebDriver instance of type class org.openqa.selenium.chrome.ChromeDriver (unknown error: cannot find Chrome binary First para in the logs, you'll see that chrome 93 is installed in .m2 folder and last para first line it is still picking chrome 91. I am not getting how. I have already all chrome instances. How can I fix this? |
Problem in adding navbar animate out animation Posted: 02 Sep 2021 07:55 AM PDT const [isMenuOpen, setIsMenuOpen] = useState(false); @keyframes appear { 0%{ transform: translateX(100%); } 100%{ transform: translateX(0%); } } .mNavBar{ animation: appear 200ms ease-in forwards; } {isMenuOpen ? <div className="mNavBar" ></div> : null} I want to add animate out animation to my navBar. I tried doing it with toggling class and adding animate out i.e translateX(-100%) but when page loads navBar somehow remains open for a second and then translates out even if isMenuOpen is false by default. |
Flutter BlurhHash flickers when loaded through CachedNetworkImage Posted: 02 Sep 2021 07:55 AM PDT I am trying to compbine BlurHash with CachedNetworkImage to offer a nice transition when loading images from Cloud Firestore. The problem is that most of the time the BlurHash flickers before transition to the loaded image starts. I narrowed it down to the fact that it flickers for hashes loaded from the model object, returned from Firestore. If I hard code an blur hash the flicker doesn't occur. Widget get _networkImage { final Duration fadeDuration = Duration(milliseconds: hasBlurhHash ? 500 : 0); return CachedNetworkImage( imageUrl: imageURL!, fit: fit, width: width, height: height, fadeInDuration: fadeDuration, fadeOutDuration: fadeDuration, placeholder: (context, __) => hasBlurhHash ? _blurHash : _loader(context), errorWidget: (context, url, error) => Image(image: AssetImage("assets/img/aboutus.png")), ); } Widget get _blurHash => BlurHash(hash: blurHash!, color: Colors.white); Widget _loader(BuildContext context) => ConstrainedBox( constraints: BoxConstraints(maxHeight: 48.h, maxWidth: 48.h), child: Center( child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor), strokeWidth: 4, ), ), ); The thing is that the blurHash data doesn't change so I'm not sure why it happens and/or how to solve it. Anyone has any clue? |
Odoo 14.0 - Inherit "website.layout" of my SECOND website Posted: 02 Sep 2021 07:55 AM PDT I'm trying to edit the layout only of my second website and not the first too in order to add some content at the end , after the footer but i don't know how to do ? Can someone help me about that ? <?xml version="1.0" encoding="utf-8" ?> <odoo> <data> <!-- Motifs de répétition --> <template id="motifs_rep" inherit_id="website.layout" name="Motifs Rep Footer"> <!-- Add an element after the bottom copyright footer --> <xpath expr="//div[@id='wrapwrap']/footer/div[@class='o_footer_copyright']" position="after"> #some content </xpath> </template> </data> </odoo> Thanks by advance... |
How to add data to a field based on other fields in an SQL database Posted: 02 Sep 2021 07:55 AM PDT I have an SQLite table called wcvp constructed from a csv file downloaded from the World Check List of Vascular Plants (see https://wcvp.science.kew.org/ and http://sftp.kew.org/pub/data-repositories/WCVP/). When I run this query: sqlite> SELECT kew_id, genus, species, infraspecies FROM wcvp WHERE genus='Quercus' AND species='robur' AND taxonomic_status='Accepted'; I get this result: kew_id | genus | species | infraspecies | 304293-2 | Quercus | robur | | 77189540-1 | Quercus | robur | broteroana | 77189379-1 | Quercus | robur | brutia | 77189383-1 | Quercus | robur | imeretina | 60459295-2 | Quercus | robur | pedunculiflo | 77171868-1 | Quercus | robur | robur | I want to add a field to the table (which has hundreds of thousands of rows in it) called number_of_infraspecies which would look like this: kew_id | genus | species | infraspecies | number_of_infraspecies | 304293-2 | Quercus | robur | | 5 | 77189540-1 | Quercus | robur | broteroana | NULL | 77189379-1 | Quercus | robur | brutia | NULL | 77189383-1 | Quercus | robur | imeretina | NULL | 60459295-2 | Quercus | robur | pedunculiflo | NULL | 77171868-1 | Quercus | robur | robur | NULL | Alternatively I could construct a new table with two fields: kew_id as a foreign key and number_of_infraspecies as the other field. Whichever approach I take I can only think of a procedure which would result in making a separate query for every row of the wcvp table or at least those rows which do not have a value in the infraspecies field (AND taxonomic_status='Accepted'). Is there a way of doing it with one or just a few queries? |
Set a dataframe column's rows to some data based on a different dataframe based on dates Posted: 02 Sep 2021 07:55 AM PDT I have a Dataframe with Dates, Names and Notes but I wanted to add which Team they we're in for the given date. The Team Data frame would have Name, Team Name, Team Start Date, Team End Date. Problem is that team members move teams constantly so I haven't found a way in pandas to get the Team Column to work properly. In excel this would have worked with the Filter formula or a simple Sumifs combined with Index/Match or in sql with a view. How would I get a Team column in the first Dataframe? Is this possible in python? dfNotes = pd.DataFrame({ 'Date':'6/30/2021 7/11/2021 7/12/2021 7/13/2021 7/14/2021 7/15/2021'.split(), 'Name': 'Emp1 Emp2 Emp3 Emp1 Emp2 Emp3'.split(), 'Case Notes':'19281080 19356855 19454005 19289960 19206939 19472141'.split() }) dfTeams = pd.DataFrame({ 'Name': 'Emp1 Emp1 Emp1 Emp2 Emp2 Emp2 Emp3 Emp3 Emp3'.split(), 'Team': '2 3 1 1 1 5 1 2 1'.split(), 'Team Start Date': '7/5/2020 4/12/2021 4/28/2021 1/1/2020 3/22/2021 6/4/2021 3/9/2020 11/25/2020 11/30/2020'.split(), 'Team End Date': '4/11/2021 4/27/2021 12/31/2021 3/21/2021 6/3/2021 12/31/2021 11/24/2020 11/29/2021 12/31/2021'.split() }) |
Mixed Authentication in ASP.NET Core (Windows and AAD JwtBearer) Posted: 02 Sep 2021 07:54 AM PDT I'm working on .Net 5 Web application that should have both Windows and Azure Active Directory JwtBearer authentications. One controller will use one windows authentication and another authentication will be for other controllers. It is clear how to set one or another, but I'm not sure how to set both of them. For Windows authentication: services.AddAuthentication(IISDefaults.AuthenticationScheme); For Azure Active Directory JwtBearer authentication: services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme) .AddAzureADBearer(options => Configuration.Bind("AzureAd", options)); It seems that I can't set multiple authentications in AddAuthentication method and I'm wondering can we have several authentications at the same time at all? I would like to set them somehow in Startup.cs and have an controller attribute with authentication scheme. [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class JwtBearerProtectedController : ControllerBase ... [Authorize(AuthenticationSchemes = IISDefaults.AuthenticationScheme)] public class WindowsAuthProtectedController : ControllerBase |
c# creating a generic serialisable model Posted: 02 Sep 2021 07:55 AM PDT I'm trying to figure out how I can serialise some data into this generic format (Array of dynamic objects) [ { Character: "BreakTooth", Aggression: "High", Strength: 50, }, { Character: "SandyPants", Aggression: "Low", Strength: 70, }, { Character: "BlueCrack", Aggression: "High", Strength: 90, } ] Where my original dataset would be like this: Character | Quality | Value =============================== BreakTooth | Aggression | High BreakTooth | Strength | 50 SandyPants | Aggression | Low SandyPants | Strength | 70 BlueCrack | Aggression | High BlueCrack | Strength | 90 This dataset could be a list of: public class Model { public string Character { get;set; } public string Quality { get; set; } public string Value { get; set; } } or it could be a datatable The issue here is that this table is, of course, dynamic - where there can be more than two qualities and respective values associated with each character. I have no way of knowing how many Qualities there will be but they will always be the same for each Character in any query. This is really two tables joined together, and I do have the ability to create this architecture if needed. So I could also create separate models like: public class Model { public string Character { get; set; } public List<Quality> Qualities { get; set; } } public class Quality { public string Name { get; set; } public string Value { get; set; } } I was thinking to use anonymous selections on the original model e.g. var result = ds.select(x => new { Character = x.Character, x.Quality.ToString() = x.Value }); where ds is an IEnumerable of the model with three properties Character Quality Value but I can't assign the property name dynamically like using x.Quality.ToString() and I'm not even sure that'd work since it'd need another iteration of the dynamic properties inside. Is it possible to achieve this? Do I need to create the separated models and, if so, how would I set them up and query them to get the exact JSON output required? |
Make a NavigationView full screen on macOS Posted: 02 Sep 2021 07:55 AM PDT How do you prevent a NavigationView from splitting itself on macOS? Basically, I want this code: struct ContentView: View { var body: some View { NavigationView { VStack { Text("Hello World") Text("Hello again") Text("Foo") } } } } to be shown in a single column. But this is split into two columns: |
Deleting documents from a Cosmos collection from Azure portal Posted: 02 Sep 2021 07:55 AM PDT Running the following stored procedure results in zero records getting deleted. /** * A Cosmos DB stored procedure that bulk deletes documents for a given query. * Note: You may need to execute this stored procedure multiple times (depending whether the stored procedure is able to delete every document within the execution timeout limit). * * @function * @param {string} query - A query that provides the documents to be deleted (e.g. "SELECT c._self FROM c WHERE c.founded_year = 2008"). Note: For best performance, reduce the # of properties returned per document in the query to only what's required (e.g. prefer SELECT c._self over SELECT * ) * @returns {Object.<number, boolean>} Returns an object with the two properties: * deleted - contains a count of documents deleted * continuation - a boolean whether you should execute the stored procedure again (true if there are more documents to delete; false otherwise). */ function bulkDeleteStoredProcedure(query) { var collection = getContext().getCollection(); var collectionLink = collection.getSelfLink(); var response = getContext().getResponse(); var responseBody = { deleted: 0, continuation: true }; console.log(query); // Validate input. if (!query) throw new Error("The query is undefined or null."); tryQueryAndDelete(); // Recursively runs the query w/ support for continuation tokens. // Calls tryDelete(documents) as soon as the query returns documents. function tryQueryAndDelete(continuation) { var requestOptions = {continuation: continuation}; var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, retrievedDocs, responseOptions) { if (err) throw err; console.log(retrievedDocs.length); if (retrievedDocs.length > 0) { // Begin deleting documents as soon as documents are returned form the query results. // tryDelete() resumes querying after deleting; no need to page through continuation tokens. // - this is to prioritize writes over reads given timeout constraints. tryDelete(retrievedDocs); } else if (responseOptions.continuation) { // Else if the query came back empty, but with a continuation token; repeat the query w/ the token. tryQueryAndDelete(responseOptions.continuation); } else { // Else if there are no more documents and no continuation token - we are finished deleting documents. responseBody.continuation = false; response.setBody(responseBody); } }); // If we hit execution bounds - return continuation: true. if (!isAccepted) { response.setBody(responseBody); } } // Recursively deletes documents passed in as an array argument. // Attempts to query for more on empty array. function tryDelete(documents) { if (documents.length > 0) { // Delete the first document in the array. var isAccepted = collection.deleteDocument(documents[0]._self, {}, function (err, responseOptions) { if (err) throw err; responseBody.deleted++; documents.shift(); // Delete the next document in the array. tryDelete(documents); }); // If we hit execution bounds - return continuation: true. if (!isAccepted) { response.setBody(responseBody); } } else { // If the document array is empty, query for more documents. tryQueryAndDelete(); } } } retrievedDocs.length is always 0. This is how I'm calling the procedure: query is SELECT c._self FROM c WHERE c.type = 'ORDER' I have confirmed the above query returns results by querying manually from the portal. This code is from this answer. |
c# Process.Start with credentials always "access is denied" when running in WPF application, Console is working fine Posted: 02 Sep 2021 07:55 AM PDT I'm starting an external executable to get the console output to analyze the result afterwards. All is working fine, when I use a Console application to start the process using Process.Start with the following code: System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = @"find.exe"; proc.StartInfo.Arguments = $"\"{host}\" -printf \"%M %p\n\""; // Set credentials proc.StartInfo.Domain = domain; proc.StartInfo.UserName = username; System.Security.SecureString ssPwd = new System.Security.SecureString(); for (int x = 0; x < password.Length; x++) { ssPwd.AppendChar(password[x]); } proc.StartInfo.Password = ssPwd; // StartInfo setup proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.CreateNoWindow = true; proc.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); proc.ErrorDataReceived += new DataReceivedEventHandler(OutputErrorHandler); proc.Start(); // <--- System.ComponentModel.Win32Exception occures on calling Start() proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); After adding the exact code to my WPF application it always throws an Exception saying "access is denied". Also while runnning the WPF application with Administrator rights the same error occures. What is different with the WPF application? Am I missing anything? Any hints appreciated... |
How to execute a method the first time and on each retry? Posted: 02 Sep 2021 07:55 AM PDT I'm using Polly for a retry policy: var policy = Policy .Handle<DatabaseException>(x => x.DatabaseErrors.ContainsKey(2601)) .WaitAndRetry(new[] { TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1500) }, (exception, timeSpan) => { FirstAndRetryMethod(); }); policy = Policy.Excecute(() => DoSomething()); With the above, FirstAndRetryMethod is called as expected on Retry . How can I call this also the first time DoSomething is executed? |
Fetch data on Button Click, not Select Posted: 02 Sep 2021 07:55 AM PDT I am new to react and I kind of did smth, which I don't really understand. I am fetching weather data from api (using next.js so, the route is in api folder). Before using Autoselect I used normal input with a ref and the function took the input value and posted it to my endpoint, the weather data came back on button click. Now since I integrated Autoselect, the data gets fetched on select. Here is the code import { useState, useEffect } from 'react'; import { ReactSearchAutocomplete } from 'react-search-autocomplete' export const SearchBar = () => { const [city, setCity] = useState('') const [payload, setPayload] = useState(null) const [error, setError] = useState(null) const [loading, setLoading] = useState(true) const items = [ { id: 0, name: 'London' }, { id: 1, name: 'Long Beach' }, { id: 2, name: 'Moscow' }, { id: 3, name: 'Mosul' }, { id: 4, name: 'Hamburg' } ] const handleOnSelect = (item) => { // the item selected const city = item?.name setCity(city) } useEffect(() => { city && fetchCityData(city); }, [city]) const fetchCityData = (city) => { const options = { method: `POST`, }; fetch(`/api/weather?city=${city}`, options) .then((response) => { if(response.ok){ return response.json().then(setPayload) } throw new Error('Api is not available') }) .catch(error => { console.error('Error fetching data: ', error) setError(error) }) .finally(setLoading(false)) } console.log(payload) const location = payload?.location?.name; const currentTemp = payload?.current?.temp_c; return( <div > <label htmlFor="email" className="block text-sm font-medium text-gray-700"> Search city </label> <div className="grid grid-cols-5 gap-4"> <div className="col-span-3"> <div className="mt-1"> <ReactSearchAutocomplete id="city" name="city" type="text" items={items} onSelect={handleOnSelect} autoFocus autoComplete="off" className="py-3 px-4 block w-full shadow-sm focus:ring-blue-500 focus:border-blue-500 border-gray-300 rounded-md" /> </div> </div> <div className="col-span-2 mt-1"> <button className="mt-1 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" type='button' onClick={fetchCityData}> Check weather </button> </div> </div> <p key={city?.location?.id} className='my-5'> { location ? `Current weather in ${location} is ${currentTemp} degrees ` : 'Please search for city to see current weather'} </p> </div> ) } So, my first question is, how is it even possible, as I do a post request with the function fetchCityData, which is not actually attached to onSelect. And second question, of course, how to correct this. First fetch and show weather data on button click. At the moment, the [object Object] gets posted to my endpoint, so, of course I get an error. I would really like to understand what is happening. SearchBar.js?2362:50 POST http://localhost:3000/api/weather?city=[object%20Object] 400 (Bad Request) |
Finding the location of ones in a bit mask - Julia Posted: 02 Sep 2021 07:55 AM PDT I have a series of values that are each being stored as UInt16 . Each of these numbers represents a bitmask - these numbers are commands that have been sent to a microprocessor telling it which pins to set high or low. I would like to parse this arrow of commands to find out which pins were being set high each time in such a way that is easier to analyse later. Consider the example value 0x3c00 , which in decimal is 15360 and in binary is 0011110000000000 . Currently I have the following function function read_message(hex_rep) return findall.(x -> x .== '1',bitstring(hex_rep)) end Which gets called on every element of the array of UInt16 . Is there a better/more efficient way of doing this? |
Can some one help me solving this problem to install nodemon Posted: 02 Sep 2021 07:55 AM PDT loadDep:fsevents -> reque - |##########---------------------------------------| WARN engine fsevents@2.3.2: wanted: {"node":"^8.16.0 || ^10.6.0 || >=11.0.0"} (c/home/gapvak-cs3/.npm-global/bin/nodemon -> /home/gapvak-cs3/.npm-global/lib/node_modules/nodemon/bin/nodemon.js > nodemon@2.0.12 postinstall /home/gapvak-cs3/.npm-global/lib/node_modules/nodemon > node bin/postinstall || exit 0 Love nodemon? You can now support the project via the open collective: > https://opencollective.com/nodemon/donate /home/gapvak-cs3/.npm-global/lib `-- nodemon@2.0.12 npm WARN optional Skipping failed optional dependency /nodemon/chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture: fsevents@2.3.2 |
Flutter Testing Bloc Navigation Posted: 02 Sep 2021 07:55 AM PDT I'm new in BLoC and testing, I need to Test if my Navigation to another screen is working, I could make the UI test, but not the event to call another screen. I don't know what I'm doing wrong. I tried the test inside my UI Test, just to see if it is called, the UI pass, but the navigation fails. I also tried to test the BLoC separately, but also failed. Can anyone help me to understand what I am doing wrong? This is the code from the ProfileScreen that works in the device: onPressed: () { unawaited( _navigationService.navigateTo(RouterPath.editProfile)); //context.read<ProfileBloc>().add(NavigateToEditProfile()); }, Here is my Test with the UI: All the comments are the things that I tried to do, but didn't work. import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/material.dart'; import 'package:mocktail/mocktail.dart' as mocktail; import '../../screens/home_test.dart'; import '../../wrapper/ui.dart'; import '../../service_locator_mock.dart' as setup_locator; class ProfileScreenMock extends MockBloc<LoginEvent, LoginState> implements LoginBloc {} class ProfileScreenMockFake extends Fake implements LoginEvent {} Logged getLoggedState() { return Logged( user: User( firstName: 'John', id: '2', lastName: 'Doe', email: 'johndoe@email', username: 'john_doe', ), ); } void main() { TestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() { setup_locator.setupLocatorMock(); mocktail.registerFallbackValue<Logged>(getLoggedState()); mocktail.registerFallbackValue<LoginEvent>(ProfileScreenMockFake()); mocktail.registerFallbackValue<ProfileEvent>(NavigateToEditProfile()); mocktail.registerFallbackValue<ProfileState>( NavToEditProfile(EditProfileScreen())); }); Widget wrappedProfileScreen(blocs) { return UIWrapper.wrapTranslated( UIWrapper.blocWrap( UIWrapper.themeWrap(ProfileScreen()), blocs, ), routes: { RouterPath.editProfile: (_) => EditProfileScreen(key: Key('FakeEditScreen')) }, ); } group('ProfileScreen', () { testWidgets('render properly', (WidgetTester tester) async { final loginBloc = LoginBlocMock(); final state = getLoggedState(); whenListen( loginBloc, Stream.fromIterable( [state], ), initialState: state, ); await tester.pumpWidget( UIWrapper.wrapTranslated( UIWrapper.blocWrap( UIWrapper.themeWrap(ProfileScreen()), [ BlocProvider<LoginBloc>.value(value: loginBloc), ], ), routes: { RouterPath.editProfile: (_) => EditProfileScreen(), }, ), ); expect(find.byType(AvatarProfile), findsOneWidget); expect(find.byKey(Key('FullName')), findsOneWidget); expect(find.byKey(Key('UserName')), findsOneWidget); expect(find.byType(ElevatedButton), findsOneWidget); }); testWidgets('nav to edit Screen', (WidgetTester tester) async { final editButton = ProfileScreenMock(); final state = wrappedProfileScreen(EditProfileScreen); whenListen( editButton, Stream.fromIterable( [state], ), initialState: state, ); await tester.pumpWidget( UIWrapper.wrapTranslated( UIWrapper.blocWrap( UIWrapper.themeWrap(ProfileScreen()), [ BlocProvider<ProfileScreenMock>.value(value: editButton), ], ), routes: { RouterPath.editProfile: (_) => EditProfileScreen(), }, ), ); await tester.tap(find.text('EditProfile')); await tester.pumpAndSettle(); expect(find.byKey(Key('FakeEditScreen')), findsOneWidget); }); }); //TEST BUTTON /* Widget wrappedProfileScreen(List<BlocProvider> blocs) { return UIWrapper.wrapTranslated( UIWrapper.blocWrap( UIWrapper.themeWrap(ProfileScreen()), blocs, ), routes: { RouterPath.settings: (_) => EditProfileScreen(key: Key('FakeSettingsScreen')) }, ); } group('tests changing screen', () { testWidgets('test edit profile button route and widgets existence', (WidgetTester tester) async { final loginBlocMock = LoginBlocMock(); whenListen( loginBlocMock, Stream.fromIterable([getLoggedState()]), initialState: getLoggedState(), ); await tester.pumpWidget( wrappedProfileScreen([ BlocProvider<LoginBloc>.value(value: loginBlocMock), ]), ); expect(find.byKey(Key('EditProfileButton')), findsOneWidget); /* await tester.tap(find.byKey(Key('EditProfileButton'))); await tester.pumpAndSettle(); */ expect(find.byKey(Key('FakeSettingsScreen')), findsOneWidget); }); }); */ /* testWidgets('test edit profile button route and widgets existence', (WidgetTester tester) async { final loginBlocMock = LoginBlocMock(); whenListen( loginBlocMock, Stream.fromIterable([getLoggedState()]), initialState: getLoggedState(), ); await tester.pumpWidget( wrappedProfileScreen([ BlocProvider<LoginBloc>.value(value: loginBlocMock), ]), ); expect(find.byKey(Key('EditProfileButton')), findsOneWidget); /* await tester.tap(find.byKey(Key('EditProfileButton'))); await tester.pumpAndSettle(); */ expect(find.byKey(Key('FakeSettingsScreen')), findsOneWidget); }); */ /* testWidgets('Navigate to Edit Profile Screeen', (WidgetTester tester) async { final loginBloc = LoginBlocMock(); final state = getLoggedState(); whenListen( loginBloc, Stream.fromIterable( [state], ), initialState: state, ); await tester.pumpWidget( UIWrapper.wrapTranslated( UIWrapper.blocWrap( UIWrapper.themeWrap( ProfileScreen(), ), [ BlocProvider<ProfileBloc>(), ], ), routes: { RouterPath.editProfile: (_) => EditProfileScreen(key: Key('EditProfileScreen')) }, ), ); await tester.tap(find.byKey(Key('EditProfileButton'))); await tester.pumpAndSettle(); expect(find.byKey(Key('EditProfileScreen')), findsOneWidget); }); */ } And here is the bloc test, together with the blocs events and state that I did Bloc_Test: // @dart=2.9 import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import '../../service_locator_mock.dart' as setup_locator; import 'package:mocktail/mocktail.dart' as mocktail; class ProfileBlocMock extends MockBloc<ProfileEvent, ProfileState> implements ProfileBloc {} class TrackManagerEventFake extends Fake implements ProfileEvent {} ProfileState buildProfileState() { return NavToEditProfile( EditProfileScreen(), ); } ProfileBlocMock buildProfileBloc({ProfileState newState}) { final profileBlocMock = ProfileBlocMock(); final state = newState ?? buildProfileState(); whenListen( profileBlocMock, Stream.fromIterable([state]), initialState: state, ); return profileBlocMock; } void main() { TestWidgetsFlutterBinding.ensureInitialized(); NavigationService navigationService; setUpAll(() { setup_locator.setupLocatorMock(); mocktail.registerFallbackValue<ProfileEvent>( TrackManagerEventFake(), ); mocktail.registerFallbackValue<ProfileState>( NavToEditProfile(EditProfileScreen()), ); }); setUp(() { navigationService = setup_locator.locator<NavigationService>(); }); tearDown(() { clearInteractions(navigationService); }); group('Navigate Edit Screen', () { blocTest( 'changes between screens', build: () => ProfileBloc(), act: (bloc) { bloc.add( EditingProfile(), ); }, verify: (_) { verify(navigationService.navigateTo( RouterPath.editProfile, )).called(1); }, expect: () => [NavToEditProfile(EditProfileScreen())], ); }); } /* class ProfileBlocMock extends MockBloc<ProfileEvent, ProfileState> implements ProfileBloc {} class ProfileEventFake extends Fake implements ProfileEvent {} ProfileState buildProfileState() { return NavToEditProfile( EditProfileScreen(), ); } ProfileBlocMock buildProfileBloc({ProfileState newState}) { final navEditProfileBlocMock = ProfileBlocMock(); final state = newState ?? buildProfileState(); whenListen( navEditProfileBlocMock, Stream.fromIterable([state]), initialState: state, ); return navEditProfileBlocMock; } void main() { TestWidgetsFlutterBinding.ensureInitialized(); NavigationService navigationService; setUpAll(() { setup_locator.setupLocatorMock(); mocktail.registerFallbackValue<ProfileEvent>( ProfileEventFake(), ); }); setUp(() { navigationService = setup_locator.locator<NavigationService>(); }); tearDown(() { clearInteractions(navigationService); }); group('ProfileBloc', () { blocTest( 'navigate to Edit Profile Screen', build: () => ProfileBloc(), act: (bloc) { bloc.add(NavToEditProfile(EditProfileScreen())); }, verify: (_) { verify(navigationService.navigateTo( RouterPath.editProfile, )).called(1); }, expect: () => [ NavigateToEditProfile(), ], ); }); } */ Here is the bloc structure: Profile_Bloc: // ignore_for_file: import_of_legacy_library_into_null_safe import 'package:bloc/bloc.dart'; import 'package:pedantic/pedantic.dart'; class ProfileBloc extends Bloc<ProfileEvent, ProfileState> { ProfileBloc() : super(NavToEditProfile(EditProfileScreen())); final NavigationService _navigationService = locator<NavigationService>(); @override Stream<ProfileState> mapEventToState(ProfileEvent event) async* { switch (event.runtimeType) { case NavigateToEditProfile: yield* _navToEditingProfileScreen(event as NavigateToEditProfile); break; } } Stream<ProfileState> _navToEditingProfileScreen( NavigateToEditProfile event) async* { yield NavToEditProfile(EditProfileScreen()); unawaited(_navigationService.navigateTo(RouterPath.editProfile)); } } Profile_Event: import 'package:meta/meta.dart'; import 'package:equatable/equatable.dart'; @immutable abstract class ProfileEvent extends Equatable { const ProfileEvent(); @override List<Object> get props => []; } class NavigateToEditProfile extends ProfileEvent {} class EditingProfile extends ProfileEvent { @override List<Object> get props => []; } Profile_state: import 'package:equatable/equatable.dart'; import 'package:indaband/profile/screens/edit_profile_screen.dart'; abstract class ProfileState extends Equatable { const ProfileState(this.navToEditProfile); final EditProfileScreen navToEditProfile; @override List<Object> get props => [navToEditProfile]; } class NavToEditProfile extends ProfileState { NavToEditProfile(EditProfileScreen navToEditProfile) : super(navToEditProfile); } |
Not able to display the count in SQL Server Posted: 02 Sep 2021 07:55 AM PDT I want to show the number of episodes whose title contain the words "on" and "ol". Using CTE from the table :- Table I tried the following code but it is throwing error: select count (select Title from tblEpisode where Title like '%on%' or Title like '%ol%') from tblEpisode Error: Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'select'. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ')'. What is the problem? Please help! |
Webview from Android Studio does show a navigation menu and background logo Posted: 02 Sep 2021 07:55 AM PDT Context I'm trying to implement a webview for my website, using Android Studio and Java. Here is the code for package com.example.neurofinance; import androidx.appcompat.app.AppCompatActivity; import android.annotation.TargetApi; import android.net.http.SslError; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.webkit.SslErrorHandler; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends AppCompatActivity { @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); WebView webView = findViewById(R.id.webView); //WebSettings webSettings = webView.getSettings(); webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setJavaScriptEnabled(true); // webSettings.setJavaScriptEnabled(true); // webSettings.setDomStorageEnabled(true); webView.getSettings().setUseWideViewPort(true);//setting wide view webView.getSettings().setLoadWithOverviewMode(true);//setting default zoomed out view webView.setInitialScale(1); webView.getSettings().setBuiltInZoomControls(true);//setting zoom controls webView.loadUrl("https://neurofinance.rf.gd/"); WebViewClient webViewClient = new WebViewClient() { @SuppressWarnings("deprecation") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @TargetApi(Build.VERSION_CODES.N) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { view.loadUrl(request.getUrl().toString()); return true; } }; webView.setWebViewClient(webViewClient); } } <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.neurofinance"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:configChanges="orientation|keyboardHidden|screenSize">> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Problem My webview does not show the navigation menu (dots) and the banner. The following two screenshots show my webview (left) and the website itself (right). The solution from this post did not help. Namely, I tried these: webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); Can anyone suggest to me what I can do here? |
Should HTTP GET be always read only? Posted: 02 Sep 2021 07:55 AM PDT Just curious should we always follow the RFC and do not update any state on GET It could be more complicated for example we have a separated state in 2 DB (its different services connected via API and an internal bus, but I've simplified it to the DB state), lets name it DB1 and DB2 DB1 has a table with guid (key), doc id (external document id in DB2) DB2 has a table doc id(key), externalID (guid from DB1 table) upon POST to DB1 service we do - DB1 insert: guid, empty doc id
- call to DB2 service (on success DB2 insert doc id, ExternalID=guid from DB1)
- update DB1 with doc id (after successful reply from 2)
if something goes wrong when processing the results from 2. then DB1 state becomes inconsistent with DB2 (assume that data was inserted in DB2 correctly, but we failed to receive a reply) On every GET we do fetch for possible record created in DB2 by guid -> ExternalID and upon finding an inconsistent state it's possible to align it with GET request and do update like on 3. after it the state is corrected, and all following GET will provide the same results what for? If the first service knows doc id it does not need to fetch this document via guid -> ExternalID (an extra communication call) on DB2 service Yes, it's a bit weird because first creation call must report an error due to failure in receiving a reply from 2., but as the result on the next GET everything can be fixed and start to work correctly. |
AdMob stopped showing ads after published on Play store by itself Posted: 02 Sep 2021 07:55 AM PDT I made an app with unity. After I publish the app, test ads was totally showing fine. Then i change test ids to real ad Id's and update the app from play console. After update is published the app working totally fine. After one day i try to open app but it starts crashing everytime i try to open. Then i thought it was a problem with AdMob plugin. I remove the plugin and then reinstall it. And app were running fine. Its been 3 days my app not gives any crash but ads not shows at all. I've consumed everything that can explore from the internet. I want to ask you that anyone have a info about that. Thanks. In the logcat the error that i get on start: Error Unity ArgumentNullException: Value cannot be null. Error Unity Parameter name: type Error Unity at System.Activator.CreateInstance (System.Type type, System.Boolean nonPublic) [0x00000] in <00000000000000000000000000000000>:0 Error Unity at GoogleMobileAds.Api.MobileAds.GetClientFactory () [0x00000] in <00000000000000000000000000000000>:0 Error Unity at GoogleMobileAds.Api.MobileAds.GetMobileAdsClient () [0x00000] in <00000000000000000000000000000000>:0 Error Unity at GoogleMobileAds.Api.MobileAds..ctor () [0x00000] in <00000000000000000000000000000000>:0 Error Unity at GoogleMobileAds.Api.MobileAds.get_Instance () [0x00000] in <00000000000000000000000000000000>:0 Error Unity at GoogleMobileAds.Api.MobileAds.Initialize (System.Action`1[T] initCompleteAction) [0x00000] in <00000000000000000000000000000000>:0 Error Unity at RewardedAdManager.Awake () [0x00000] in <00000000000000000000000000000000>:0 BannerView Script: public class BannerViewAdManager : MonoBehaviour { private BannerView bannerView; public string bannerViewId = "ca-app-pub-3940256099942544/6300978111"; // Test private void Awake() { MobileAds.Initialize(InitializationStatus => { }); if (PlayerPrefs.HasKey("ads") == false && PauseAds.AdWathced == false) { RequestBanner(); } else { if(this.bannerView != null) { HideBanner(); } } } private void RequestBanner() { AdSize adaptiveSize = AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth); this.bannerView = new BannerView(bannerViewId, adaptiveSize, AdPosition.Bottom); AdRequest request = new AdRequest.Builder().Build(); this.bannerView.LoadAd(request); } public void HideBanner() { this.bannerView.Hide(); this.bannerView.Destroy(); } } Interstitial script: using UnityEngine; using GoogleMobileAds.Api; using System; using UnityEngine.SceneManagement; using System.Collections.Generic; public class InterstitialToScene : MonoBehaviour { public InterstitialAd interstitial; public string interstitialId = "ca-app-pub-3940256099942544/1033173712"; // Test public string targetSceneName; public List<GameObject> withAds; public List<GameObject> withoutAds; private void Awake() { MobileAds.Initialize(InitializationStatus => { }); RequestInterstitial(); } private void RequestInterstitial() { if (this.interstitial != null) { this.interstitial.Destroy(); } this.interstitial = new InterstitialAd(interstitialId); this.interstitial.OnAdFailedToLoad += HandleOnAdFaildToLoad; this.interstitial.OnAdFailedToShow += HandleOnAdFaildToShow; this.interstitial.OnAdClosed += HandleOnAdClosed; AdRequest request = new AdRequest.Builder().Build(); this.interstitial.LoadAd(request); ChangeBtnsByAds.isAdsActive = true; Debug.Log("-> Interstitial Ad Requested"); Debug.Log("-> isAdsActive = true (Ads button will be activate)"); } public void ShowInterstitial() { if(this.interstitial.IsLoaded()) { if (PlayerPrefs.HasKey("ads") == false && PauseAds.AdWathced == false) { this.interstitial.Show(); } else { SceneManager.LoadScene(sceneName: targetSceneName); } } else { SceneManager.LoadScene(sceneName: targetSceneName); } } } Rewarded script: using UnityEngine; using GoogleMobileAds.Api; using System; using UnityEngine.SceneManagement; using System.Collections; public class RewardedAdManager : MonoBehaviour { private RewardedAd rewarded; public string rewardedId = "ca-app-pub-3940256099942544/5224354917"; // Test public PauseAds pauseAds; public GameObject warningMessagePage; public GameObject stopAdsPage; public GameObject stopAdsButton; public BannerViewAdManager bannerViewAdManager; private void Awake() { MobileAds.Initialize(InitializationStatus => { }); if (PlayerPrefs.HasKey("ads") == false && PauseAds.AdWathced == false) { RequestRewarded(); } } private void RequestRewarded() { if (this.rewarded != null) { this.rewarded.Destroy(); } this.rewarded = new RewardedAd(rewardedId); this.rewarded.OnAdFailedToLoad += HandleOnAdFaildToLoad; this.rewarded.OnAdFailedToShow += HandleOnAdFaildToShow; this.rewarded.OnAdClosed += HandleOnAdClosed; AdRequest request = new AdRequest.Builder().Build(); this.rewarded.LoadAd(request); Debug.Log("-> Rewarded Ad Requested"); } public void ShowRewarded() { if (PlayerPrefs.HasKey("ads") == false) { if (this.rewarded.IsLoaded()) this.rewarded.Show(); } } } |
How to show zeros count in datastudio report Posted: 02 Sep 2021 07:55 AM PDT I am preparing a report with some data of places and the number of visits to these places by a list of staff. That is, each person has to visit a number of places in the week. I need to show the list of people, the place and count the total visits in the week. I have two databases, the first one contains the person in charge and the place. And in the other one I have the history of visits where is the person, the week and the place. However, I want to show the places that are still to be visited in a specific week. But as there is no data int the history database, datastudio does not show anything, I need it to show me the place, week and zeros. I tried to merge those two databases but i couldn't find solution. The week is numeric and the other are text. Thanks for your help |
GitPython: How to detect if file is deleted? Posted: 02 Sep 2021 07:55 AM PDT I'm writing an automated script to process staged/unstaged files for a pre-commit hook. I would like to be able to know if a file is marked as deleted by git ("D " or " D" in git status --porcelain -- {filename} ) so that I can remove it from the list. I would like to do so through the GitPython API if possible. Previously attempted steps: I couldn't find in the documentation any reference to "delete" that related to this use case Using dir(item) where item is a Diffable from repo.index.diff(None) reveals the following members: ['NULL_BIN_SHA', 'NULL_HEX_SHA', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '_handle_diff_line', '_index_from_patch_format', '_index_from_raw_format', '_pick_best_path', 'a_blob', 'a_mode', 'a_path', 'a_rawpath', 'b_blob', 'b_mode', 'b_path', 'b_rawpath', 'change_type', 'copied_file', 'deleted_file', 'diff', 'new_file', 'raw_rename_from', 'raw_rename_to', 're_header', 'rename_from', 'rename_to', 'renamed', 'renamed_file', 'score'] out of which deleted_file seems to be the only sensible candidate - but it doesn't seem to reflect the result of git status --porcelain since all deleted files in git status are set to deleted_file=False (same as non-deleted ones). For now I am relying on git directly to assert if a file is deleted or not: def _is_deleted(path: str): files = _gitstatus() return 'D' in files[path] @lru_cache(maxsize=1) def _gitstatus(): child = subprocess.Popen(["git", "status", "--porcelain"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = [stream.decode('utf-8') if stream is not None else '' for stream in child.communicate()] if child.returncode != 0: raise Exception(err) files = { line[3:]: tuple(line[0:2]) for line in out.split('\n') } return files but I'd much prefer using the GitPython API if possible. Any idea how to achieve the equivalent result of the above function? |
creating Mat with openCV in python Posted: 02 Sep 2021 07:55 AM PDT I am used to java 's implementation of OpenCV . I want to create a Mat structure, fill data into it, extract a submat and then apply some image transform. So in java , I use my_mat = new Mat(my_rows, my_cols, CvType.CV_8U); my_mat.put(0, 0, my_data); my_mat.submat(0, my_other_rows, 0, my_other_cols); But I didn't find anything working in python 's OpenCV . I found this link but it is broken |
No comments:
Post a Comment