Python: strange division results (1023456789876543201 / 9 ) Posted: 06 Oct 2021 09:13 AM PDT I have the following piece of code with a pretty strange result. The code I: print("{:.2f}".format(1023456789876543201/9)) Result: 113717421097393696.00 The code II: print("{:20d}".format(1023456789876543201//9)) Result: 113717421097393689 Why does Python returns wrong result in the first code sample? I know about floating point arithmetics but it seems for me that this is not the case. |
ASP.net MVC Kendo UI Grid column headers not aligning to table cells Posted: 06 Oct 2021 09:13 AM PDT Hey all I'm new to Kendo and I'm trying to fix my grid data in its spot and not move when I resize the browsers window. Currently when resizing it lower it starts cutting off the column names and the data below them. This is not the results I want. I want to be able to resize it and the "table" grid stay the same size no matter what. My .cshtml page code: @(Html.Kendo().ToolBar()..... @(Html.Kendo().Grid < Demo.Tool.Web.Core.Entities.BatchItem > () .Name("batches") .Columns(c => { c.AutoGenerate(false); c.Bound(b => b.Id).Visible(false).HeaderHtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }); c.Bound(b => b.Description).Width("200").HeaderHtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }); c.Bound(b => b.PercentageComplete).Width("200").HeaderHtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }) /*Percentage Complete*/ .HtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }) .ClientTemplate("<div class='not-progress'>" + "<div class='batch-not-progress'></div>" + "<span>0%</span>" + "</div>" + "<div class='progress batch-progress'></div>") .Width("200"); c.Bound(b => b.SubmissionTime).Format("{0:MM/dd/yyyy hh:mm:ss}") /*Submission Time*/ .HeaderHtmlAttributes(new { style = "text-align: center;" }) .HtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }) .Width("200"); c.Bound(b => b.Status).ClientTemplate("#= BatchMonitor.getStatusTemplate(Status) #") /*Status*/ .HeaderHtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }) .Width("200"); c.Bound(b => b.Rank).Title("Priority").ClientTemplate("<span/>") /*Priority*/ .HtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }) .HeaderHtmlAttributes(new { style = "text-align: center;", @class = "batch-monitor-grid-batches-header" }) .Filterable(false) .Sortable(false) .Width("200"); }) .HtmlAttributes(new { @class = "batch-monitor-grid batch-monitor-detail-grid batch-monitor-grid-batches" }) .ClientDetailTemplateId("grdBatchMonitorJobTemplate") .AutoBind(false) .DataSource(ds => { ds.WebApi() .ServerOperation(true) .Model(m => { m.Id(b => b.Id); }) .Read(r => r.Url(string.Format("{0}://{1}/api/v1/jobbatch", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host)).Type(HttpVerbs.Get)).PageSize(10); }) .Events(e => e.DataBound("BatchMonitor.onDatabound") .DetailExpand("BatchMonitor.onDetailViewExpand") .DetailCollapse("BatchMonitor.onDetailViewCollapse") .Change("BatchMonitor.onBatchGridChange")) .Pageable(p => p.Refresh(true) .PageSizes(new int[] { 5, 10, 25, 50, 100 }) .Numeric(true)) .Scrollable(s => s.Virtual(GridVirtualizationMode.Columns).Height("auto")) .Resizable(r => r.Columns(true)) .Sortable(s => s.SortMode(GridSortMode.SingleColumn)) .Selectable(s => s.Mode(GridSelectionMode.Multiple)) .ColumnMenu(c => c.Columns(false)) .Filterable()) <script type = "text/kendo-tmpl" id = "grdBatchMonitorJobTemplate"> @(Html.Kendo().Grid < Demo.Tool.Web.Core.Entities.JobItem > () .Name("grdJobs_#=Id#") .HtmlAttributes(new { @class = "batch-monitor-grid batch-monitor-detail-grid batch-monitor-grid-no-alt-row-color" }) .Columns(c => { c.AutoGenerate(false); c.Bound(j => j.Description).Width("200").HtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }); c.Bound(j => j.PercentageComplete).ClientTemplate("<div><div class='not-progress'><div class='job-not-progress'></div><span>0%</span></div><div class='progress job-progress'></div></div>") .Width("200") .HtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }); c.Bound(j => j.Id).Width("200").ClientTemplate("<span></span>"); c.Bound(j => j.Status).Width("200").ClientTemplate("\\#= BatchMonitor.getStatusTemplate(Status)\\#").HtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }); c.Bound(j => j.Rank).Width("200").HtmlAttributes(new { style = "text-align: center; white-space: nowrap; table-layout: fixed;" }); }) .Events(e => e.DataBound("BatchMonitor.onJobGridDatabound") .Change("BatchMonitor.onJobGridChange") .DetailCollapse("BatchMonitor.onJobGridDetailViewCollapse") .DetailExpand("BatchMonitor.onJobGridDetailViewExpand")) .ClientDetailTemplateId("grdBatchMonitorActionTemplate") .DataSource(ds => ds.WebApi().Read(r => r.Url(string.Format("{0}://{1}/api/v1/jobbatch/jobs/#=Id#", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host))) .PageSize(10)) .Selectable(s => s.Mode(GridSelectionMode.Multiple)) .ToClientTemplate()) </script> <script type = "text/kendo-tmpl" id = "grdBatchMonitorActionTemplate"> @(Html.Kendo().Grid < Demo.Tool.Web.Core.Entities.ActionItem > () .Name("grdAction_#=Id#") .HtmlAttributes(new { @class = "batch-monitor-grid batch-monitor-grid-no-alt-row-color" }) .Columns(c => { c.Bound(a => a.Description).Width("200"); c.Bound(a => a.PercentageComplete).ClientTemplate("<div class='not-progress'><div class='action-not-progress'></div><span>0%</span></div><div class='progress action-progress'></div>").Width("100") .Width("200") .HtmlAttributes(new { style = "text-align: center;" }); c.Bound(a => a.Id).Width("200").ClientTemplate("<span></span>"); c.Bound(a => a.Status).Width("200").ClientTemplate("\\#= BatchMonitor.getStatusTemplate(Status) \\#"); c.Bound(a => a.ParentId).Width("200").ClientTemplate("<span/>"); }) .Events(e => e.DataBound("BatchMonitor.onActionGridDatabound") .Change("BatchMonitor.onJobGridChange")) .DataSource(ds => ds.WebApi() .Read(r => r.Url(string.Format("{0}://{1}/api/v1/jobbatch/actions/#=Id#", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host))).PageSize(10)) .ToClientTemplate()) </script> This is what the code above produces: Am I missing a setting somewhere in order to correct this behavior? |
Vue, eslint formatting settings Posted: 06 Oct 2021 09:13 AM PDT Any suggestions for improvement would be welcomed - I would quite like wrap attributes on any multi-props. I always seem to struggle to set up new projects with decent formatting. I thought I'd make a note of it and share it with others as after a bit of Googling I'm definitely not the first with this issue. https://www.youtube.com/watch?v=W4i_lTAqsX8 |
Laravel deploy on subdomain Posted: 06 Oct 2021 09:13 AM PDT I created new subdomain on GoDaddy and compressed my project file as zip and uploaded to public_html/subdomain_name and I modified sub-domain document-root to /public_html/subdomain_name/public and when I am trying to reach 'www.my-project.com/subdomain_name' I just see this |
Use variable value instead of variable name Posted: 06 Oct 2021 09:13 AM PDT I don't know if I formulated the title correctly. I have a prop called resource. It contains a string which is also the url path where I want to make my fetch request to. Here I do want the value of the variable resource and not the name resource = user Wrong: data: json._embedded.resource Correct: data: json._embedded.user How can I make this dynamic so that with a different resource value the path for the data also changes? Code: const { headers, json } = response; console.log(response) switch (type) { case GET_LIST: case GET_MANY_REFERENCE: if (!json.page.totalElements) { throw new Error( "The page.totalElements property must be must be present in the Json response" ); } return { data: json._embedded.resource, total: parseInt(json.page.totalElements, 10) };```` |
Test OnDestinationChangedListener Navigation Component Posted: 06 Oct 2021 09:13 AM PDT In my splash activity I have an handler that waits for 3 seconds and then opens login fragment if it is the first time the user is opening the app. I'm having issues while testing this feature. @Test fun whenIsFirstLogin_redirectToMyLogin() { val navController = TestNavHostController(ApplicationProvider.getApplicationContext()) launchFragmentInHiltContainer<MySplashFragment> { navController.setGraph(R.navigation.nav) Navigation.setViewNavController(requireView(), navController) } Thread.sleep(Constants.SPLASH_WAIT_TIME) Assert.assertEquals(R.id.loginFrag, navController.currentDestination?.id) } The problem is, the test doesn't wait for the listener to be dispatched and just terminates itself. How can I make the test wait for the listener so that I can assert the result? |
Discord.js get rank position of user Posted: 06 Oct 2021 09:13 AM PDT I want to get the number of users that have a lower number of XP points than the member who used the command, this way I can get his rank. However I don't know much in javascript and sql queries, and I'm hard stuck with this, where it simply returns [object Object] instead of a number. My sql table const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get(); if (!table['count(*)']) { // If the table isn't there, create it and setup the database correctly. sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER, level INTEGER, money INTEGER);").run(); // Ensure that the "id" row is always unique and indexed. sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run(); sql.pragma("synchronous = 1"); sql.pragma("journal_mode = wal"); } // And then we have two prepared statements to get and set the score data. client.getScore = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?"); client.setScore = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points, level, money) VALUES (@id, @user, @guild, @points, @level, @money);"); }); My attempt if (message.content.startsWith(prefix + "cl stats")) { const curxp = score.points; client.rank = sql.prepare("SELECT count(*) FROM scores WHERE points >= @curxp AND guild = @guild").get(); console.log(client.rank); await message.reply(`${client.rank}`); } |
Execution failed for task ':react-native-agora:compileDebugJavaWithJavac' Posted: 06 Oct 2021 09:13 AM PDT i have tried npx react-native start run android i got this Execution failed for task.and i remove node module and lock file than reinstall(npm) same error.and also i removed agora file after i add npm i react-native-agora . that time same compileDebugJavaWithJavac with different dependencies(example react-native-image-crop-picker:compileDebugJavaWithJavac ) than i try same way to remove and add npm i got another error(react-native-agora:compileDebugJavaWithJavac) error: FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':react-native-agora:compileDebugJavaWithJavac'. > Failed to query the value of task ':react-native-agora:compileDebugJavaWithJavac' property 'options.generatedSourceOutputDirectory'. > Querying the mapped value of map(java.io.File property(org.gradle.api.file.Directory, property(org.gradle.api.file.Directory, fixed(class org.gradle.api.internal.file.DefaultFilePropertyFactory$FixedDirectory, /home/ubuntu/Desktop/quaquiz/node_modules/react-native-agora/android/build/generated/ap_generated_sources/debug/out))) org.gradle.api.internal.file.DefaultFilePropertyFactory$ToFileTransformer@49f0db11) before task ':react-native-agora:compileDebugJavaWithJavac' has completed is not supported build gradle: uildscript { ext { buildToolsVersion = "30.0.3" minSdkVersion = 21 compileSdkVersion = 30 targetSdkVersion = 30 supportLibVersion = "28.0.0" googlePlayServicesAuthVersion = "17.0.0" } repositories { mavenCentral() google() jcenter() } dependencies { classpath('com.android.tools.build:gradle:3.6.1') classpath 'com.google.gms:google-services:4.3.10' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } here i increased sdk version 30 after i got all this error. before i using build gradle buildToolsVersion = "29.0.2" minSdkVersion = 21 compileSdkVersion = 29 targetSdkVersion = 29 |
Can nginx encode a request uri that has decoded special characters? Posted: 06 Oct 2021 09:13 AM PDT As far as I understand, what nginx can do is decode characters (as part of normalization) of a given request_uri, if the configuration is done in a certain way. From nginx documentation http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass: A request URI is passed to the server as follows: If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive: location /name/ { proxy_pass http://127.0.0.1/remote/; } If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI: location /some/path/ { proxy_pass http://127.0.0.1; } Before version 1.1.12, if proxy_pass is specified without a URI, the original request URI might be passed instead of the changed URI in some cases. In some cases, the part of a request URI to be replaced cannot be determined: When location is specified using a regular expression, and also inside named locations. In these cases, proxy_pass should be specified without a URI. When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break): location /name/ { rewrite /name/([^/]+) /users?name=$1 break; proxy_pass http://127.0.0.1; } In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server. When variables are used in proxy_pass: location /name/ { proxy_pass http://127.0.0.1$request_uri; } In this case, if URI is specified in the directive, it is passed to the server as is, replacing the original request URI. Our upstream server is confluence and confluence doesn't support some charactes in title (https://jira.atlassian.com/browse/CONFSERVER-11285). I would like to know if nginx can encode request URI, so that the encoded request URI can be sent to confluence as it is. |
How do you export Settings->Editor->Inspections->Java->Declaration redundancy->Unused declaration->Entry Points->Annotations Posted: 06 Oct 2021 09:13 AM PDT How do you export Settings->Editor->Inspections->Java->Declaration redundancy->Unused declaration->Entry Points->Annotations and similar settings? For example, I have configured Spring's @Value and @Autowired annotations to be implicitly written to get rid of a lot of warnings generated by the IDE. I have a bunch of similar best practice configurations I want to share with developers on the team. I have tried the suggested approach in How to save/export all the settings of IntelliJ IDEA? but the exported zip does not contain my setting anywhere: unzip settings.zip grep -r -i autowire . <empty result> |
Firefox SVG Rendering Bug Posted: 06 Oct 2021 09:13 AM PDT Issue animating SVG elements with vector-effect: non-scaling-stroke attribute in Firefox. Stroke does not scale properly until animation is complete. Works fine in Chrome and Safari. Anyone know of a fix? Here is a reproduction -- https://codepen.io/ldrummond1/pen/GREVEvO?editors=1100 |
force file creation/writing before the end of the test Posted: 06 Oct 2021 09:13 AM PDT I have the following code in a test: @Test void genericTest() { //stuff createTempJsonFile(filename, body); func.method(filename); //stuff } private void createTempJsonFile(String filename, String body) { try { File file = new File(filename); FileWriter writer = new FileWriter(file); writer.write(body); writer.close(); } catch (IOException e) { //stuff } } The file is correctly created. The problem is that func.method does not find it, indeed Intellij only shows me the file created (appearing in the file list) at the end of the execution of the test. The issue is not the file path because on the further executions (when the file already exists since it was created at the end of the previous one), the test regularly passes. To me, it looks like the file creation is finalized only at the end of the test and that would be unacceptable since I need to operate in it in the test itself. How can I fix it? Is there a way to make the func.method wait until the file is generated? |
How to return a string containing details of an instance of a class? Posted: 06 Oct 2021 09:13 AM PDT I am trying to use a static method to return a string containing the details of instance 'a' which is in class Person. It should return the the attributes details like Name, age etc. I used a constructor in my main class to to set the attributes. However, I am getting told I have to put the static method in my main class and when I try it does not work. { public static void main(String[] args) { Person a = new Person(); public static String getDetails(Person a) { return null; } } } Ignore the null. |
How to use negative lookahead (NOT lookbehind) to match a string that does NOT contain a given substring at a specific position? Posted: 06 Oct 2021 09:13 AM PDT I'd like to match certain file types (e.g., ".txt") with a non-empty root name that doesn't end in a particular substring (e.g., "-bad"). With negative lookbehind support, the solution is simple: /.(?<!-bad)\.txt$/ Safari, however, still does not support negative lookbehinds. Ugh. How could I achieve the same result using a negative lookahead? I'd like to do this with a single regular expression. Please do not provide any non-regex or multi-step solutions. The test code below shows that I'm close, but one test is still failing. 😕 const regex = /.((?!-bad).{4})\.txt$/; const tests = [ ['this-file-bad.txt', false], ['this-file.txt', true], ['.txt', false], ['f.txt', true] ]; const results = tests.map(([input, expected]) => ((regex.test(input) === expected) ? '✅' : '❌') + input); console.log(results.join('\n'));
|
having problems with axios.post while try to get data FROM server Posted: 06 Oct 2021 09:13 AM PDT Im trying to use axios.post (in TS) to get respones from server (using POST as GET) without sending any Data. the server send back the Data but REACT cant handle the respones here is the react component interface allComapnies { comapniesData:CompanyData[]; } function GetAllCompanies(props:allComapnies): JSX.Element { const myURL = globals.urls.admin+"get_company/all"; const [comapniesData,setData] = useState([new CompanyData()]); useEffect(()=>{axios.post(myURL).then((response)=>{ console.log(response.data); setData(response.data); }).catch(error=>{console.log(error)}); },[]); return ( <div className="getAllCompanies"> {comapniesData.map(item=><OneCompany key ={item.id} id={item.id} name={item.name} email={item.email} />)} </div> ); } export default GetAllCompanies; the console massage: Error: Request failed with status code 302 - at createError (createError.js:16)
- at settle (settle.js:17)
- at XMLHttpRequest.onloadend (xhr.js:54)
the browser get the respons from the server: [{id: 2, name: "company2", email: "hgfytj@fdgreg", password: "trjyjytk",…},…] the function of the REST Post inside the Controller in the Server(SPRING): @RestController @RequestMapping("admin") @CrossOrigin(origins = "localhost:3000", allowedHeaders = "*") @RequiredArgsConstructor public class AdminController extends ClientController { private final AdminService adminService; ... @PostMapping("get_company/all") public ResponseEntity<?> getAllCompanies() { return new ResponseEntity<>(adminService.getAllCompanies(), HttpStatus.FOUND); } ... } |
Two instances of the same project without sharing database data in Lando Posted: 06 Oct 2021 09:13 AM PDT I'm working on a Drupal project hosted on platform.sh. I started to work locally with Lando but I messed things up a bit and I tried to create a second local Lando build for the same project to try some changes, keeping the fist project in it's broken state. The problem is that the second project seems to be using the same database as the first one. This might be related to caching but I don't wand to lose local database data from the first project and I'm not sure I can safely Lando pull to get fresh database data from platform.sh for the second project. |
enable a template if i can get a non const reference from std::vector.front() Posted: 06 Oct 2021 09:13 AM PDT I do have a generic container like so: template<typename T> struct GenericContainer { T& at(size_t index) { return data.at(index); } void append(const T& value) { data.push_back(value); } std::vector<T> data; }; As you all know we can't get a non const reference to bool through std::vector.at function. So this does not compile : bool& b = std::vector<bool>(true).front()
For the same reason i can't call the function at on my GenericContainer.
I would like to enable the function at on my GenericContainer only if i can get a non const reference to T.
I tried to implement a type traits like that but it does not work, it returns true_type for bool and int, i am looking for false_type for bool and true_type for int. It is inspired from a is_copy_assignable type traits.
template <typename T> struct is_ref_extractable_from_vector { private: template <class U, class ENABLED = decltype(std::declval<U&>() = std::declval<std::vector<U>>().front())> static std::true_type try_assignment(U&&); static std::false_type try_assignment(...); public: using type = decltype(try_assignment(std::declval<T>())); }; template<typename T> using is_ref_assignable_from_vector_t = typename is_ref_extractable_from_vector<T>::type; template <typename T> inline constexpr bool is_ref_assignable_from_vector_v = is_ref_assignable_from_vector_t<T>::value; static_assert(!is_ref_assignable_from_vector_v<bool>); static_assert(is_ref_assignable_from_vector_v<int>); i have no clue of why the assignment in the enable_if clause always compile. i was hopping SFINAE to discard try_assignment(U&&) overload with U = bool. thanks for your help. ps : note that i'm a bit novice in meta programming so i will not be suprised if there is an obvious reason for that result :) |
Instantiate object of given class by invoking implicit default constructor Posted: 06 Oct 2021 09:13 AM PDT Currently, I have a situation where I am trying to instantiate an object of a class, with the class given as a parameter, and have the object's properties initialized with default values (e.g. null). THe problem is, my class does not have any constructors and I am not able to add one for various reasons. The possible classes are also not connected by a superclass, they are all direct subclasses of Object. The classes I am trying to instantiate look like the following: public class MyClass { public String prop1; public int prop2; public int prop3; } That means the classes contain only properties and no methods, and as such no explicit constuctors. In cases where I know the class beforehand, I can of course just do this: public MyClass create() { return new MyClass(); } In the above case, the compiler generates me a default constructor for MyClass and initiates all properties with their default values. As pointed out in the comments, this means I technically have a constructor, but one that I am only able to access using the "new" keyword and by knowing the class beforehand. Now, what I am trying to do (basically) is the following: public someClass create(Class<?> someClass) { return new someClass(); } Of course, the 'new' keyword won't work in this scenario, so I have tried out many alternatives, none of which have worked so far: - Using
someClass.getConstructor().newInstance() or someClass.getDeclaredConstructor().newInstance() . Code compiled but I got the expected "NoSuchMethodException" as it could not find an <init>-method or constructor for someClass - Casting from Object like
Object newObject = someClass.cast(new Object()) . As expected, this crashes as well, as you can't cast from a superclass to a subclass My only real alternative right now, as the range of possible classes is not too large, is to conjure up a massive switch-case using "instanceof"s for every class and then just using the "new" keyword in each branch. But as you can imagine, I am not too fond of that. So am I trying to do the impossible or is there a way to do this? |
custom `geom_` with two different styles for plotting Posted: 06 Oct 2021 09:13 AM PDT My goal is to write a custom geom_ method that calculates and plots, e.g., confidence intervals and these should be plotted either as polygons or as lines. The question now is, where to check which "style" should be plotted? So far I have tried out three different approaches, - (i) write two different
geom_ /stat_ for line and polygon style plots, - (ii) write a single
geom_ /stat_ which uses a custom GeomMethod , - (iii) write a single
geom_ /stat_ which uses either GeomPolygon or GeomLine . In my opinion, to sum up - (i) is more or less straightforward but only bypasses the problem,
- (ii) works when you use either
GeomPath$draw_panel() or GeomPolygon$draw_panel() depending on an extra parameter style . But here I can't work it out to set default_aes depending also on the extra argument style . Compare also the answer here. - (iii) works when calling
geom_ but fails for calling stat_ as the name matching within ggplot2 fails. See minimal example below. Setting up the methods of approach (iii): geom_my_confint <- function(mapping = NULL, data = NULL, stat = "my_confint", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, style = c("polygon", "line"), ...) { style <- match.arg(style) ggplot2::layer( geom = if (style == "line") GeomPath else GeomPolygon, mapping = mapping, data = data, stat = stat, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( na.rm = na.rm, style = style, ... ) ) } stat_my_confint <- function(mapping = NULL, data = NULL, geom = "my_confint", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, style = c("polygon", "line"), ...) { style <- match.arg(style) ggplot2::layer( geom = geom, stat = StatMyConfint, data = data, mapping = mapping, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( na.rm = na.rm, style = style, ... ) ) } StatMyConfint <- ggplot2::ggproto("StatMyConfint", ggplot2::Stat, compute_group = function(data, scales, style) { if (style == "polygon") { nd <- data.frame( x = c(data$x, rev(data$x)), y = c(data$y - 1, rev(data$y) + 1) ) nd } else { nd <- data.frame( x = rep(data$x, 2), y = c(data$y - 1, data$y + 1), group = c(rep(1, 5), rep(2, 5)) ) nd } }, required_aes = c("x", "y") ) Trying out the methods of approach (iii): library("ggplot2") d <- data.frame( x = seq(1, 5), y = seq(1, 5) ) ggplot(d, aes(x = x, y = y)) + geom_line() + geom_my_confint(style = "polygon", alpha = 0.2) ggplot(d, aes(x = x, y = y)) + geom_line() + geom_my_confint(style = "line", linetype = 2) This works well so far. However when calling the stat_ there is an error in ggplot2:::check_subclass because there is no GeomMyConfint method. ggplot(d, aes(x = x, y = y)) + geom_line() + stat_my_confint() # Error: Can't find `geom` called 'my_confint' Any solutions or suggestions for alternative approaches? |
Split overlapping monologues into the dialog Posted: 06 Oct 2021 09:13 AM PDT I have a list of monologues grouped by speakers, e.g.: speaker 1: 00:00 Hello 00:02 How 00:02 are 00:03 you 00:04 ? speaker 2: 00:01 Hi 00:02 Wait 00:02 ! speaker 3: 00:00 Hey 00:03 Good I'm looking to transform this representation into a readable/reasonable dialog, e.g. speaker 3 00:00 Hey speaker 1 00:00 Hello speaker 2 00:01 Hi speaker 1 00:02 How... speaker 2 00:02 Wait! speaker 1 00:02 ...are you? speaker 3 00:03 Good This is a simple representation. But it happens that speakers overlap more hard. Definitely, I can sort it by the time, But I'm looking for a more advanced approach. For example, based on speaker's words frequency or any other approach that would be more human-friendly. Note: I'm looking for some (known) study reference. Any idea, that is better than sorting by the timing |
Pandas- Add a new row based on a specific condition Posted: 06 Oct 2021 09:13 AM PDT I have a specific dataframe which looks like this: owner | name | col_name | test_col1 | test_col2 | svc | dmn_dmn | A | 1 | "String1" | svc | dmn_dmn | B | 2 | "String12" | svc | dmn_dmn | C | remain_constant_3 | "String13" | svc | dmn_dmn | D | remain_constant_4 | "String14" | svc | time1 | E | 5 | "String1123" | svc | time1 | F | 6 | "String123223" | svc | sap | J | 1 | "String11" | svc | sap | K | 2 | "String12" | svc | sap | D | 4 | "String14" | If the values "C" and "D" are not present in the column col_name then add "C" and "D" to its col_name. The final dataframe should look like this: owner | name | col_name | test_col1 | test_col2 | svc | dmn_dmn | A | 1 | "String1" | svc | dmn_dmn | B | 2 | "String12" | svc | dmn_dmn | C | remain_constant_3 | "String13" | svc | dmn_dmn | D | remain_constant_4 | "String14" | svc | time1 | E | 5 | "String1123" | svc | time1 | F | 6 | "String123223" | svc | time1 | C | remain_constant_3 | "String13" | svc | time1 | D | remain_constant_4 | "String14" | svc | sap | J | 1 | "String11" | svc | sap | K | 2 | "String12" | svc | sap | C | remain_constant_3 | "String13" | svc | sap | D | remain_constant_4 | "String14" | Edited: Please also note that there could be more columns in this dataframe. I didnt add the other columns as i thought it wouldnt matter with the code but then i saw there was some confusion |
C Programming: Converting python oop program to c language Program Posted: 06 Oct 2021 09:13 AM PDT i have been trying to convert this python code to a c language source code, i have done majority of the things but can't make it work, i can't figure out how to convert map and append functions, and i am not sure if things are correct. if someone can help i would appreciate it a lot thanks in advance. class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def insert(self,data): ptr1 = Node(data) temp = self.head ptr1.next = self.head if self.head is not None: while(temp.next != self.head): temp = temp.next temp.next = ptr1 else: ptr1.next = ptr1 self.head = ptr1 def printList(self): temp = self.head if self.head is not None: while(True): print(temp.data, end = " ") temp = temp.next if (temp == self.head): break def lottery(self,s,t): # deleting list temp = self.head while( t > 0 ): for i in range(1,s): temp = temp.next print(temp.next.data) if(temp.next == self.head): self.head = temp.next.next t-=1 temp.next = temp.next.next #deletion temp = temp.next # finding minimum min = 100000 temp = self.head if self.head is not None: while(True): if(temp.data < min): min = temp.data temp = temp.next if (temp == self.head): break return min for _ in range(int(input())): min = 100000 group = 1 head = [] arr = [] g = int(input()) for i in range(0,g): p,s,t = map(int,input().split()) temp = LinkedList() for j in range(1,p+1): temp.insert(j) head.append(temp) arr.append([p,s,t]) for i in range(0,g): print("Group #"+str(i+1)+":") m = head[i].lottery(arr[i][1],arr[i][0] - arr[i][2]) if(min > m): min = m group = i+1 print("Lottery winner is "+str(min)+" from group " + str(group)) C code: #include <stdio.h> struct node { int data; struct node* next; }; void insert(struct node** head_ref, int new_data) { struct node* new_node = (struct node*) malloc(sizeof(struct node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } void printList(struct node *head){ struct node *tmp = head; while(tmp != NULL){ if(tmp->next == NULL){ printf("%d", tmp->data); } else{ printf("%d, ", tmp->data); } tmp = tmp->next; } } int lottery(struct node* head , int s, int t){ struct node *temp = head; while(t > 0){ for(int i = 1; i < s; i++){ temp = temp -> next; printf("%d", temp->next->data); if(temp->next == head){ head = temp->next->next; } t -= 1; temp->next = temp->next->next; temp = temp->next; } } int min = 100000; temp = head; if(!head == NULL){ while(1){ if(temp->data < min){ min = temp->data; } temp = temp->next; if(temp == head){ break; } } } return min; } int * map(const int *input, size_t input_len, int (*func)(int x)) { int *out = malloc(input_len * sizeof *out); if(out != NULL) { for(size_t i = 0; i < input_len; ++i) out[i] = func(input[i]); } return out; } int main(){ int min; int noOfTimes; int group; int g; int p; scanf("%d", &noOfTimes); for(int i = 0; i < noOfTimes; i++){ min = 10000; group = 1; scanf("%d", &g); for(int j = 0; j < g; j++){ p = map(); } } return 0; } |
Share data api with BehaviorSubject - architecture Observables Store Posted: 06 Oct 2021 09:13 AM PDT I would just like to make a call in the api and reuse the data in an observable, like a kind of store like in redux. API URL: http://demo5095413.mockable.io/consolidado Stackblitz project : https://stackblitz.com/edit/angular-ivy-iy9zhv?file=src/app/core.service.ts Service responsible for connection with api @Injectable({ providedIn: 'root' }) export class ConsolidadoApi { constructor(private http: HttpClient) { } getInvestiments(): Observable<any> { return this.http.get<PosicaoConsolidada>(`${environment.basePosicaoConsolidada}`) .pipe( map(res => res), shareReplay(), ) } } Service where the data is processed, my facade layer(store) Initially this way, this observable is responsible for making the call in the api. At the end of it I issue a BehaviorSubject export class CoreService { private subject = new BehaviorSubject<any>([]); investment$: Observable<any> = this.subject.asObservable(); constructor(private api: ConsolidadoApi, private loadingService: LoadingService, public messagesService: MessagesService, public state: StateService) { this.getInvesmentsPortifolio$() } public getInvesmentsPortifolio$(): Observable<Carteiras> { return this.api.getInvestiments() .pipe( map(response => response.carteiras), catchError(err => { const message = "Error Investments"; this.messagesService.showErrors(message); console.log(message,err); return throwError(err); }), tap(investment$ => this.subject.next(investment$)) ) } That's how I would like to do it, access the observable that already has all the investment portfolios and from there create an observable from the investment portfolio "Agora" getPortifolioAgora(): Observable<any> { return this.investment$ .pipe( map(response => response.carteiras.find( carteira => carteira.tipoInvestimento === "AGORA" )) ); } But in my component dont work constructor(public coreService: CoreService, private loadingService: LoadingService) { } ngOnInit(): void { this.loadData() } public loadData(){ this.loadingService.loadingOn() this.coreService.getPortifolioAgora().subscribe(res => { console.log(res) }) this.coreService.getInvesmentsPortifolio$().subscribe(res => { this.carteiras = res console.log('All portifolio investments----->',res) }) } Properties undefined? I know if i do it that way the find works. // In this observable I access directly in the api and I can access the investment portfolio Agora // it's working, but I wouldn't want to do it that way because I would have made another call on the server public portifolioAgora$(): Observable<Carteiras> { return this.api.getInvestiments() .pipe( map(response => response.carteiras.find( carteira => carteira.tipoInvestimento === "AGORA" )), finalize(() => this.loadingService.loadingOff()) //tap(data => console.log(data, JSON.stringify(data))) ) } |
Extract frames simultaneously from two video using ffmpeg Posted: 06 Oct 2021 09:13 AM PDT I would like to know the CLI command and the script to extract images using FFmpeg of two videos simultaneously and not sequentially. For example - the first frame of the first video the first frame of the second video and the second frame of first video and then the second frame of second video and so on. Videos will be in mp4 or asf and image should be in jpeg |
Good practices structuring Git repository Posted: 06 Oct 2021 09:12 AM PDT My team is required to rewrite a highly modified moodle platform. The way we are going to face it is creating several plugins integrated with moodle itself. Those plugins also get installed in several different files of the moodle folder structure. A very basic example would be: /root /folder_1 /plugin_1 /plugin_2 /folder_2 /plugin_1 /plugin_2 That raises the problem of structuring our git repository, as the deployment would get slow and cumberstone as the number of plugins raises We are contemplating a basically three ways: - Indepentend Git repositories. Each plugin gets its own repo. As every plugin does a specific job, not necessarily related to each other, it would be a clean way to do it. The problem is having a large number of project that are actually related to each other in gitlab may look a bit ugly. Also the deployment might be the slowest, but the easiest to update a single plugin.
- A repository per moodle folder. Easiest to deploy, but updating or fixing just a single plugin might not be so straightforward
- Branch per folder. A big repository containing all the plugins, but having a number of 'main' branches that contain several plugins. Cleaner on gitlab, as all the plugins are in the same project, not so clean in the branches tab. Also working on different plugins would require checking out branches quite frequently.
Basically what I'm asking for is a bit of advice handling a larger and more fragmented project (to me) than usual. Thanks in advance. |
IAuthenticationManager does not contain definition of GetExternalLoginInfoAsync, How do i fix this issue? Posted: 06 Oct 2021 09:13 AM PDT I have this method and i am getting this line of error to it, please assist me. public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();//IAuthenticationManager does not contain definition of GetExternalLoginInfoAsync. Are you missing some assembly? } private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication;// HttpContext does not contain a definition of GetOwinContext. are you missing some assembly or directive. } } NB:// For GetOwinContext i followed this link to install the package, the error is now gone, but im still left with the error for GetExternalLoginInfoAsync. https://www.codeproject.com/Questions/5255999/Httpcontextbase-does-not-contain-a-definition-for |
How to add custom Material-UI palette colors Posted: 06 Oct 2021 09:14 AM PDT I'm trying to establish my own palette colors to match my branding in Material-UI. So far I can only get the primary and secondary colors to work when applied as the background color to buttons. When I add my own variable names like use "accent" as shown as an example from Material-UI's website, the button defaults to grey. Here is my MyTheme.js code: import { createMuiTheme } from 'material-ui/styles'; import purple from 'material-ui/colors/purple'; export default createMuiTheme({ palette: { primary: { // works main: '#165788', contrastText: '#fff', }, secondary: { // works main: '#69BE28', contrastText: '#fff', }, companyBlue: { // doesnt work - defaults to a grey button main: '#65CFE9', contrastText: '#fff', }, companyRed: { // doesnt work - grey button main: '#E44D69', contrastText: '#000', }, accent: { // doesnt work - grey button main: purple, // import purple doesnt work contrastText: '#000', }, }, }); Here is my App.js code: import React, { Component } from 'react'; import Button from 'material-ui/Button'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import MyTheme from './MyTheme'; import './App.css'; import { withStyles } from 'material-ui/styles'; import PropTypes from 'prop-types'; const styles = theme => ({ button: { margin: theme.spacing.unit, }, input: { display: 'none', }, }); class App extends Component { constructor(props) { super(props); } render() { const { classes } = this.props; return ( <MuiThemeProvider theme={MyTheme}> <Button variant="raised" > Default </Button> <Button variant="raised" color="primary" className={classes.button}> Primary </Button> <Button variant="raised" color="secondary" className={classes.button}> Secondary </Button> <Button variant="raised" color="companyRed" className={classes.button}> Company Red </Button> <Button variant="raised" color="accent" className={classes.button}> Accent </Button> </MuiThemeProvider> ); } } App.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(App); |
Using Docker-Compose, how to execute multiple commands Posted: 06 Oct 2021 09:13 AM PDT I want to do something like this where I can run multiple commands in order. db: image: postgres web: build: . command: python manage.py migrate command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" links: - db |
Annotations from javax.validation.constraints not working Posted: 06 Oct 2021 09:13 AM PDT What configuration is needed to use annotations from javax.validation.constraints like @Size , @NotNull , etc.? Here's my code: import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Person { @NotNull private String id; @Size(max = 3) private String name; private int age; public Person(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } } When I try to use it in another class, validation doesn't work (i.e. the object is created without error): Person P = new Person(null, "Richard3", 8229)); Why doesn't this apply constraints for id and name ? What else do I need to do? |
How to find and restore a deleted file in a Git repository Posted: 06 Oct 2021 09:13 AM PDT Say I'm in a Git repository. I delete a file and commit that change. I continue working and make some more commits. Then, I find I need to restore that file. I know I can checkout a file using git checkout HEAD^ foo.bar , but I don't really know when that file was deleted. - What would be the quickest way to find the commit that deleted a given filename?
- What would be the easiest way to get that file back into my working copy?
I'm hoping I don't have to manually browse my logs, checkout the entire project for a given SHA and then manually copy that file into my original project checkout. |
No comments:
Post a Comment