Bind mount Chrome 'User Data' to Docker Container on Windows Posted: 27 Jul 2021 07:47 AM PDT Our objective is to run a Selenium Python script that communicates with a docker container 'Selenium-standalone chrome'. So far we have been able to pass the IP address and port no. which the container is running on, and the script is working pretty fine, but we need the container to access our local Chrome "User Data" to use saved credentials. Been trying this command but still doesn't initiate the binding: docker run -d -p 4444:4444 --shm-size="2g" -v "C:%LOCALAPPDATA%\Google\Chrome\User Data":/data selenium/standalone-chrome |
Laravel Vapor Unable to Download DOCX or XLSX file types Posted: 27 Jul 2021 07:46 AM PDT I am using Laravel vapor to host my application, and I am having issue downloading certain file types from AWS S3. I'm wondering if this is a CloundFront issue with the request headers not allowing these file types. Since I am able to download PNG, JPG, PDF files fine, I just have issue with files like DOCX & XLSX. In my API I am just using the Storage facade to stream the download. /** * Download file from storage * @param Document $document * @return StreamedResponse */ public function download(Document $document): StreamedResponse { return Storage::disk('s3')->download($document->path); } Here are the request header which I believe are set accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 This is the error that is thrown |
What is more important for SEO? LCP or CLS Posted: 27 Jul 2021 07:46 AM PDT Hey quick question and hoping for a simple answer. What is more important for SEO... LCP (Largest Contentful Paint) or CLS (Cumulative Layout Shift)? I can get CLS down to 0.00 but LCP for example may be 7s. But I can also get LCP down to .8s but CLS may increase to .2 (which is still in a fair range). Although I do see that LCP impacts the performance score of Google Lighthouse more than CLS when being calculated.. Any thoughts or advice? |
I created a new page template in the Understrap theme page template folder and now my custom js wont work on my main page Posted: 27 Jul 2021 07:46 AM PDT I created a template-home.php file under my page-templates folder and made it my default main screen. My custom js was working on the default menu screen for understrap, however after i changed the main screen to to template-home.php the custom js wont work. Any advice on why this is happening? |
Can not add column after adding view - mariadb Posted: 27 Jul 2021 07:45 AM PDT I have a table: CREATE TABLE queued_action( entity_id VARCHAR(100) NOT NULL, entity_type varchar(100) NOT NULL, control_level INT NOT NULL, control_action json NOT NULL, processed_at TIMESTAMP(3) NULL, processing_error varchar(256) NULL ); and then Ive created a view: CREATE VIEW top_control_level_queued AS SELECT qa.entity_id, qa.entity_type, qa.control_level, qa.control_action, qa.processed_at,qa.processing_error FROM queued_action qa LEFT JOIN control_lock cl ON qa.entity_id = cl.entity_id AND qa.entity_type = cl.entity_type WHERE qa.processed_at IS NULL AND (qa.control_level, qa.entity_id, qa.entity_type) IN (SELECT MIN(qa2.control_level), qa2.entity_id, qa2.entity_type FROM queued_action qa2 GROUP BY qa2.entity_id, qa2.entity_type) AND (cl.control_level > qa.control_level OR ( cl.control_level IS NULL OR (cl.tr_from > current_timestamp(3) OR cl.tr_to < current_timestamp(3)) )); I use flyway migrations. So as a next step after time I need now to add new column so Ive added new sql: ALTER TABLE queued_action ADD queued_until TIMESTAMP(3) NULL; and I have an error: SQL Error [1054] [42S22]: (conn=29) Unknown column 'my_db .qa .control_action ' in 'CHECK' when I try to create this table, without adding a view, no problem at all. Anyone can help me ? thanks! ( version of database: mariadb-10.6 ) |
React native showing TypeError: undefined is not an object (evaluating 'Context._context') Posted: 27 Jul 2021 07:46 AM PDT I'm using context API to store my user-information in the state. First I tried to use the createContext in app.js and provided my value and everything worked fine. but I was getting a warning which is about require cycles. So I thought If I create the context in a different file I won't get the warning. So I created a js file called appContext.js ** appContext.js** import React from "react"; export const AppContext = React.createContext({}); then I tried to use it in my app.js file like this import Home from "./Screens/Home"; import Signup from "./Screens/Form/Signup"; import Login from "./Screens/Form/Login"; import { AppContext } from "./appContext"; const Drawer = createDrawerNavigator(); function App() { const [userInfo, setUserInfo] = useState({ userName: null, userEmail: null, userPhone: { number: null, countryCode: null, }, userLoggedIn: false, }); return ( <AppContext.Provider value={{ userState: [userInfo, setUserInfo], }} > {userInfo.userLoggedIn ? ( <NavigationContainer> <Drawer.Navigator initialRouteName="Home"> <Drawer.Screen name="Home" component={Home} /> </Drawer.Navigator> </NavigationContainer> ) : ( <NavigationContainer> <Drawer.Navigator edgeWidth={0} initialRouteName="Sign Up"> <Drawer.Screen name="Login" component={Login} /> <Drawer.Screen name="Sign Up" component={Signup} /> </Drawer.Navigator> </NavigationContainer> )} </AppContext.Provider> ); } But Im getting this error: |
Convert async function to RxJs Observable Posted: 27 Jul 2021 07:46 AM PDT To prevent writing a certain amount of code, such as this example: ... public getDataSet() : Observable<any> { return new Observable(observer => { if (this.dataset === undefined) { this.get().subscribe(data => { this.dataset = new DataSet(data) ; observer.next(this.dataset) observer.complete() ; }) ; } else { observer.next(this.dataset) observer.complete() ; } }) ; } I would like to use async/await feature but still return an Observable to remain consistent in using asynchronous data gathering services. Thus according to RxJs's documentation, I should be using from() operator. https://www.learnrxjs.io/learn-rxjs/operators/creation/from Here is what I try to implement (which looks much more concise) : import { Observable, from } from 'rxjs' ; ... return from(async () => { // ✘ error if (this.dataset === undefined) this.dataset = new DataSet(await this.get().toPromise()) ; return this.dataset ; }) ; However, TypeScript doesn't recognize async () => {} as an ObservableInput , but it does recognize this one : import { Observable, from } from 'rxjs' ; ... return from(new Promise((resolve) => { // ✔ valid if (this.dataset === undefined) { this.get().toPromise().then(data => { this.dataset = new DataSet(data) ; resolve(this.dataset) ; }) ; } else resolve(this.dataset) ; })) ; Though, JavaScript's async keyword makes a function always return a Promise. console.log((async () => {}) ()) // Promise {} Is there a way to make the from() RxJs operator accepting async promises ? |
TSQL Calculated column Posted: 27 Jul 2021 07:46 AM PDT I'm trying to calculate Indice column. Daily variation works fine. But when I try to calculate Indice query returns nothing. It works when I change ((1 * DailyVariation) + 1) as Indice to 0 as Indice I'm probably doing something really dumb, could someone help me? CREATE TABLE #temp ( Revenue MONEY, PreviousBalance MONEY, DailyVariation DECIMAL(6, 5), Indice DECIMAL(8, 7) ) insert into #temp SELECT PreviousBalance Revenue (Revenue / PreviousBalance) as DailyVariation -- eg.: -0,06077% ((1 * DailyVariation) + 1) as Indice -- should be something like 0,999392313 -- IT WORKS WITHOUT THIS LINE FROM tableA select * from #temp |
Compilation error when overloading a previously defined within a namespace function template Posted: 27 Jul 2021 07:45 AM PDT Is it a MinGW bug or an expected behavior? - This version compiles:
template<typename T> constexpr auto get_foo(T &t) { return t.foo(); } template<typename Impl> class dummy { public: dummy() { [[maybe_unused]] auto &&foo = get_foo(impl_); } private: Impl impl_; }; struct Foo{}; using TupleFoo = std::tuple<Foo>; Foo &get_foo(TupleFoo &tuple) { return std::get<Foo>(tuple); } int main(int, char **) { TupleFoo tuple{}; [[maybe_unused]] auto &&foo = get_foo(tuple); [[maybe_unused]] auto d = dummy<TupleFoo>(); return 0; } - This version will not compile when instantiating
dummy : namespace custom { template<typename T> constexpr auto get_foo(T &t) { return t.foo(); } template<typename Impl> class dummy { public: dummy() { [[maybe_unused]] auto &&foo = get_foo(impl_); } private: Impl impl_; }; } struct Foo { }; using TupleFoo = std::tuple<Foo>; namespace custom { Foo &get_foo(TupleFoo &tuple) { return std::get<Foo>(tuple); } } int main(int, char **) { TupleFoo tuple{}; [[maybe_unused]] auto &&foo = custom::get_foo(tuple); // [[maybe_unused]] auto d = custom::dummy<TupleFoo>(); // will not compile return 0; } - This version will compile:
// Type and function definitions come before templates struct Foo { }; using TupleFoo = std::tuple<Foo>; namespace custom { Foo &get_foo(TupleFoo &tuple) { return std::get<Foo>(tuple); } } namespace custom { template<typename T> constexpr auto get_foo(T &t) { return t.foo(); } template<typename Impl> class dummy { public: dummy() { [[maybe_unused]] auto &&foo = get_foo(impl_); } private: Impl impl_; }; } int main(int, char **) { TupleFoo tuple{}; [[maybe_unused]] auto &&foo = custom::get_foo(tuple); [[maybe_unused]] auto d = custom::dummy<TupleFoo>(); // will not compile return 0; } I would understand if version 3 would work, but 1 and 2 would not compile regardless of using a namespace. But 1 and 2 behave differently. Practically using 3 is inconvenient since one would have to include header with templates after function declaration. That could lead to very ambiguous errors. Error: In instantiation of 'constexpr auto custom::get_foo(T&) [with T = std::tuple<Foo>]': ../Modules/eos/sandbox/sb_eos_algorithm.cpp:72:56: required from 'custom::dummy<Impl>::dummy() [with Impl = std::tuple<Foo>]' ../Modules/eos/sandbox/sb_eos_algorithm.cpp:93:55: required from here ../Modules/eos/sandbox/sb_eos_algorithm.cpp:65:18: error: 'class std::tuple<Foo>' has no member named 'foo'; did you mean 'struct Foo Foo::Foo'? (not accessible from this context) 65 | return t.foo(); |
Set to Monday of selected week on change Posted: 27 Jul 2021 07:45 AM PDT I am using bootstrap datetimepicker for my date select field which displays week Mon - Sun. When a user clicks on any date in the week, I need it to set Monday as the date. The below code works great except when the user clicks on Sunday, it selects Monday from the following week. $('#start_date').on('dp.change', function (e) { var value = $("#start_date").val(); var firstDate = moment(value, "YYYY-MM-DD").day(1).format("YYYY-MM-DD"); $("#start_date").val(firstDate); }); How can I have the date set to Monday of the week displayed when Sun is selected. |
Declaring Heat Capacity Cp in Dymola Posted: 27 Jul 2021 07:46 AM PDT I am having some problems to call the Specific Heat Capacity of my working fluid that in this case is Hydrogen, I can't call it using the Pressure or either the Temeperature, if someone could help me please, thanks in advance. Here is my code import Modelica.SIunits; package Hyd extends ExternalMedia.Media.CoolPropMedium( mediumName="hydrogen", substanceNames={"hydrogen"}, inputChoice=ExternalMedia.Common.InputChoice.pT); end Hyd; SIunits.SpecificHeatCapacity cp_in;//[J/kg*K] Hyd.AbsolutePressure Pb_0; Hyd.Temperature Tin; Hyd.SaturationProperties sat9,sat10; Equation sat9=Hyd.setSat_T(Tin); sat10=Hyd.setSat_p(Pb_0); cp_in=Hyd.specificHeatCapacityCp(sat9);//[J/kg*K] cp_in=Hyd.specificHeatCapacityCp(sat10);//[J/kg*K] The function is declared as: function specificHeatCapacityCp_Unique8 input ExternalMedia.Media.BaseClasses.ExternalTwoPhaseMedium.ThermodynamicState state ; output Modelica.Media.Interfaces.Types.SpecificHeatCapacity cp := 1000.0 "Specific heat capacity at constant pressure"; end specificHeatCapacityCp_Unique8; |
Unable to use OffsetDateTime as a query parameter using JPA Data/JPQL Posted: 27 Jul 2021 07:46 AM PDT I have an Entity CustomEntity with a data member updateDate of type OffsetDateTime . I have defined a Repository for this Entity which has a simple method to retrieve list of records matching updateDate as List<CustomEntity> findByUpdateDate(OffsetDateTime updateDate); Now, when this method is called from Controller/Service bean, I can see no matching record is retrieved; however, when I execute the generated SQL in the DB, I can see matching rows available. I can retrieve the records based on other data members of the entity; its just an issue with OffsetDateTime and LocalDateTime I got to understand that java.time package support was not in JPA 2.1; however I am using JPA 2.3.1. Do I need to use Converter s (as suggested for JPA 2.1? Any help is much appreciable. EDIT :- Below is the code for Entity @Entity @Table(name = "SAMPLE_TABLE") public class CustomEntity { @Id @GeneratedValue private Long id; @Column private OffsetDateTime updateDate; //Getters & Setters } I am using Microsoft SQL Server and the generated SQL query (hibernate generated) looks something like below select sample0_.id as id1_10, sample0_.updateDate as update2_10 from sample_table sample0_ where sample0_.updateDate=? binding parameter [1] as [TIMESTAMP] - [2021-07-27T17:22:34.597Z] |
Customize material UI Switch when checked and disabled Posted: 27 Jul 2021 07:46 AM PDT I'm having trouble adding the styling to a Material UI Switch in React when it is disabled. I'd like to use withStyles for this. The handling for the checked vs unchecked states works fine as does the styling for the track, but nothing I've tried has worked to style the disabled state of either the thumb or the track. Here's the code I'm using including some commented out attempts to style the disabled state: const MySwitch = withStyles({ switchBase: { color: "orange", opacity: 0.8, "&$checked": { color: "orange", opacity: 1 }, "&$checked + $track": { backgroundColor: "black", opacity: 1 }, // "&$checked + $disabled": { // color: "gray", // opacity: 1 // }, // "&disabled": { // color: "gray", // opacity: 1 // }, // "&:disabled": { // color: "gray", // opacity: 1 // }, }, // disabled: { // "& + $thumb": { // color: "gray" // } // }, checked: {}, track: {} })(Switch); Any thoughts? |
How do I make a webpage only available once? Posted: 27 Jul 2021 07:46 AM PDT I am trying to make a webpage that only new users can see if a returning viewer returns he will be redirected to another webpage I found this on stackoverflow but I am unable to figure it out. I have made a HTML and CSS page which showcases the features of my web app. I want this page to load only for new visitors. If a returning visitor visits my domain, it should redirect him/her to the web platform. Essentially, the new user should see "Landing Page" while a returning user should be redirected to "Web Platform" The answer was How do I make a web page show up only once? I am unable to use it because I don't know what to do and how to create localstorage |
Laravel is suspiciously slow (fresh app, everything is by default) Posted: 27 Jul 2021 07:46 AM PDT I work with Windows 10. My hardware is: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz 2.60 GHz RAM 8.00GB SSD Actually, this is a game laptop (MSI GL 65 95CK) if you are interested. I decided to install Laravel, went to documentation and implemented described steps: - In WSL terminal (I use Ubuntu)
curl -s "https://laravel.build/example-app?with=mysql,redis" | bash cd example-app && /vendor/bin/sail up I went to browser and realized that the main page took almost 1 second to render! Sometimes even two seconds! I thought, "ok, maybe the framework is in a not optimized mode. Debug and so on", and decided to turn APP_DEBUG in .env to false . I also removed all routes and put this instead: Route::get('/', [\App\Http\Controllers\TestController::class, 'test']); Before this, I created the TestController : class TestController extends Controller { public function test() { return response()->json([ 'name' => 'Abigail', 'state' => 'CA', ]); } } Then I run php artisan optimaze , open in browser http://localhost/api and the result is a big sorrow: Why 800ms? I did not do anything. Ok, I decided just to rename the index.php file in the public folder to index2 for example, put new one index.php with the array printing just to test whether this is a Laravel problem or this is just an infrastructure issue. New index.php : Much better! Then I thought, "let's compare with another framework, for example with .NET Core". And I made a very simple Web Api project. Controller: namespace MockWebApi.Controllers { [ApiController] [Route("")] public class MainController : ControllerBase { [Route("test")] public IActionResult Test() { return Ok(new { Test = "hello world!!!" }); } } } The result is: Ok, you can argue that this is a compiled language. I decided to check with Node.js and Express: Code: router.get('/', function(req, res, next) { res.json({"test": "123"}) }); Result: As you can see, Node as fast as C# in this case. So, what is wrong with Laravel? Did I miss something in installation? UPDATE I raised Laravel without Sail. My docker-compose file: version: '3' services: php-fpm: build: context: docker/php-fpm volumes: - ./:/var/www networks: - internal nginx: build: context: docker/nginx volumes: - ./:/var/www ports: - "80:80" depends_on: - php-fpm networks: - internal networks: internal: driver: bridge Nginx Dockerfile: FROM nginx ADD ./default.conf /etc/nginx/conf.d/default.conf WORKDIR /var/www Nginx config: server { listen 80; index index.php; server_name 127.0.0.1 localhost; root /var/www/public; location / { try_files $uri /index.php?$args; } location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass php-fpm:9000; fastcgi_index index.php; fastcgi_read_timeout 1000; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; } } php-fpm Dockerfile: FROM php:7.4-fpm RUN apt-get update && apt-get install -y wget git unzip \ && apt-get install libpq-dev -y RUN wget https://getcomposer.org/installer -O - -q \ | php -- --install-dir=/bin --filename=composer --quiet RUN groupadd -r -g 1000 developer && useradd -r -u 1000 -g developer developer USER developer WORKDIR /var/www I did not get any performance improvement( |
MS Access System Resources exceeded with select query Posted: 27 Jul 2021 07:46 AM PDT I saw this question asked a few times here but none i saw seemed to address my specific issue. I have a select query that is pulling from 2 linked tables. When i run the query about 5 min later i get an error saying system resources exceeded. Any idea how i can fix this? Below is my query, The two tables are rather large with 146k rows and 24 columns in one and 312K rows and 67 columns in the other. Is this just too much data for Access? SELECT [Learner Name]=[learning item number] AS [Key], Date() AS [Business Day], [business day] - [updated due date] AS [Days Overdue], Iif([days overdue] > 0, "true", "false") AS [Greater Than Zero], assignments.[standard id], assignments.[learner name], [email] AS [Email Address], active_workforce.employee_status, active_workforce.employee_type, active_workforce. [bank title desc], assignments.[learning item number], assignments.[learning item name], assignments.[learning item type], assignments.[enrollment record status], assignments.[enrollment record substatus], assignments.[enrollment type], assignments.[enrolled on date], assignments.[due date], Iif([due date] BETWEEN #3 / 16 / 2020 # AND #7 / 31 / 2020 # , [due date] + 30, [due date]) AS [Update Due Date], assignments.[upcoming or overdue], assignments.[business unit], assignments.department, active_workforce.job_code, assignments.job, assignments. [legal employer], assignments.[manager name], assignments.[manager sid], assignments. [location name], assignments.position, active_workforce.start_dt, active_workforce.cost_ctr_nbr, active_workforce.cost_ctr_desc, active_workforce.city, active_workforce.country_name, active_workforce.region_code, active_workforce.company, active_workforce.level_02_manager_sid, active_workforce.level_02_manager, active_workforce.level_03_manager_sid, active_workforce.level_03_manager, active_workforce.level_04_manager_sid, active_workforce.level_04_manager, active_workforce.level_05_manager_sid, active_workforce.level_05_manager, active_workforce.level_06_manager_sid, active_workforce.level_06_manager, active_workforce.level_07_manager_sid, active_workforce.level_07_manager, active_workforce.level_08_manager_sid, active_workforce.level_08_manager, active_workforce.level_09_manager_sid, active_workforce.level_09_manager, active_workforce.level_10_manager_sid, active_workforce.level_10_manager, active_workforce.[lob code], active_workforce.[lob description], active_workforce.[sub lob code], active_workforce.[sub lob description], active_workforce.[level 7 code], active_workforce.[level 7 description], active_workforce.[level 8 code], active_workforce.[level 8 description], active_workforce.[level 9 code], active_workforce.[level 9 description], active_workforce.[level 10 code], active_workforce.[level 10 description], active_workforce.[level 11 code], active_workforce.[level 11 description], active_workforce.[level 12 code], active_workforce.[level 12 description], active_workforce.[level 13 code], active_workforce.[level 13 description], active_workforce.[level 14 code], active_workforce.[level 14 description] FROM assignments INNER JOIN active_workforce ON assignments.[standard id] = active_workforce.sid; |
What is the Java equivalent to Kotlin's take() method? Posted: 27 Jul 2021 07:45 AM PDT I'm working on a memory card game that display matches images, the lesson on youtube was in kotlin and there's a method called take() that takes int number to display the images according to the number of cardviews i implemented in adapter. i'm trying to create the game but in java and i need to display the images for all the card i have and can't figure out what is the equivalent for this method take() in java this is the approach i came up with for the list: drawables = new ArrayList<>(); drawables.add(R.drawable.ic_face); drawables.add(R.drawable.ic_flash); drawables.add(R.drawable.ic_flower); drawables.add(R.drawable.ic_gift); drawables.add(R.drawable.ic_heart); drawables.add(R.drawable.ic_house); drawables.add(R.drawable.ic_moon); drawables.add(R.drawable.ic_plane); drawables.add(R.drawable.ic_school); drawables.add(R.drawable.ic_send); drawables.add(R.drawable.ic_star); drawables.add(R.drawable.ic_work); //shuffle both arrays ArrayList<Integer> secondDrawable = new ArrayList<>(drawables); Collections.shuffle(secondDrawable); |
Random characters instead of String input in Combobox Items? Posted: 27 Jul 2021 07:46 AM PDT I am trying to create a choicebox in my application using javafx/scenebuilder in IntelliJ but so far am not able to get Strings to show as menu items - in the example screenshot below I have just tried to create an option with the letter C? The code I have used is below. Any ideas what I am doing wrong? I thought it might be a font issue but I can't find a way to change the font of the menu items. <AnchorPane prefHeight="45.0" prefWidth="127.5"> <children> <Text fill="WHITE" strokeType="OUTSIDE" strokeWidth="0.0" text="I" AnchorPane.leftAnchor="11.0" AnchorPane.topAnchor="4.0"> <font> <Font name="Courier Bold" size="40.0" /> </font> </Text> <ChoiceBox fx:id="keyChoice" prefWidth="79.0" style="-fx-background-color: #FBC5B8;" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="8.0"> <items> <FXCollections fx:factory="observableArrayList"> <String fx:value="C" /> </FXCollections> </items> </ChoiceBox> </children> </AnchorPane> |
unable to run afterScenario with tag in config.js file for webdriverio cucumberjs framework Posted: 27 Jul 2021 07:46 AM PDT I am working on webdriverio CucumberJS BDD framework. I want to execute some code in afterScenario of wdio.config.js file for scenarios marked with particular tag eg @setting. I already have below afterScenario setup in my wdio.config.js. How can I run afterScenario with set of code only for particular tags from feature file? /** * Runs after a Cucumber scenario */ afterScenario: function (uri, feature, scenario, result, sourceLocation, context) { if (commonHelper.elements.userMenuLink.isDisplayed()) { commonHelper.clickLogout(); } browser.deleteAllCookies(); }, I tried to insert below code in above file but it doesnt work let isLastTag; scenario.pickle.tags.forEach(tag => { isLastTag = tag.equals("@settings"); }); if(isLastTag.contains('settings')) { console.log('Setting key worked'); } |
Autoencoder and Inception Resnet V2 feature Posted: 27 Jul 2021 07:47 AM PDT I want to create an autoencoder starting from the vector of the features extracted with the Inception Resnet V2 model and following the diagram shown in the following image: This is the code I wrote at the moment: image_size = (150, 150, 3) model = InceptionResNetV2(weights='imagenet', include_top=False, input_shape=image_size) for layer in model.layers: layer.trainable = False feature = model.predict(x[:10]) print(feature.shape) # (10, 3, 3, 1536) What is the way to implement this in Keras? Thank you for your time. |
rails model scope doesnt select good query Posted: 27 Jul 2021 07:46 AM PDT I would like to select my Offers available during dates range, I compare arrival and departure dates search params with bookings confirmed of each offer in a scope. scope :booking_available, -> (arrival_date, departure_date) { includes(:bookings).references(:bookings) .where.not('bookings.arrival_date <= ? AND bookings.departure_date >= ? AND bookings.status != ?', arrival_date, departure_date, 0) } And call it in my search function in controller. if offer_params[:arrival_date].present? && offer_params[:departure_date].present? @offers = @offers.booking_available(offer_params[:arrival_date], offer_params[:departure_date]) end But the result give me only offers not available, I think .not in my query doesn't work and I don't know how fix it. |
How to flatten multiple raster and plot all pixel values on a single histogram? Posted: 27 Jul 2021 07:46 AM PDT I'm trying to extract the pixel values of a large list (stack or brick) of raster with 483 elements , then plot these values on a single histogram to check if the values are bimodal. Please, what's the best way to approach this? I tried using the ra1 <- flattenBrick(all_tiffs, thresh = NULL) but got this error ra1 <- flattenBrick(all_tiffs, thresh = NULL) Error in (function (classes, fdef, mtable) : unable to find an inherited method for function 'calc' for signature '"list", "function"' Then, I tried this ra2 <- as.array(evi_flat) and got this error ra2 <- as.array(evi_flat) Error: cannot allocate vector of size 41.5 Gb Please, data can be found here test.RData. Thank you. |
woocomerce doesn't return all orders Posted: 27 Jul 2021 07:46 AM PDT I'm using C# to get all orders. I use an end point of https://mywebsite.com/wp-json/wc/v3/orders I'm expecting all orders back, but I only receive 10. Is there a setting in wordpress or wooCommewrce that restricts this? Here is the actual C# code I use to get the data: private string Get(string fullendpoint) { string requestURL = @fullendpoint; UriBuilder tokenRequestBuilder = new UriBuilder(requestURL); var query = HttpUtility.ParseQueryString(tokenRequestBuilder.Query); query["oauth_consumer_key"] = consumerkey; query["oauth_nonce"] = Guid.NewGuid().ToString("N"); query["oauth_signature_method"] = "HMAC-SHA1"; query["oauth_timestamp"] = (Math.Truncate((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds)).ToString(); string signature = string.Format("{0}&{1}&{2}", "GET", Uri.EscapeDataString(requestURL), Uri.EscapeDataString(query.ToString())); string oauth_Signature = ""; using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(woosecret + "&"))) { byte[] hashPayLoad = hmac.ComputeHash(Encoding.ASCII.GetBytes(signature)); oauth_Signature = Convert.ToBase64String(hashPayLoad); } query["oauth_signature"] = oauth_Signature; tokenRequestBuilder.Query = query.ToString(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(tokenRequestBuilder.ToString()); request.ContentType = "application/json; charset=utf-8"; request.Method = "GET"; var httpResponse = (HttpWebResponse)request.GetResponse(); string result = string.Empty; using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = streamReader.ReadToEnd(); } httpResponse.Close(); return result; } and I call it with: var response = await Task.Run(() => Get(fullEndPoint)); I understand Woo uses paging and by default returns 10 at a time. If I use: var retval = new List<T>(); var fullEndPoint = string.Concat(site, "wp-json/wc/v3/", endpoint); int page = 1; int per_page = 10; var request = new RestRequest(Method.GET); while (true) { fullEndPoint = string.Concat(fullEndPoint, "?page=", page, "&per_page=", per_page); var response = await Task.Run(() => Get(fullEndPoint)); if (response.Length == 0) break; var deserializedData = JsonConvert.DeserializeObject<List<T>>(response); retval.AddRange(deserializedData); page++; } return retval; to make the call I receive unauthorised from the documetation woo documentation what I'm doing should be ok |
Dart http.MultipartRequest not sending data to Lumen after relocating server to a different apache server, Postman works fine Posted: 27 Jul 2021 07:46 AM PDT I have a multipart request I'm trying to send from my Flutter app to my remote Lumen/Apache server. This code was working fine when I was hosting my Lumen server in Homestead locally, which runs nginx. The Lumen server itself responds accurately when sending the request via Postman. I doubt the Flutter application is sending nothing at all, as it was working before the server move. Since it's not the Lumen app, as it works with Postman, then I presume it has something to do with apache. The header I set, using http.MultipartRequest() is (in Postman I used form-data ): headers['Content-Type'] = 'multipart/form-data'; I also have an Authorization Bearer: token header which works fine, as the app would've presented an Unauthorized response before running the route. I have the following code: ... print("Multipart request fields: " + request.fields.toString()); print("Multipart request files: " + request.files.toString()); var streamedResponse = await request.send(); response = await http.Response.fromStream(streamedResponse); if (response.statusCode == 200) print('Uploaded!'); I get the following output in debug: I/flutter ( 7073): Multipart request fields: {productName: new, description: new, price: 30.0, currency: USD, quantity: -1.0, mass: 0.0, massUnit: lb, isData: true} I/flutter ( 7073): Multipart request files: [Instance of 'MultipartFile'] In my Lumen application, I have a function that simply does: var_dump($request->all()); die; I get the following result: I/flutter ( 7073): array(1) { I/flutter ( 7073): ["_method"]=> I/flutter ( 7073): string(4) "POST" I/flutter ( 7073): } This arrived from the request not passing validation checks. Before this, I had the longer function: $validator = Validator::make($request->all(), [ 'productName' => 'required', 'description' => 'required', 'image' => 'sometimes|image|mimetypes:image/jpeg,image/png|max:600',// TODO remove sometimes from this 'price' => 'required', 'currency' => 'required|string', 'quantity' => 'required', 'mass' => 'numeric', 'massUnit' => 'required|string', 'isData' => 'present|string|nullable', ]); And it was failing the validation tests, even though the data was apparently being sent (and it used to pass before the server move). What could the reason be? It seems the only difference is moving from an nginx local Homestead server to a remote apache server. I thought maybe I need a different header, possibly. Update With some more testing, I found that the request works without error if there is no image in the multipart/form-data request. The issue seems to rely on there being a file attached. Apparently, when and only when there is a file attached, the server reports that no data was sent. I have two very similar requests, one that is POST and one that is PATCH. I found that with Postman, using the request that is a PATCH, sending it as a PATCH requests results in the same issue -- no data sent. Sending it as a POST request with the field "_method" set to "PATCH" does work, however. The request that is a POST request (to add a new item) works fine without the "_method" field, when set to a POST request. The POST endpoint is responding as if http is not sending a "POST" request (empty data). With the PATCH endpoint, Lumen is responding as if it was a "POST" request. Here's the difference between Postman and http.MultipartRequest : With POST request: Postman: POST request + "_method: POST": Works http: POST request + "_method: POST": No data sent With PATCH request: Postman: POST request + "_method: PATCH": Works Postman: PATCH request without "_method": No data sent http: POST request + "_method: PATCH": 405 Method Not Allowed (as if it was a PATCH request) Again, the properly formed requests work if there is no file attached (and everything else is the same). It's when the http request has a file that it suddenly works unexpectedly. In the last server, I could not fully test the http functionality as I was using localtunnel.js to forward requests to my phone from Homestead, but it has a file size limit that I didn't want to work with. I did know that dart's http was sending the file, however, due to the 413 Request Entity Too Large responses that didn't occur without the image. Here's the output of the request object in Flutter's DevTools (sorry it's a picture -- it doesn't permit selecting the text): When not including a file, the request looks identical except for that files list is empty. Despite this, a request without a file is received by the server with data, while the other results in no data apparently sent. The headers field of the request object looks fine too, with Content-Type being present. The authorization field clearly works, too, otherwise I would be getting unauthorized errors. Since the request object looks fine, something between request.send(); and the Lumen app is dropping all of the data if there is a file attached. Where it's coming from -- the Flutter app or the server -- is difficult to be sure about. (Considering the Flutter app was definitely sending something large when a file was attached when I was using localtunnel.js, it seems likely to be on the server side, as it seems the Flutter app is sending data, just the server is dropping it if there is a file. However, Postman works without hiccup, which suggests the server is functioning correctly.) |
Please how can i fix this "Object of class stdClass could not be converted to int" in codeigniter Posted: 27 Jul 2021 07:45 AM PDT i keep getting the error Object of class stdClass could not be converted to int and i don't know whats wrong. The error is in this line "if( $result > 0 ){" public function index() { $this->form_validation->set_rules('passwd', 'passwd', 'required|min_length[5]'); if($this->form_validation->run() == FALSE) { $this->load->view('login'); } else{ $where = array( 'email' => $_POST['email'], 'passwd' =>$_POST['passwd'] , ); $result = $this->LoginModel->login_user($where); if( $result > 0 ){ $sessiondata = array( 'email' => $where['email'], 'id' => $result->id, 'name' => $result->name, ); $this->session->set_userdata($sessiondata); return redirect('Location: home'); } else{ $this->session->set_flashdata('error_msg', 'wrong details'); return redirect('Welcome'); $this->db->close(); } } } And my model public function login_user($where){ $query = $this->db->where($where) ->get('admin'); if ($query-> num_rows() > 0) return $query->row(); else return false; } |
Save as PDF using Selenium and Chrome Posted: 27 Jul 2021 07:45 AM PDT I am trying to Save as pdf using the print dialog, a web page where I have already logged on using Selenium and Headless Chrome (v81). All the articles state I should be able to print/save the document as pdf using kiosk mode where the print to pdf happens automatically so the preview dialog is surpressed e.g. I cannot get Chrome to default to saving as a PDF when using Selenium Selenium Chrome save as pdf change download folder So far I have the following code: ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.AddArguments("--headless", "--disable-infobars", "--disable-extensions", "--test-type", "--allow-insecure-localhost", "--ignore-certificate-errors", "--ignore-ssl-errors=yes", "--disable-gpu", "--kiosk-printing", "--allow-running-insecure-content"); chromeOptions.AcceptInsecureCertificates = acceptInsecureCertificates; chromeOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Ignore; chromeOptions.AddUserProfilePreference("print.always_print_silent", true); chromeOptions.AddUserProfilePreference("download.default_directory", @"C:\Temp"); chromeOptions.AddUserProfilePreference("savefile.default_directory", @"C:\Temp"); chromeOptions.AddUserProfilePreference("download.prompt_for_download", false); chromeOptions.AddUserProfilePreference("printing.default_destination_selection_rules", "{\"kind\": \"local\", \"namePattern\": \"Save as PDF\"}"); chromeOptions.AddUserProfilePreference("printing.print_preview_sticky_settings.appState", "{\"recentDestinations\": [{\"id\": \"Save as PDF\", \"origin\": \"local\", \"account\": \"\" }],\"version\":2,\"isGcpPromoDismissed\":false,\"selectedDestinationId\":\"Save as PDF\"}"); webDriver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), chromeOptions, TimeSpan.FromMinutes(timeoutMinutes)); Then I print the page using this: var driver = FeatureContext.Current.GetWebDriver(); driver.ExecuteJavaScript("window.print();"); But I get the print preview dialog, always and my default printer is set and not Save as PDF. I would use the chrome command line however for the fact I need to be logged on to the site. What is wrong with the code above? |
HTTP Request in Android with Kotlin Posted: 27 Jul 2021 07:46 AM PDT I want to do a login validation using POST method and to get some information using GET method. I've URL, server Username and Password already of my previous project. |
How to best *fake* keyword style function arguments in Rust? Posted: 27 Jul 2021 07:46 AM PDT I'm interested to have something functionally similar to keyword arguments in Rust, where they're currently not supported. For languages that provide keyword argument, something like this is common: panel.button(label="Some Button") panel.button(label="Test", align=Center, icon=CIRCLE) I've seen this handled using the builder-pattern, eg: ui::Button::new().label("Some Button").build(panel) ui::Button::new().label("Test").align(Center).icon(CIRCLE).build(panel) Which is fine but at times a little awkward compared with keyword arguments in Python. However using struct initialization with impl Default and Option<..> members in Rust could be used to get something very close to something which is in practice similar to writing keyword arguments, eg: ui::button(ButtonArgs { label: "Some Button".to_string(), .. Default::default() } ); ui::button(ButtonArgs { label: "Test".to_string(), align: Some(Center), icon: Some(Circle), .. Default::default() }); This works, but has some down-sides in the context of attempting to use as keyword args: - Having to prefix the arguments with the name of the
struct (also needing to explicitly include it in the namespace adds some overhead). - Putting
Some(..) around every optional argument is annoying/verbose. .. Default::default() at the end of every use is a little tedious. Are there ways to reduce some of these issues, (using macros for example) to make this work more easily as a replacement for keyword access? |
Firebase Project Results in "Auth/network-request-failed" error on login Posted: 27 Jul 2021 07:46 AM PDT I'm running into a strange problem with my Cordova Project that uses Firebase. It works perfectly in browser, but when I run my app on an emulator or phone (Android), (at least) the first login attempt per load always results in an "Auth/network-request-failed" error. Here is my relevant Firebase code: <!-- Import Firebase JS --> <script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script> <!-- Import Firebase Authentication--> <script src="https://www.gstatic.com/firebasejs/ui/live/0.4/firebase-ui-auth.js"></script> <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/live/0.4/firebase-ui-auth.css" /> And here is my security meta-tag (which I heard could result in a similar problem): <meta "content_security_policy": "script-src 'self' https://apis.google.com https://www.googleapis.com https://securetoken.googleapis.com; object-src 'self'", "permissions": ["https://*/*","activeTab"]> EDIT: I have not changed any code but now I experience this error occasionally in browser (Chrome) as well, if less often. I can't find a pattern, although the issue seems to go away in a session after the user registers. Any help would be greatly appreciated, thank you so much. |
How do you push a tag to a remote repository using Git? Posted: 27 Jul 2021 07:45 AM PDT I have cloned a remote Git repository to my laptop, then I wanted to add a tag so I ran git tag mytag master When I run git tag on my laptop the tag mytag is shown. I then want to push this to the remote repository so I have this tag on all my clients, so I run git push but I got the message: Everything up-to-date And if I go to my desktop and run git pull and then git tag no tags are shown. I have also tried to do a minor change on a file in the project, then push it to the server. After that I could pull the change from the server to my Desktop computer, but there's still no tag when running git tag on my desktop computer. How can I push my tag to the remote repository so that all client computers can see it? |
No comments:
Post a Comment