text
stringlengths
15
59.8k
meta
dict
Q: Conditional renaming with batch file i'd like to rename two files in a specific directory on my computer with a batch file. The problem is that i'd like, if it's possible doing so with standard batch commands, to rename the files conditionally. To be more specific, my example is as follows: I've got two "hosts" files located in C:\Windows\System32\drivers\etc; one is named "hosts", the other is named "hosts_X", a "hosts" file that contains specific instructions that i need to be active in a specific case. I'd like to switch between this two "hosts" files: there are two cases: case "A" in which there's a "hosts" file and a "hosts_X" file, case "B" in which the original "hosts" file is renamed to "hosts_Y" and "hosts_X" is renamed to "hosts". Is it possible to have a single batch file that renames the two files conditionally? Like, if there's a file named "hosts" and a file named "hosts_x", rename "hosts" to "hosts_y" and "hosts_x" to hosts, and if there's a file named "hosts" and a file named "hosts_y", rename "hosts" to "hosts_x" and "hosts_y" to "hosts"? Thank you for any info and help! A: I summarize the useful suggestions by Liturgist and Alex K. and answer this question to get it removed from list of questions with no answer. Batch file according to idea provided by Liturgist: @echo off if not "%~1" == "" ( if exist "C:\Windows\System32\drivers\etc\hosts_%~1" ( copy /Y "C:\Windows\System32\drivers\etc\hosts_%~1" C:\Windows\System32\drivers\etc\hosts ) else ( echo %~f0 %* echo. echo Error: There is no file C:\Windows\System32\drivers\etc\hosts_%~1 echo. pause ) ) else ( echo %~f0 echo. echo Please call this batch file with either X or Y as parameter. echo. pause ) The batch file must be called with a parameter which specifies which hosts file should become active with at least hosts_X and hosts_Y in directory C:\Windows\System32\drivers\etc. The parameter should be either X or Y. An additional file check is made in case of parameter does not specify an existing hosts file resulting in an error message. There is also a message output if batch file is called without a parameter. Batch file according to idea provided by Alex K.: @echo off if exist C:\Windows\System32\drivers\etc\hosts_X ( ren C:\Windows\System32\drivers\etc\hosts hosts_Y ren C:\Windows\System32\drivers\etc\hosts_X hosts echo hosts_X is now the active hosts file. ) else ( ren C:\Windows\System32\drivers\etc\hosts hosts_X ren C:\Windows\System32\drivers\etc\hosts_Y hosts echo hosts_Y is now the active hosts file. ) echo. pause This batch file toggles active hosts file depending on which template hosts file currently exists: * *With hosts_X existing, hosts is renamed to hosts_Y and hosts_X is renamed to hosts. *Otherwise with hosts_Y existing, hosts is renamed to hosts_X and hosts_Y is renamed to hosts. There should be never hosts, hosts_X and hosts_Y all existing at the same time in the directory as this would result in failing file renames. But all 3 files existing at same time should not be a use case to take into account for this task. (Using move /Y instead of ren with second file name having also full path would help in this not to expect use case.) For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully. * *call /? ... for an explanation of %~1, %~f0 and %*. *copy /? *echo /? *if /? *ren /? *pause /?
{ "language": "en", "url": "https://stackoverflow.com/questions/33441253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is this list-initialization of an array of unknown size valid in C++0x? Is this list-initialization of an array of unknown size valid in C++0x? int main() { int x[]{0, 1,2,3,4}; return x[0]; } I believe it is valid, but would appreciate some confirmation. If anyone could quote from the C++0x-FCD to support their case, it would be greatly appreciated. Thanks! A: This goes from 8.5/16 first bullet to 8.5.4 list-initialization and from 8.5.4/3 third bullet to 8.5.1 aggregate initialization and then 8.5.1/4 says An array of unknown size initialized with a brace-enclosed initializer-list containing n initializer-clauses, where shall be greater than zero, is defined as having elements The only difference if the object is an array between = { ... } and { ... } is that the first is called copy-list-initialization and the second is called direct-list-initialization, so both are kinds of list-initialization. The elements of the array are copy-initialized from the elements of the initializer list in both cases. Notice that there is a subtle difference between those forms if the array has a size and the list is empty, in which case 8.5.4 second bullet applies: struct A { explicit A(); }; A a[1]{}; // OK: explicit constructor can be used by direct initialization A a[1] = {}; // ill-formed: copy initialization cannot use explicit constructor This difference does not apply to lists that have content in which case third bullet applies again, though struct A { explicit A(int); }; A a[1]{0}; // ill-formed: elements are copy initialized by 8.5.1 A a[1] = {0}; // ill-formed: same. The FCD changed this compared to the previous draft, and initialization with an empty initializer list now always works even with explicit default constructors. This is because the FCD states that the elements are value-initialized, and value initialization doesn't care about explicitness since it doesn't do overload resolution on default constructors (it couldn't figure out better or worse matches anyway). The previous draft used normal overload resolution on the constructors and thus rejected explicit default constructors during copy initialization. This defect report did that change. A: Yes, it is valid, and has been for decades, even in C. The size is simply set to the number of elements supplied. I don't know the reference, unfortunately. (Added bonus...) If you need the number of elements use sizeof(x)/sizeof(*x). It's safer than hard-coding a constant that may become invalid if you add or remove entries. EDIT: As pointed out in the comments, the code in question is missing an = (a fact that I missed), without which it isn't valid in any current standard of C or C++.
{ "language": "en", "url": "https://stackoverflow.com/questions/2613562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: array_map w/ null value I use the following to take an array called $list and turn it into URLs: function genIMG($sValue) { return 'http://asite.com/'.$sValue.'?&fmt=jpg'; } $IMGurls = array_map("genIMG", array_unique($list)); foreach($IMGurls as $imgLink) { echo "<a href='". $imgLink ."'>". $imgLink ."</a><br />"; } This works, but I also have some null values in the array. How can I have the array map ignore any values of null? Otherwise it just creates something like this: http://asite.com/?&fmt=jpg with no file name since it was null. A: You $list must have contained empty values use array_filter $IMGurls = array_map("genIMG", array_unique(array_filter($list))); Example $list = array(1,2,3,4,5,"","",7); function genIMG($sValue) { return 'http://asite.com/' . $sValue . '?&fmt=jpg'; } $IMGurls = array_map("genIMG", array_unique(array_filter($list))); foreach ( $IMGurls as $imgLink ) { echo "<a href='" . $imgLink . "'>" . $imgLink . "</a><br />"; } Output http://asite.com/1?&fmt=jpg http://asite.com/2?&fmt=jpg http://asite.com/3?&fmt=jpg http://asite.com/4?&fmt=jpg http://asite.com/5?&fmt=jpg http://asite.com/7?&fmt=jpg
{ "language": "en", "url": "https://stackoverflow.com/questions/12694896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: search function not working - Ruby on rails I'm new to Ruby on Rails and trying to implement a search function with simple form to filter out availabilities results. After I press search button, it still stays on the same page and not running the search function in the controller. The permitted is false. I'm wondering why this might occur. Is there anything wrong with the search_params I wrote? Rails version is 6.0.2.1. views/availabilities/_searchform.html.erb <form> <div id="aDiv"> <%= simple_form_for :search, :url => search_rides_result_path, :method => :get do |f| %> <div class="form-row"> <div class="form-group col-md-2"> <%= f.input :start_city, label: 'Start City', class: "form-control", error: 'Start address is mandatory, please specify one' %> </div> <div class="form-group col-md-4"> <%= f.input :start_street_address, label: 'Start Street Address', class: "form-control" %> </div> </div> <div class="form-row"> <div class="form-group col-md-2"> <%= f.input :end_city, label: 'Destination City', class: "form-control" %> </div> <div class="form-group col-md-4"> <%= f.input :end_street_address, label: 'Destionation Street Address', class: "form-control" %> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <%= f.input :trip_time, as: :datetime, inline_label: 'Yes, remember me', class: "form-control" %> </div> <div class="form-group col-md-2"> <%= f.input :lowest_acceptable_price, label: 'Expected Price', class: "form-control" %> </div> </div> <%= f.submit "Search", class: "btn btn-primary" %> <% end %> </div> </form> routes.rb file. get 'search_rides', to: "availabilities#index" get 'search_rides_result', to: "availabilities#search" availabilities_controller.rb def index @availabilities = Availability.unmatched end def search @availabilities = Availability.unmatched.search(search_params[:start_city]) end def search_params params.require(:search).permit(:start_city, :start_street_address, :end_city, :end_street_address, :trip_time, :lowest_acceptable_price) end models/availability.rb class Availability < ApplicationRecord has_many :users, :through => :posts has_one :request scope :unmatched, ->{ where(matched_request_id: -1) } def self.search (params) puts "start searching" results = city_matches(start_city, end_city, params[:start_city], params[:end_city]) return nil unless results results end A: Instead of using 2 different methods for search, try combining both in index method. Your index method will now look as follows: def index if params[:search] @availabilities = Availability.unmatched.search(search_params[:start_city]) else @availabilities = Availability.unmatched end end Change the form url to search_rides_path. This way search results will be rendered in same view upon form submission.
{ "language": "en", "url": "https://stackoverflow.com/questions/60853791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create auto email response when the receiver opens the mail? Hi My boss wants me to create auto email response when the receiver opens the mail. Most of our clients use gmail but they can use any kinds of mail system. How can I create it ? Thanks A: It's not going to be the answer your boss wants to hear, but last time I looked into this there's no reliable way of knowing when someone has opened an email you've sent. Traditionally (to find out email read counts for marketing emails) it's been done by embedding an image in the email and then having the loading of that image from your server trigger some action; you could do this and have the image address point to a script which sends the auto response then returns a single pixel transparent gif (for example), but it's becoming more standard to disable images in emails these days, so that isn't a 100% reliable route. That said, if the people you send emails to are more likely than not to load non-embedded images, that is one way to achieve it :) A: Read Receipts are not available in GMail: http://www.google.com/support/forum/p/gmail/thread?tid=3ad9e2c7914d3f0e&hl=en There's not much support for this feature in many email clients. It's a privacy issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/6067942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Session_Start firing multiple times I have a base web ui project, I also have other 'plugin' projects which are just other mvc web applications. I take the dll's and views from them and toss them into my main web ui's bin and views folder so they can just be added or removed at any time which does work. each 'plugin' contains a GET method that is called from the main web ui to load the menu options from each of the 'plugins'. After each URL is called, the main web ui fires the `Session_Start' menu.Append(HelperMethods.GetModuleMenuHTML(controller, SecurityController.CurrentDomain())); public static string GetModuleMenuHTML(string controllerName, string currentDomain) { string html = string.Empty; try { //THIS LINE HERE IS CAUSING Session_Start to fire again //IN THE MAIN WEB UI html = new WebClient().DownloadString(string.Format("{0}/{1}/GetMenu", currentDomain, controllerName)); } catch (Exception ex) { } return html; } What is causing Session_Start to fire when calling html = new WebClient().DownloadString(string.Format("{0}/{1}/GetMenu", currentDomain, controllerName)); and how can I prevent that from happening? Does this have something to do with me just dropping in the dll and views from another project directly into the main web ui projects as a "plugin" (which does however load correctly into my UI) to be easily added and removed? A: Its mainly because of this: html = new WebClient().DownloadString(string.Format("{0}/{1}/GetMenu", currentDomain, controllerName)); This line uses WebClient class to get the html, but the WebClient class is stateless, and each time its called it uses another request with no cookies, so the server thinks it a new request, and starts a new session. A: The WebClient request is recursively starting a new session. As a hack, you could modify your Session_Start() to check if the incoming url is /{controller}/GetMenu and simply avoid the WebClient call. See: https://stackoverflow.com/a/18656561. Otherwise, perhaps decorating your MenuController with SessionStateAttribute (https://msdn.microsoft.com/en-us/library/system.web.mvc.sessionstateattribute(v=vs.118).aspx) might avoid the Session_Start altogether (if GetMenu() doesn't use the session state).
{ "language": "en", "url": "https://stackoverflow.com/questions/38276276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to render a full page video background in Next.js but getting blank page I'm trying to have a full page video background in the homepage of my Nextjs application but am just getting blank white space where the content should be. I'm fairly new to Nextjs and am probably making a silly mistake here, if anyone could point this out I'd really appreciate the help. My mp4 video is stored within public/assets as so here: This is my index.js file: import Head from 'next/head'; import Image from 'next/image'; import React, { useRef, useEffect, useState } from 'react'; import ScrollAnimation from '../components/ScrollAnimation'; import Footer from '../components/Footer'; import Header from '../components/Header'; export default function Home() { return ( <div> <Head> <title>Greystone</title> <link rel='icon' href='/favicon.ico' /> <link rel='preload' href='/fonts/FairplayDisplay/FairplayDisplay-Bold.ttf' as='font' crossOrigin='' /> <link rel='preload' href='/fonts/FairplayDisplay/FairplayDisplay-Regular.ttf' as='font' crossOrigin='' /> </Head> <main className='overflow-y-hidden h-screen'> <Header /> <div id='main' className='transition duration-1000 relative ease-in-out' onWheel={scrollTo}> {/* Page 1 */} <div className='h-screen w-full flex items-center'> <video autoplay loop muted className='w-full h-screen z-10'> <source src='../public/assets/bubble-video.mp4' type='video/mp4' /> </video> <div className='flex flex-col absolute right-20'> <ScrollAnimation /> </div> <div className='w-2/5 text-left flex flex-col text-white left-20 absolute'> <h2 className='text-5xl'>We’re Greystone.</h2> <h2 className='text-5xl'> We think recruitment is broken. Be part of something better. </h2> <p className='text-left mt-5 text-lg'> Greystone brings the top 10% of talent together in an exclusive club, then pairs those dream hires with the right clients. It’s role-finding, reimagined. </p> <div className='mt-5 border-b-2 border-white w-36'> <h3 className='text-left text-lg'>FIND OUT MORE</h3> </div> </div> </div> </div> <Footer /> </main> </div> ); } Many thanks in advance if anyone can help! A: It seems I didn't need to have 'public' in the src url call for anyone who may experience a similar issue in future. The video tag now looks like so: <video autoPlay loop muted className='w-full h-screen z-10'> <source src='/assets/bubble-video.mp4' type='video/mp4' /> </video> A: adding mute attribute to the video tag solved a similar issue for me <video preload="auto" playsInline autoPlay muted loop > <source src="/video.mp4" type="video/mp4" /> </video>
{ "language": "en", "url": "https://stackoverflow.com/questions/67993350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why rewritten dynamic routs don't work with basePath and locales in Next.js? For example I have project structure like this: . └── pages ├── news │ ├── [slug].tsx │ └── index.tsx └── reviews.tsx All pages are static generated My next.config.js has following rules const BASE_PATH = process.env.APP_HOST === 'be' ? `/${process.env.APP_LANGUAGE}` : undefined; const paths = { news: { nl: '/nieuws', en: '/news', fr: '/actualite', de: '/neuigkeiten', }, reviews: { nl: '/reviews', en: '/reviews', fr: '/avis', de: '/bewertungen', }, }; module.exports = { async rewrites() { return [ { source: paths.reviews, destination: '/reviews', }, { source: `${paths.news}/:path*`, destination: '/news/:path*', }, ] }, basePath: BASE_PATH, i18n: process.env.APP_HOST === 'be' ? { locales: ['default', process.env.APP_LANGUAGE], defaultLocale: 'default', localeDetection: false, } : undefined, trailingSlash: process.env.APP_HOST === 'be', sassOptions: { prependData: `$basePath: '${BASE_PATH || ''}';`, }, env: { APP_HOST: process.env.APP_HOST, APP_LANGUAGE: process.env.APP_LANGUAGE, } } If process.env.APP_HOST !== "be" static and dynamic routes work perfect If process.env.APP_HOST === "be" static routes work fine but dynamic route gives 404 page. For example process.env.APP_HOST = "be" and process.env.APP_LANGUAGE = "de" In getStaticPaths all paths for articles are correct. /de/bewertungen/ the page is correct /de/neuigkeiten/ the page is correct /de/neuigkeiten/some-article-path/ - 404 error I've tried to change paths in rewrites, set locale: false for dynamic path, tried make rewrite in next middleware - nothing works for me
{ "language": "en", "url": "https://stackoverflow.com/questions/74211683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sql query to find the value exist in source I have the following query, select Vendor_ID, Descr, source, Name, Parent_Vendor_ID from VENDOR; Data: VendorID Descr Source name Parent Vendor ID 1234 ONLINE ABC JACK 6666 5689 OFFSHORE XYZ SAM 5555 9999 SHOP TTT EBAY 1234 6666 ECOMMERCE FRE AMERICAS From the above table data 5555 doesn't exist in Vendor ID field. so I need the output as below VendorID Descr Source name Parent Vendor ID EXIST 1234 ONLINE ABC JACK 6666 Yes 5689 OFFSHORE XYZ SAM **5555 No** 9999 SHOP TTT EBAY 1234 Yes 6666 ECOMMERCE FRE AMERICAS I need to find if the Parent_Vendor_ID exist in Field 1 Vendor_ID. if exist simply need a column with Yes/No. If yes YES else NO Output should be all fields + Parent_Vendor_ID_Exist select Vendor_ID, Descr, source, Name, Parent_Vendor_ID,Parent_Vendor_ID Exist I tried to if else but its not returning all values. Can someone please suggest? A: select v1.Vendor_ID, v1.Descr, v1.source, v1.Name, v1.Parent_Vendor_ID, case when v2.Vendor_ID is null then 'NO' else 'YES' end as Parent_Vendor_ID_Exist from vendor v1 left join vendor v2 on v1.Parent_Vendor_ID = v2.Vendor_ID A: SELECT v1.Vendor_ID , v1.Descr , v1.source , v1.Name , v1.Parent_Vendor_ID , nvl2(v2.vendor_id,'Yes','No') as parent_exist FROM VENDOR v1 LEFT OUTER JOIN vendor v2 ON (v1.parent_vandor_id = v2.vendor_id); A: Try this.. SELECT Vendor_ID, Descr, source, Name, Parent_Vendor_ID, CASE WHEN EXISTS( SELECT Vendor_ID FROM VENDOR v2 WHERE v1.Parent_Vendor_ID = v2.Vendor_ID) THEN 'Yes' ELSE 'No' END as "Parent_Vendor_ID Exist" FROM VENDOR v1; let me know if this works.
{ "language": "en", "url": "https://stackoverflow.com/questions/40890523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is this method reference failing at runtime but not the corresponding lambda call? I have these two interfaces. One is public (A), the other one is package private (AA). A extends AA. package pkg.a; @FunctionalInterface public interface A extends AA { } . package pkg.a; interface AA { default void defaultM() { System.out.println(m()); } String m(); } I have this code (in a different package): package pkg; import java.util.Arrays; import java.util.List; import pkg.a.A; public class Test { public static void main(String[] args) { List<A> list = Arrays.asList(() -> "imp1", () -> "imp2"); list.stream().forEach(a -> a.defaultM()); list.stream().forEach(A::defaultM); } } When running the above code the list.stream().forEach(A::defaultM); throws the below exception. Why? Why can't the method reference access the methods defined in the package-private interface while the lambda expression can? I'm running this in Eclipse (Version: 2018-12 (4.10.0)) with Java version 1.8.0_191. imp1 imp2 Exception in thread "main" java.lang.BootstrapMethodError: call site initialization exception at java.lang.invoke.CallSite.makeSite(CallSite.java:341) at java.lang.invoke.MethodHandleNatives.linkCallSiteImpl(MethodHandleNatives.java:307) at java.lang.invoke.MethodHandleNatives.linkCallSite(MethodHandleNatives.java:297) at pkg.Test.main(Test.java:14) Caused by: java.lang.IllegalArgumentException: java.lang.IllegalAccessException: class is not public: pkg.a.AA.defaultM()void/invokeInterface, from pkg.Test at java.lang.invoke.MethodHandles$Lookup.revealDirect(MethodHandles.java:1360) at java.lang.invoke.AbstractValidatingLambdaMetafactory.<init>(AbstractValidatingLambdaMetafactory.java:131) at java.lang.invoke.InnerClassLambdaMetafactory.<init>(InnerClassLambdaMetafactory.java:155) at java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:299) at java.lang.invoke.CallSite.makeSite(CallSite.java:302) ... 3 more Caused by: java.lang.IllegalAccessException: class is not public: pkg.a.AA.defaultM()void/invokeInterface, from pkg.Test at java.lang.invoke.MemberName.makeAccessException(MemberName.java:850) at java.lang.invoke.MethodHandles$Lookup.checkAccess(MethodHandles.java:1536) at java.lang.invoke.MethodHandles$Lookup.revealDirect(MethodHandles.java:1357) ... 7 more A: This appears to be a bug in certain Java versions. I can replicate it if I compile and run it with JDK 8, specifically: tj$ javac -version javac 1.8.0_74 tj$ java -version java version "1.8.0_74" Java(TM) SE Runtime Environment (build 1.8.0_74-b02) Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode) ...but not with JDK 11 or 12, specifically: tj$ javac -version javac 11.0.1 tj$ java -version openjdk version "11.0.1" 2018-10-16 OpenJDK Runtime Environment 18.9 (build 11.0.1+13) OpenJDK 64-Bit Server VM 18.9 (build 11.0.1+13, mixed mode) and tj$ javac -version javac 12.0.2 tj$ java -version java version "12.0.2" 2019-07-16 Java(TM) SE Runtime Environment (build 12.0.2+10) Java HotSpot(TM) 64-Bit Server VM (build 12.0.2+10, mixed mode, sharing) I can also replicate it if I compile with JDK 8 but run it with JDK 12's runtime, suggesting a compilation problem. A: This is a bug: Method reference uses wrong qualifying type. A reference to a method declared in a package-access class (via a public subtype) compiles to a lambda bridge; the qualifying type in the bridge method is the declaring class, not the referenced class. This leads to an IllegalAccessError. Fixed in Java 9.
{ "language": "en", "url": "https://stackoverflow.com/questions/57755303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Malfunction of a jQuery slideToggle() implementation I've got a problem with the following setup: I have a button that is inside a nav element. <nav id="navbuttons"> <button type = "button" id="projectsMenu" onclick="slideProjects()">Projects</button> </nav> which should slide in/out the following nav element when clicked: <nav id="projects"> We're projects </nav> To do this, I'm using the following JavaScript/jQuery function: function slideProjects(){ $(document).ready(function(){ $("#projectsMenu").click(function(){ $("#projects").slideToggle("slow"); }); }); } This causes eratic behavior of the button and the secondary nav (which has more stuff in it than "We're projects", but they're just examples of the same thing I'm asking about). The button has to be clicked twice in order to get the second nav to show, and even then, it "winks" at you (it slides down, slides up, then slides down again, sometimes multiple times). From what I understand/have been told, I have this problem because there are too many "onclick" event handlers on in the process, which brings a need for multiple clicks like I mentioned earlier. If I remove onclick from the html element (I was told it was deprecated), it doesn't seem to listen to the button. Is this correct, and what do I do to fix this? A: It should be just <nav id="navbuttons"> <button type="button" id="projectsMenu">Projects</button> </nav> then $(document).ready(function () { $("#projectsMenu").click(function () { $("#projects").stop(true).slideToggle("slow"); }); }); Demo: Fiddle because in your case, the actual slideToggle code is not executed in the first click... in the slideProjects method you are registering a click handler which is sliding the element. Instead you can just use the dom ready handler to add a click handler to the projectsMenu element and there is no need to have a onclick handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/23622261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JQuery Ajax call returns "Error: Not enough storage is available to complete this operation." So I am getting the above error when I am trying to pass the result.target of an OnLoad event in the FileReader.readAsArrayBuffer call using an jQuery Ajax POST call. The POST call is not actually being made (as monitored by Fiddler). This call works for files tested to about 120 mbs. I am trying to upload a 218 mb file though now. Also this seems to be IE specific, as it works in Chrome. Call: $.ajax({ type: 'POST', url: url, contentType: 'application/json;odata=verbose', data: fileData, processData: false, headers: { ACCEPT: 'application/json;odata=verbose', "X-RequestDigest": formDigest, "If-Match": "*" } }).done(function (results) { //Do Stuff }); As context, fileData is the result.target created through a file upload via the HTML 5 File API. I am trying to pass a file to upload in SharePoint via the Web API. A: Servers usually have limits on file sizes that can be uploaded. It sounds like you're running into the servers limit. If you own the server, you can raise the cap, otherwise you could try asking the server's admin.
{ "language": "en", "url": "https://stackoverflow.com/questions/31988570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to detect fling on TextView without cancelling scroll? Trying to detect a fling on a TextView using simpleGestureDetector: public void onCreate(Bundle savedInstanceState) { ... textContent.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent ev) { return gestureDetector.onTouchEvent(ev); } }); } class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if(foo) { fooBar(); return true; } return super.onFling(e1, e2, velocityX, velocityY); } } This works in the sense that my code fooBar() is run if the conditions foo are met, but the problem I find is that when the conditions aren't met, returning super.onFling() causes the fling to be cancelled, it seems, since the textview scroll no longer continues after the finger is lifted on a fling. Here is the XML: <RelativeLayout android:id="@+id/main_area" android:layout_height="match_parent" android:layout_width="match_parent"> <TextView android:id="@+id/main_text" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:textSize="16dp" android:lineSpacingExtra="2dip" /> </RelativeLayout> Is there any way I can keep the ordinary scroll behaviour and still detect the fling? EDIT: Sorry, my bad, this had nothing to do with the gesture detector, it was just because I took the TextView out of its ScrollView - for some reason it seems TextViews don't have smooth (inertia) scrolling like ScrollViews. A: The difference between scroll and fling events is that the user lifts his finger in the end of the movement in order to make it a fling. (and the speed is higher). Therefore, I think it is not possible to combine both events as they are (too) similar to detect (before ending them) which one is being performed. Also from a user perspective, using both gestures at the same time is confusing (due to the similarity). So the answer is: no there is no way to keep the ordinary scroll behaviour and still detect the fling. (at least I tried in the past and did not succeed in using both events in a proper way) A: I'm not sure this will be your problem, but why do you return true if your condition is met? If you don't want the event to be consumed, you should return false (or super.onFling). That's what the return value is for.
{ "language": "en", "url": "https://stackoverflow.com/questions/12894785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Underlay same histogram in each panel This is a followup to this, this, and this question. Currently, I have a twelve-panel lattice in which the same dark histogram outline is superimposed on twelve different solid gray histograms: This makes it easy to compare the new data in each panel with the same set of other data. Leaving out some details that are irrelevant to this question, my code looks like this: histogram(~ foo | bar, data=mydata[mydata$bar!="none",], # get only the 12 categories col=mylightgray, border=mylightgray, panel=function(...){panel.histogram(...) # add histogram to ea. panel: panel.histogram(x=mydata[mydata$bar=="none",]$foo, col="transparent", border="black")}) Now I want to reverse the colors, so to speak: I want to superimpose different outline histograms on the same solid gray histogram. Here's the problem: If I simply swap the colors, so that the main histogram has col="transparent" and border="black", while the panel function histogram uses mylightgray, the gray histograms will be on top, and will obscure parts of the outline histogram, which defeats the purpose of putting two histograms in one panel. On the other hand, if I swap the data specification, so that the outer main histogram uses bar=="none" and the panel histogram uses bar!="none", I only get one panel. The problem is that it's the main histogram call, not the extra panel function, that both writes first and also controls the number of panels. It appears to be impossible to create multiple panels in which the plot that's on the bottom is the same--unless I just create a dataframe with twelve duplicates of the same data. I wonder if there's a solution without producing special data. A: Swap the colors and the order of the panel.histograms calls. That is, plot the gray histogram first.
{ "language": "en", "url": "https://stackoverflow.com/questions/39005140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use subprocess Popen? I'm trying to execute a command using Popen. The command uses some PostGIS/Postgresql utility programs to upload a raster file to a database and works when executed from the command line. It uses unix style pipes to chain 2 commands and looks like this: "C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe" -d -I -C -e -Y -F -t 128x128 "C:\\temp\\SampleDTM\\SampleDTM.tif" test | "C:\\Program Files\\PostgreSQL\\9.2\\bin\\psql.exe" -h localhost -p 5432 -d adr_hazard -U postgres When using within Python, I make it a string with the ' codes: command = '"C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe" -d -I -C -e -Y -F -t 128x128 "C:\\temp\\SampleDTM\\SampleDTM.tif" test | "C:\\Program Files\\PostgreSQL\\9.2\\bin\\psql.exe" -h localhost -p 5432 -d adr_hazard -U postgres' attempting to execute it results in an error: p = subprocess.Popen(command) ERROR: Unable to read raster file: test The error seems like the command was not parsed correctly (it is interpreting the wrong argument as the raster file) Am I using Popen wrong? A: Your command uses pipe |. It requires a shell: p = subprocess.Popen(command, shell=True) The command itself as far as I can tell looks ok. A: It's not necessary to use shell=True to achieve this with pipes. This can be done programmatically with pipes even where concern about insecure input is an issue. Here, conn_params is a dictionary with PASSWORD, NAME (database name), USER, and HOST keys. raster2pgsql_ps = subprocess.Popen([ 'raster2pgsql', '-d', '-I', '-C', '-e', '-Y', '-F', '-t', '128x128', 'C:\\temp\\SampleDTM\\SampleDTM.tif', 'test' ], stdout=subprocess.PIPE) # Connection made using conninfo parameters # http://www.postgresql.org/docs/9.0/static/libpq-connect.html psql_ps = subprocess.check_output([ 'psql', 'password={PASSWORD} dbname={NAME} user={USER} host={HOST}'.format(**conn_params), ], stdin=raster2pgsql_ps.stdout) A: The following worked for me on Windows, while avoiding shell=True One can make use of Python's fstring formatting to make sure the commands will work in windows. Please note that I used shp2pgsql but it should be a very similar process for raster2pgsql. Parameters for the shp2pgsql: srid is the coordinate system of the shape file, filename is the path to the shape file to be imported, tablename is the name you'd like to give your table. import os import subprocess shp2pgsql_binary = os.path.join(pgsql_dir, "bin", "shp2pgsql") psql_binary = os.path.join(pgsql_dir, "bin", "psql") command0 = f'\"{shp2pgsql_binary}\" -s {srid} \"{filename}\" {tablename}' command1 = f'\"{psql_binary}\" \"dbname={databasename} user={username} password={password} host={hostname}\"' try: shp2pgsql_ps = subprocess.Popen(command0, stdout=subprocess.PIPE) psql_ps = subprocess.check_output(command1, stdin=shp2pgsql_ps.stdout) except: sys.stderr.write("An error occurred while importing data into the database, you might want to \ check the SQL command below:") sys.stderr.write(command) raise To adpat to raster2pgsql, you just need to modify the string in command0, e.g. -s {srid} becomes -d -I -C -e -Y -F -t 128x128. The string for command1 can remain the same. A: It will be better to use subprocess.Popen in this way: proc = subprocess.Popen(['"C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe"', '-d', '-I', '-C', '-e', '-Y', '-F', '-t', '128x128', '"C:\\temp\\SampleDTM\\SampleDTM.tif"', 'test', '|', '"C:\\Program Files\\PostgreSQL\\9.2\\bin\\psql.exe"', '-h', 'localhost', '-p', '5432', '-d', 'adr_hazard', '-U', 'postgres'], shell = True, stdout = subprocess.pipe, stderr = subprocess.STDOUT) proc.wait() result = proc.stdout.readlines()#if you want to process the result of your command proc.kill() B.T.W, it's good to format the path first, use: path = os.path.normalpath("C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe") this will avoid some path problems for different OS platform. The shell = True is important if you want to execute your command just like executing it in local shell. Hope will help you. A: PIPE = subprocess.PIPE pd = subprocess.Popen(['"C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe", '-d', '-I', '-C', '-e', '-Y', '-F', '-t', '128x128', "C:\\temp\\SampleDTM\\SampleDTM.tif", 'test'], stdout=PIPE, stderr=PIPE) stdout, stderr = pd.communicate()
{ "language": "en", "url": "https://stackoverflow.com/questions/22090626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to combine a variable and a special character into a regular expression I need to do something like this: st = 'abcdef' wr = 'ab' if re.search(^wr,st): print 'OK' the problem is I cannot combine special character with a variable (i.e. ^wr). Is there a way to do that?
{ "language": "en", "url": "https://stackoverflow.com/questions/43430096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find which key is pressed, not which character it will be? I need to find out which key was pressed, not what character it would be. For example, I want after pressing 'a' a number such (1) create so I can map it to other languages. In common way we can find it is 'a' or we can have it's hash code, but is it possible to have char or hash code in a language and find out what char or hash code it would be in another language? Attention some language have not the standard keyboard so pressing a key not mean a certain character. A: There's no reason to do this in any language i've seen. (besides the fact that you didn't specify in which language you are trying to achieve this) All languages allow you to get the character code from a keypress. If you know which encoding was used (UTF 8, Ascii, you name it), it's trivial to map the code to the actual character. Assigning a different keyboard layout on OS level means that it no longer matters which keyboard layout you are using. if you have a QWERTY keyboard, switch it to AZERTY and press the button where the q would be, you get an a, despite the letters on the keyboard still saying QWERTY. If you are using a chinese keyboard, the characters no longer map to any western set, so the character codes will not match up with UTF8 or ASCII, but CP963 (or another chinese codepage, depending on several factors), which is so different there is no real way to translate it to UTF8 or ASCII.
{ "language": "en", "url": "https://stackoverflow.com/questions/30749703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove an item from a UICollectionView I have a set of images showing in a UICollectionView. When the user taps on an image, it spawns a UIActionSheet with a few options for that image. One of them id removing the photo from the UICollectionView. When the user selects remove button in the UIActionSheet, it pops up an alert view asking for confirmation. If the user selects yes, it should remove the photo. My problem is, to remove the item from the UICollectionView, you have to pass the indexPath to the deleteItemsAtIndexPaths event. Since the final confirmation is granted in the alert view's didDismissWithButtonIndex event, I can't figure out a way to get the indexPath of the selected image from there to pass it to deleteItemsAtIndexPaths event. How can I do this? Here's my code: - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { switch (buttonIndex) { case 0: deletePhotoConfirmAlert = [[UIAlertView alloc] initWithTitle:@"Remove Photo" message:@"Do you want to remove this photo?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil]; [deletePhotoConfirmAlert addButtonWithTitle:@"Yes"]; [deletePhotoConfirmAlert show]; break; case 1: NSLog(@"To Edit photo"); break; } } - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { if (alertView == deletePhotoConfirmAlert) { if (buttonIndex == 1) { // Permission to delete the button is granted here. // From here deleteItemsAtIndexPaths event should be called with the indexPath } } } - (void)deleteItemsAtIndexPaths:(NSArray *)indexPaths { } A: Why not make use of [self.collectionView indexPathsForSelectedItems]; . I have done this for deleting multiple images at a time. - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { if (alertView == deletePhotoConfirmAlert) { if (buttonIndex == 1) { // Permission to delete the button is granted here. NSArray *selectedItemsIndexPaths = [self.collectionView indexPathsForSelectedItems]; // Delete the items from the data source. [self deleteItemsFromDataSourceAtIndexPaths:selectedItemsIndexPaths]; // Now delete the items from the collection view. [self.collectionView deleteItemsAtIndexPaths:selectedItemsIndexPaths]; } } } // This method is for deleting the selected images from the data source array -(void)deleteItemsFromDataSourceAtIndexPaths:(NSArray *)itemPaths { NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet]; for (NSIndexPath *itemPath in itemPaths) { [indexSet addIndex:itemPath.row]; } [self.images removeObjectsAtIndexes:indexSet]; // self.images is my data source } Edit -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { NSArray *indexpaths = [self.collectionView indexPathsForSelectedItems]; DetailViewController *dest = [segue destinationViewController]; dest.imageName = [self.images objectAtIndex:[[indexpaths objectAtIndex:0] row]]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/16080322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Horizontal lookup using unstructured lookup keys I need to find the rate for a given location and weight, using a lookup table that lists rates per location and weight. The problem is that the weights in the table are formatted like Up to 2 kg, 2.01-3 kg, 3.01-5 kg and so on, while the weights I am looking for are plain numbers like 10.5 and 13.5. How can I map the location-weight tuples to the rates in the lookup table? Spreadsheet here A: I am assuming that you want to obtain something like this: where you input a location in the A9 cell and a Weight in the B9 cell and it automatically puts the correct rate in the C9 cell. This can be achieved with the following formula (in the C9 cell): =ARRAYFORMULA(VLOOKUP(A9,A1:G5,HLOOKUP(B9,{A1:G1;COLUMN(A1:G1)},2,0),0)) which mixes VLOOKUP (you can read more about it here) to fetch the correct Location Code with HLOOKUP (you can read more about it here) to fetch the correct Weight. A: This can be done very simply by just nesting one FILTER inside another; as per the answer given by Oriel Castander you could use this formula in cell C9 instead: =filter(filter(B2:G5,A2:A5=A9),B1:G1=B9)
{ "language": "en", "url": "https://stackoverflow.com/questions/73217736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cordova iOs Google Maps map Blank on Appstore i have created an iPhone App with cordova and the google maps Plugin for Cordova (https://github.com/wf9a5m75/phonegap-googlemaps-plugin). I entered the API Key for Ios and on the Emulator it works great. Also when i test it on my iPhone it works. So i submitted the app to the AppStore and after it gets reviewed i downloaded it from the Appstore but the Map is blank. There are no Control Elements like when the API Key is wrong. Now my question is what i should do now? I tried: <access origin="*" /> * *Changing Bundle Identifier *Check API Key *Take the IPA and installed it manually on a iPhone/iPad (the Map works) So i think the Probleme must came from Apple or do i see that wrong? Thanks in advance A: The phonegap-googlemaps-plugin is not subjected by <access origin="*" />, because the Google Maps SDK for iOS connects to the internet directly. Typically the bundle identifier and the API key are mismatch. Google Maps iOS SDK Integration not loading maps Is there any error message in Xcode?
{ "language": "en", "url": "https://stackoverflow.com/questions/26461109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: Compare files with similar names (recursively) With the help of these guys, I was able to produce the following code, which reads in two files, (i.e., SA1.WRD and SA1.PHN), merges them, and compares the results against a sub-list of words excised from a dictionary: import sys import os import re import itertools #generator function to merge sound and word files def takeuntil(iterable, stop): for x in iterable: yield x if x[1] == stop: break #open a dictionary file and create subset of words class_defintion = re.compile('([1-2] [lnr] t en|[1-2] t en)') with open('TIMITDIC.TXT') as w_list: entries = (line.split(' ', 1) for line in w_list) comp_set = [ x[0] for x in entries if class_defintion.search(x[1]) ] #open word and sound files total_words = 0 with open(sys.argv[1]) as unsplit_words, open(sys.argv[2]) as unsplit_sounds: sounds = (line.split() for line in unsplit_sounds) words = (line.split() for line in unsplit_words) output = [ (word, " ".join(sound for _, _, sound in takeuntil(sounds, stop))) for start, stop, word in words ] for x in output: total_words += 1 #extract words from above into list of words in dictionary set glottal_environments = [ x for x in output if x[0] in comp_set ] I'm trying to modify the part after #open a dictionary files to run on a large directory with several subdirectories. Each subdirectory contains .txt files, .wav files, .wrd, and .phn files. I want to only open .wrd and .phn files, and I'd like to be able to open them two at a time, and only if the base file name matches, i.e, SA1.WRD and SA1.PHN, not SA1.WRD and SI997.PHN. My immediate guess was to do something like this: for root, dir, files in os.walk(sys.argv[1]): words = [f for f in files if f.endswith('.WRD')] phones = [f for f in files if f.endswith('.PHN')] phones.sort() words.sort() files = zip(words, phones) Which returns: [('SA1.WRD', 'SA1.PHN'), ('SA2.WRD', 'SA2.PHN'), ('SI997.WRD', 'SI997.PHN')] My first question is whether I am on the right track, and if so, my second question is how I can go about treating each of these items in these tuples as filenames to read. Thanks for any help you offer. EDIT: I figured I can put the block of code into a for loop: for f in files: #OPEN THE WORD AND PHONE FILES, COMAPRE THEM (TAKE A WORD COUNT) total_words = 0 with open(f[0]) as unsplit_words, open(f[1]) as unsplit_sounds: ... However, this causes an IOError, presumably due to the single-quotes around each item in each tuple. Update I modified my original script to include os.path.join(root, f) as noted below. The script now walks through all files in the directory tree, but it only processes the last two it finds. Here is the output of print files: [] [('test/test1/SI997.WRD', 'test/test1/SI997.PHN')] [('test/test2/SI997.WRD', 'test/test2/SI997.PHN')] A: I have tested different parts in relation to the filesystem but it's easier for you to confirm on the actual files to confirm it works on your data. EDIT to allow for inclusion of pathnames import sys import os import os.path import re import itertools #generator function to merge sound and word files def takeuntil(iterable, stop): for x in iterable: yield x if x[1] == stop: break def process_words_and_sounds(word_file, sound_file): #open word and sound files total_words = 0 with open(word_file) as unsplit_words, open(sound_file) as unsplit_sounds: sounds = (line.split() for line in unsplit_sounds) words = (line.split() for line in unsplit_words) output = [ (word, " ".join(sound for _, _, sound in takeuntil(sounds, stop))) for start, stop, word in words ] for x in output: total_words += 1 return total_words, output for root, dir, files in os.walk(sys.argv[1]): words = [ os.path.join( root, f ) for f in files if f.endswith('.WRD')] phones = [ os.path.join( root, f ) for f in files if f.endswith('.PHN')] phones.sort() words.sort() files = zip(words, phones) # print files output = [] total_words = 0 for word_sounds in files: word_file, sound_file = word_sounds word_count, output_subset = process_words_and_sounds(word_file, sound_file) total_words += word_count output.extend( output_subset ) #open a dictionary file and create subset of words class_defintion = re.compile('([1-2] [lnr] t en|[1-2] t en)') with open('TIMITDIC.TXT') as w_list: entries = (line.split(' ', 1) for line in w_list) comp_set = [ x[0] for x in entries if class_defintion.search(x[1]) ] #extract words from above into list of words in dictionary set glottal_environments = [ x for x in output if x[0] in comp_set ]
{ "language": "en", "url": "https://stackoverflow.com/questions/10713131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error with gem install sqlite3 on MacOS Monterey with Ruby 3.0.2 on Apple Silicon M1 I’m getting errors when I try to gem install sqlite3 under a fresh rbenv installation of Ruby 3.0.2. The sqlite3 gem installs successfully under Ruby 2.7.4. What is the fix for this? I’m using MacOS Monterey on an Apple Silicon M1 machine. ➜ ~ > rbenv shell 3.0.2 ➜ ~ > gem install sqlite3 Fetching sqlite3-1.4.2.gem Building native extensions. This could take a while… ERROR: Error installing sqlite3: ERROR: Failed to build gem native extension. current directory: /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3 /Users/brian/.rbenv/versions/3.0.2/bin/ruby -I /Users/brian/.rbenv/versions/3.0.2/lib/ruby/3.0.0 -r ./siteconf20211119-57074-7hi3f4.rb extconf.rb checking for sqlite3.h… yes checking for pthread_create() in -lpthread… yes checking for -ldl… yes checking for sqlite3_libversion_number() in -lsqlite3… yes checking for rb_proc_arity()… yes checking for rb_integer_pack()… yes checking for sqlite3_initialize()… yes checking for sqlite3_backup_init()… yes checking for sqlite3_column_database_name()… yes checking for sqlite3_enable_load_extension()… yes checking for sqlite3_load_extension()… yes checking for sqlite3_open_v2()… yes checking for sqlite3_prepare_v2()… yes checking for sqlite3_int64 in sqlite3.h… yes checking for sqlite3_uint64 in sqlite3.h… yes creating Makefile current directory: /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3 make DESTDIR\= clean current directory: /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/sqlite3-1.4.2/ext/sqlite3 make DESTDIR\= compiling aggregator.c In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/defines.h:73: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/backward/2/attributes.h:43: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/pure.h:25: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/assert.h:132:1: error: '__declspec' attributes are not enabled; use '-fdeclspec' or '-fms-extensions' to enable support for __declspec attributes RBIMPL_ATTR_NORETURN() ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noreturn.h:29:33: note: expanded from macro 'RBIMPL_ATTR_NORETURN' # define RBIMPL_ATTR_NORETURN() __declspec(noreturn) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:24: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/anyargs.h:77: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/intern/vm.h:64:1: error: '__declspec' attributes are not enabled; use '-fdeclspec' or '-fms-extensions' to enable support for __declspec attributes RBIMPL_ATTR_NORETURN() ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noreturn.h:29:33: note: expanded from macro 'RBIMPL_ATTR_NORETURN' # define RBIMPL_ATTR_NORETURN() __declspec(noreturn) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/int.h:26: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/long.h:70:1: error: '__declspec' attributes are not enabled; use '-fdeclspec' or '-fms-extensions' to enable support for __declspec attributes RBIMPL_ATTR_NORETURN() ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noreturn.h:29:33: note: expanded from macro 'RBIMPL_ATTR_NORETURN' # define RBIMPL_ATTR_NORETURN() __declspec(noreturn) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:28: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:46:14: error: expected parameter declarator RUBY_ALIGNAS(SIZEOF_VALUE) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/value.h:41:23: note: expanded from macro 'SIZEOF_VALUE' # define SIZEOF_VALUE SIZEOF_LONG ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/arm64-darwin21/ruby/config.h:61:21: note: expanded from macro 'SIZEOF_LONG' #define SIZEOF_LONG 8 ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:28: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:46:14: error: expected ')' /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/value.h:41:23: note: expanded from macro 'SIZEOF_VALUE' # define SIZEOF_VALUE SIZEOF_LONG ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/arm64-darwin21/ruby/config.h:61:21: note: expanded from macro 'SIZEOF_LONG' #define SIZEOF_LONG 8 ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:46:1: note: to match this '(' RUBY_ALIGNAS(SIZEOF_VALUE) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/backward/2/stdalign.h:27:22: note: expanded from macro 'RUBY_ALIGNAS' #define RUBY_ALIGNAS RBIMPL_ALIGNAS ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/stdalign.h:66:44: note: expanded from macro 'RBIMPL_ALIGNAS' # define RBIMPL_ALIGNAS(_) __declspec(align(_)) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:28: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:47:1: error: expected function body after function declarator RBasic { ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:82:23: error: incomplete definition of type 'struct RBasic' return RBASIC(obj)->klass; ~~~~~~~~~~~^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:82:12: note: forward declaration of 'struct RBasic' return RBASIC(obj)->klass; ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:50: note: expanded from macro 'RBASIC' #define RBASIC(obj) RBIMPL_CAST((struct RBasic *)(obj)) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:35: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/value_type.h:157:28: error: incomplete definition of type 'struct RBasic' VALUE ret = RBASIC(obj)->flags & RUBY_T_MASK; ~~~~~~~~~~~^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/value_type.h:157:17: note: forward declaration of 'struct RBasic' VALUE ret = RBASIC(obj)->flags & RUBY_T_MASK; ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:50: note: expanded from macro 'RBASIC' #define RBASIC(obj) RBIMPL_CAST((struct RBasic *)(obj)) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:237:23: error: incomplete definition of type 'struct RBasic' return RBASIC(obj)->flags & flags; ~~~~~~~~~~~^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:237:12: note: forward declaration of 'struct RBasic' return RBASIC(obj)->flags & flags; ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:50: note: expanded from macro ‘RBASIC’ #define RBASIC(obj) RBIMPL_CAST((struct RBasic *)(obj)) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:285:1: error: ‘__declspec’ attributes are not enabled; use ‘-fdeclspec’ or ‘-fms-extensions’ to enable support for __declspec attributes RBIMPL_ATTR_NOALIAS() ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noalias.h:53:32: note: expanded from macro ‘RBIMPL_ATTR_NOALIAS’ # define RBIMPL_ATTR_NOALIAS() __declspec(noalias) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:288:30: warning: declaration of ‘struct RBasic’ will not be visible outside of this function [-Wvisibility] rbimpl_fl_set_raw_raw(struct RBasic *obj, VALUE flags) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:290:8: error: incomplete definition of type 'struct RBasic' obj->flags |= flags; ~~~^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:288:30: note: forward declaration of ‘struct RBasic’ rbimpl_fl_set_raw_raw(struct RBasic *obj, VALUE flags) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:298:27: warning: incompatible pointer types passing ‘struct RBasic *’ to parameter of type ‘struct RBasic *’ [-Wincompatible-pointer-types] rbimpl_fl_set_raw_raw(RBASIC(obj), flags); ^~~~~~~~~~~ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:30: note: expanded from macro ‘RBASIC’ #define RBASIC(obj) RBIMPL_CAST((struct RBasic *)(obj)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/cast.h:33:28: note: expanded from macro ‘RBIMPL_CAST’ # define RBIMPL_CAST(expr) (expr) ^~~~~~ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:288:38: note: passing argument to parameter ‘obj’ here rbimpl_fl_set_raw_raw(struct RBasic *obj, VALUE flags) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:310:1: error: ‘__declspec’ attributes are not enabled; use ‘-fdeclspec’ or ‘-fms-extensions’ to enable support for __declspec attributes RBIMPL_ATTR_NOALIAS() ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noalias.h:53:32: note: expanded from macro ‘RBIMPL_ATTR_NOALIAS’ # define RBIMPL_ATTR_NOALIAS() __declspec(noalias) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:313:32: warning: declaration of ‘struct RBasic’ will not be visible outside of this function [-Wvisibility] rbimpl_fl_unset_raw_raw(struct RBasic *obj, VALUE flags) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:315:8: error: incomplete definition of type 'struct RBasic' obj->flags &= ~flags; ~~~^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:313:32: note: forward declaration of ‘struct RBasic’ rbimpl_fl_unset_raw_raw(struct RBasic *obj, VALUE flags) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:323:29: warning: incompatible pointer types passing ‘struct RBasic *’ to parameter of type ‘struct RBasic *’ [-Wincompatible-pointer-types] rbimpl_fl_unset_raw_raw(RBASIC(obj), flags); ^~~~~~~~~~~ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:30: note: expanded from macro ‘RBASIC’ #define RBASIC(obj) RBIMPL_CAST((struct RBasic *)(obj)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/cast.h:33:28: note: expanded from macro ‘RBIMPL_CAST’ # define RBIMPL_CAST(expr) (expr) ^~~~~~ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:313:40: note: passing argument to parameter ‘obj’ here rbimpl_fl_unset_raw_raw(struct RBasic *obj, VALUE flags) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:335:1: error: ‘__declspec’ attributes are not enabled; use ‘-fdeclspec’ or ‘-fms-extensions’ to enable support for __declspec attributes RBIMPL_ATTR_NOALIAS() ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/attr/noalias.h:53:32: note: expanded from macro ‘RBIMPL_ATTR_NOALIAS’ # define RBIMPL_ATTR_NOALIAS() __declspec(noalias) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:30: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:338:34: warning: declaration of ‘struct RBasic’ will not be visible outside of this function [-Wvisibility] rbimpl_fl_reverse_raw_raw(struct RBasic *obj, VALUE flags) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:340:8: error: incomplete definition of type 'struct RBasic' obj->flags ^= flags; ~~~^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:338:34: note: forward declaration of ‘struct RBasic’ rbimpl_fl_reverse_raw_raw(struct RBasic *obj, VALUE flags) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:348:31: warning: incompatible pointer types passing ‘struct RBasic *’ to parameter of type ‘struct RBasic *’ [-Wincompatible-pointer-types] rbimpl_fl_reverse_raw_raw(RBASIC(obj), flags); ^~~~~~~~~~~ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:30: note: expanded from macro 'RBASIC' #define RBASIC(obj) RBIMPL_CAST((struct RBasic *)(obj)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/cast.h:33:28: note: expanded from macro 'RBIMPL_CAST' # define RBIMPL_CAST(expr) (expr) ^~~~~~ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:338:42: note: passing argument to parameter 'obj' here rbimpl_fl_reverse_raw_raw(struct RBasic *obj, VALUE flags) ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:465:43: error: incomplete definition of type 'struct RBasic' if (RBASIC_CLASS(x) && !(RBASIC(x)->flags & RUBY_FL_SINGLETON)) { ~~~~~~~~~^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/fl_type.h:465:34: note: forward declaration of 'struct RBasic' if (RBASIC_CLASS(x) && !(RBASIC(x)->flags & RUBY_FL_SINGLETON)) { ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rbasic.h:34:50: note: expanded from macro 'RBASIC' #define RBASIC(obj) RBIMPL_CAST((struct RBasic *)(obj)) ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:25: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic.h:23: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/arithmetic/char.h:29: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:74:19: error: field has incomplete type 'struct RBasic' struct RBasic basic; ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:74:12: note: forward declaration of 'struct RBasic' struct RBasic basic; ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:109:26: error: incomplete definition of type 'struct RBasic' VALUE f = RBASIC(str)->flags; ~~~~~~~~~~~^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:74:12: note: forward declaration of ‘struct RBasic’ struct RBasic basic; ^ In file included from aggregator.c:1: In file included from ./aggregator.h:4: In file included from ./sqlite3_ruby.h:4: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby.h:38: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/ruby.h:26: In file included from /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core.h:23: /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rarray.h:88:19: error: field has incomplete type ‘struct RBasic’ struct RBasic basic; ^ /Users/brian/.rbenv/versions/3.0.2/include/ruby-3.0.0/ruby/internal/core/rstring.h:74:12: note: forward declaration of ‘struct RBasic’ struct RBasic basic; ^ fatal error: too many errors emitted, stopping now [-ferror-limit=] 6 warnings and 20 errors generated. make: *** [aggregator.o] Error 1 make failed, exit code 2 Gem files will remain installed in /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/sqlite3-1.4.2 for inspection. Results logged to /Users/brian/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/extensions/arm64-darwin-21/3.0.0/sqlite3-1.4.2/gem_make.out ➜ ~ > A: I figured out the answer. It works if I prepend the gem install command with CC='clang -fdeclspec'. Like this: CC='clang -fdeclspec' gem install sqlite3
{ "language": "en", "url": "https://stackoverflow.com/questions/70040049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: D3.js Brush controls with Ordinal Crossfilter Scales I'm aiming to subset my choropleth like this wonderful example. I've reviewed the API documentation and Mike's Ordinal Brushing example. Unfortunately, I'm still not getting my thick head around how brushes are supposed to work. The examples are sophisticated and somewhat inaccessible for newcomers (lots of turnery operators and arrays of chart objects etc). I've chosen not to use dc.js due to lack of support for things I'll have to deal with later. Nice work though and props to Nick Qi Zhu. Can someone pls review my (native d3) approach and show me what I'm doing wrong? I've setup my bar chart which renders fine. Basically a count of values in a normal distribution. // Setup Crossfilter dimensions and groups var nation = crossfilter(MSPB), byScr = nation.dimension(function(d){ return d.score; }), byScrGrp = byScr.group().reduceCount(), byHosp = nation.dimension(function(d){ return d.FIPS; }); // Histogram X-Axis ordinal scale var x = d3.scale.ordinal() .domain(d3.range(0,2,0.1)) .rangeBands([0, width, 0.5, 0.5 ]); // Histogram Y-Axis linear scale var y = d3.scale.linear() .domain([0, d3.max(byScrGrp.all(), function(d){ return d.value; })]) .range([height/2, 0]); // Histogram SVG containiner var svg = d3.select("#histogram").append("svg:svg") .attr("width", width + margin.left + margin.right) .attr("height", height/2 + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // Histogram bars svg.selectAll("rect") .data(byScrGrp.all()) .enter().append("rect") .attr("x", function(d,i){ return i * (width / byScrGrp.size() ); }) .attr("width", width / byScrGrp.size() - barPadding ) .attr("y", function(d){ return y(d.value) ; }) .attr("height", function(d){ return ((height/2) -y(d.value)); }) .attr("fill", function(d){ return color(d.key); }) .on("mouseover", function(d){ d3.select(this).attr("fill", "teal"); }) .on("mouseout", function(d) { d3.select(this).attr("fill", function(d){return color(d.key);}) } ); Immediately after, I try to add my brush controls like this. Initially I just want to get the drag selection working on the bar chart. I'll worry about getting xAxis extent values for filtering the choropleth later. var brush = d3.svg.brush() .x(x) .on("brushstart", brushstart) .on("brush", brushmove) .on("brushend", brushend) var brushg = svg.append("g") .attr("class", "brush") .call(brush) brushg.selectAll("rect") .attr("height", height/2) .attr("width", width); function brushstart() { svg.classed("selecting", true); } function brushmove() { var s = brush.extent(); brushg.classed("selected", function(d) { return s[0] <= (d = x(d)) && d <= s[1]; }); } function brushend() { svg.classed("selecting", !d3.event.target.empty()); } I'm seeing the crosshair drag handles but not seeing what I'd expect and certainly not getting the desired effect. It's slow on this webserver but the full js file is here and partially working example here. EDIT: I've tried to create a JSFiddle here. Any pointers would be much appreciated. Thanks A: Hard to say without experimenting (any chance of creating a JSfiddle or similar?). I suspect the issue is that you are setting the width of all the rects in the brush. You only need to set the height, I believe. This is probably what is causing your extents to go all crazy. Once you get that straightened out, you'll need to filter your Crossfilter dimension based on the brush extent. Also, Crossfilter's group.reduceCount function doesn't take an argument, and if it is possible you are missing data you need to make sure to test/cast your data in your dimension accessors to make sure they always return naturally ordered numbers or strings.
{ "language": "en", "url": "https://stackoverflow.com/questions/30330821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HazelCast - How to insert records through a Map to a table with auto sequence field as PK I am using HazelCast to do read/write operations on MS SQL server database. I have a database table whose primary key is an auto increment column. I read existing data in this table to a Map when my application starts. The Map has an underlying MapStore implementation. The key of the map is the auto increment column value. The value of the map is an object containing few fields from the table. User can insert records to this table through the HazelCast layer. This insert is performed in a Transaction (TransactionalMap is obtained from HazelCast). It is at this place i face a problem as i do not have the primary key value (auto increment value) to set to the TransactionalMap instance. I have the insert to database table logic in the MapStore's store() method and the store() method is called only after commit is called on the Transaction. I am not getting how to first set the key value (auto increment value) to the map. Auto increment value can be obtained post the insert to the table. Ideas/Points are most welcome. Thanks, s.r.guruprasad A: You can implement PostProcessingMapStore interface on your MapStore which enables the ability to update the stored entry inside the store() method. You can obtain the auto-generated fields from the database then you can reflect those changes to your entry. See Post Processing documentation : http://docs.hazelcast.org/docs/latest-dev/manual/html-single/index.html#post-processing-objects-in-map-store A: The only way I can see to do what you ask is to have your code write a demo record into the database and then read it back before into Hz and making MapStore do an update rather than insert. Of course this would be slow and cumbersome. The best solution would be to turn off the autoincrement, but what you could also do is use a different field as the cache key, say have a member called cacheKey and store that in your database record, when you do an insert in MapStore you just need insert where databaserecord.cachekey == cacheKey.
{ "language": "en", "url": "https://stackoverflow.com/questions/40425286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Please explain '%' usage in python I'm learning multithreading in python and I was reading through this answer. I understand most of the code however there is this one line which I simply don't understand and I don't know how to search for it on Google as the '%' sign keeps returning modulo. req.headers['Range'] = 'bytes=%s-%s' % (start, start+chunk_size) I thought that req.headers['Range'] would retrieve some 'range' element from an array however here they are assigning it a value of 'bytes=%s-%s' % (start, start+chunk_size). I really just don't understand what is going on in this line. Things like 'bytes=%s-%s' I am assuming is some sort of python syntax which I am unaware of. If you could explain each term in this line that would be very much appreciated. A: In python there are multiple ways to format strings. using %s inside a string and then a % after the string followed by a tuple (or a single value), allows you to create a new string: x = 5 y = 8 'my favourite number is %s, but I hate the number %s' % (x, y) results in: 'my favourite number is 5, but I hate the number 8' I think they call it C-type string formatting. For more information, you can check out this page. In my opinion, it is easier to format string using f'strings, or .format(). Check out this page too
{ "language": "en", "url": "https://stackoverflow.com/questions/53946697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Latitude and Longitude are null I'm working on an app getting user's current location and showing it on map, as well as Latitude and Longitude on the screen, so far everything is going fine, the map's showing my current location as well as displaying latitude and longitude on the screen using this code @Override public void onLocationChanged(Location location) { TextView tvLocation = (TextView) findViewById(R.id.tv_location); // Getting latitude of the current location double latitude = location.getLatitude(); // Getting longitude of the current location double longitude = location.getLongitude(); // Creating a LatLng object for the current location LatLng latLng = new LatLng(latitude, longitude); // Showing the current location in Google Map googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); // Zoom in the Google Map googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); // Setting latitude and longitude in the TextView tv_location tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude ); } Problem occurs when I want to send this latitude and longitude on server , it throws NUll pointer exception 01-04 23:27:38.759 29286-29286/io.xgear.geotag E/AndroidRuntime: FATAL EXCEPTION: main Process: io.xgear.geotag, PID: 29286 java.lang.NullPointerException at io.xgear.geotag.MainActivity$GeoTagTask.<init>(MainActivity.java:234) at io.xgear.geotag.MainActivity$1.onClick(MainActivity.java:181) at android.view.View.performClick(View.java:4633) at android.view.View$PerformClick.run(View.java:19270) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:146) at android.app.ActivityThread.main(ActivityThread.java:5602) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) at dalvik.system.NativeStart.main(Native Method) this is the piece of code for getting latitude and longitude to send public class GeoTagTask extends AsyncTask<Void, Void, Boolean> { private final String shopCode; Location location; private String lat = Double.toString(location.getLatitude()); private String lng = Double.toString(location.getLongitude()); private boolean isConnect; GeoTagTask(String shopId) { shopCode = shopId; isConnect = false; } @Override protected Boolean doInBackground(Void... params) { boolean res = false; try { ContentValues nameValuePairs = new ContentValues(); nameValuePairs.put("Id", shopCode); nameValuePairs.put("lat", lat); nameValuePairs.put("lng", lng); //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show(); Log.i("Latitude", lat+""); Post post = new Post(getApplicationContext()); String result = ""; // isConnect = post.isConnected(); // if(isConnect) { result = post.doPost(nameValuePairs); jsonObj = new JSONObject(result); Log.i("Result", result+""); if(jsonObj.getInt("success") == 1) res = true; // } } catch (JSONException e) { e.printStackTrace(); } return res; } and this is the full code package io.xgear.geotag; import android.Manifest; import android.app.Dialog; import android.app.FragmentTransaction; import android.content.pm.PackageManager; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.widget.TextView; import android.support.v4.app.Fragment; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.content.ContentValues; import android.os.AsyncTask; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import io.xgear.geotag.helper.Post; public class MainActivity extends FragmentActivity implements LocationListener { GoogleMap googleMap; private GeoTagTask mAuthTask = null; GPSTracker gps; private JSONObject jsonObj; // UI references. private EditText txtShopCode; private EditText lblAddress; private View mProgressView; private View mGeoTagForm; private Button btnGeoTag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtShopCode = (EditText) findViewById(R.id.txtShopCode); btnGeoTag = (Button) findViewById(R.id.btnGeoTag); mGeoTagForm = (View) findViewById(R.id.geoTagForm); mProgressView = findViewById(R.id.geoTagProgress); // Getting Google Play availability status int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); // Showing status if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available int requestCode = 10; Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); dialog.show(); } else { // Google Play Services are available // Getting reference to the SupportMapFragment of activity_main.xml SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); // Getting GoogleMap object from the fragment googleMap = fm.getMap(); // Enabling MyLocation Layer of Google Map googleMap.setMyLocationEnabled(true); // Getting LocationManager object from System Service LOCATION_SERVICE LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); // Creating a criteria object to retrieve provider Criteria criteria = new Criteria(); // Getting the name of the best provider String provider = locationManager.getBestProvider(criteria, true); // Getting Current Location if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } Location location = locationManager.getLastKnownLocation(provider); if(location!=null){ onLocationChanged(location); } locationManager.requestLocationUpdates(provider, 20000, 0, this); } btnGeoTag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { String shopid = txtShopCode.getText().toString(); boolean cancel = false; View focusView = null; //txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER); if (TextUtils.isEmpty(shopid)) { txtShopCode.setError(getString(R.string.error_field_required)); focusView = txtShopCode; cancel = true; } else { showProgress(true); mAuthTask = new GeoTagTask(shopid); mAuthTask.execute((Void) null); } } }); } // // public void btnGeoTag_Click(View v){ // // } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE); mGeoTagForm.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE); } } public class GeoTagTask extends AsyncTask<Void, Void, Boolean> { private final String shopCode; Location location; private String lat = Double.toString(location.getLatitude()); private String lng = Double.toString(location.getLongitude()); private boolean isConnect; GeoTagTask(String shopId) { shopCode = shopId; isConnect = false; } @Override protected Boolean doInBackground(Void... params) { boolean res = false; try { ContentValues nameValuePairs = new ContentValues(); nameValuePairs.put("Id", shopCode); nameValuePairs.put("lat", lat); nameValuePairs.put("lng", lng); //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show(); Log.i("Latitude", lat+""); Post post = new Post(getApplicationContext()); String result = ""; // isConnect = post.isConnected(); // if(isConnect) { result = post.doPost(nameValuePairs); jsonObj = new JSONObject(result); Log.i("Result", result+""); if(jsonObj.getInt("success") == 1) res = true; // } } catch (JSONException e) { e.printStackTrace(); } return res; } @Override protected void onPostExecute(final Boolean success) { mAuthTask = null; showProgress(false); if (success) { // Intent intent = new Intent(LoginActivity.this, MainActivity.class); // intent.putExtra("jsonObj", jsonObj.toString()); // startActivity(intent); txtShopCode.getText().clear(); txtShopCode.requestFocus(); Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show(); } else { // if(isConnect){ // mPasswordView.setError(getString(R.string.error_incorrect_password)); // mPasswordView.requestFocus(); // } // else Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show(); } } @Override protected void onCancelled() { mAuthTask = null; showProgress(false); } } @Override public void onLocationChanged(Location location) { TextView tvLocation = (TextView) findViewById(R.id.tv_location); // Getting latitude of the current location double latitude = location.getLatitude(); // Getting longitude of the current location double longitude = location.getLongitude(); // Creating a LatLng object for the current location LatLng latLng = new LatLng(latitude, longitude); // Showing the current location in Google Map googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); // Zoom in the Google Map googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); // Setting latitude and longitude in the TextView tv_location tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude ); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.activity_main, menu); // return true; // } } UPDATE I have added thes lines in GeoTagTask the button is working the app is not crashing but I'm not sure if it's going to work if location is changed because if( location != null){ onLocationChanged(location); } locationManager.requestLocationUpdates(provider, 20000, 0, this); is giving me errors . The lines I have added LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(provider); A: inside GeoTagTask location object is different one and also doesn't initilized. Location location; private String lat = Double.toString(location.getLatitude()); private String lng = Double.toString(location.getLongitude()); A: Problem Problem is inside GeoTagTask , Location location; private String lat = Double.toString(location.getLatitude()); private String lng = Double.toString(location.getLongitude()); You are accessing an uninitialized variable. Solution Make onCreate location a global variable, public class MainActivity extends FragmentActivity implements LocationListener { Location location; void onCreate() { .... location = locationManager.getLastKnownLocation(provider); .... } } Use the global variable inside GeoTagTask, public class GeoTagTask extends AsyncTask<Void, Void, Boolean> { private String lat = Double.toString(location.getLatitude()); private String lng = Double.toString(location.getLongitude()); ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/34597831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Merge multiple mutually exclusive factor columns into a single column Say I have three columns in a data frame. I want to merge these into a single column. Each of the three columns is a binary attribute such as green/yellow, red/blue, black/white, etc. I want to merge all of these into a single column with multiple row1=c(0,0,1) row2=c(1,0,0) row3=c(0,1,0) df=data.frame(rbind(row1,row2,row3)) Is there a way to merge each of these columns into a single column? The single column would now have to have six different factors instead of the two it already has. Can anyone show me how to code this? A: You can encode these as you would encode a binary number, by assigning increasing powers of two for each column. You want to multiply each row by c(1,2,4) and then take the sum. # The multiplier, powers of two x <- 2^(seq(ncol(df))-1) x ## [1] 1 2 4 # The values apply(df, 1, function(row) sum(row*x)) ## row1 row2 row3 ## 4 1 2 To add this as a new column: df$new <- apply(df, 1, function(row) sum(row*x)) df ## X1 X2 X3 new ## row1 0 0 1 4 ## row2 1 0 0 1 ## row3 0 1 0 2 A: Try: > df X1 X2 X3 row1 0 0 1 row2 1 0 0 row3 0 1 0 > > > mm = melt(df) No id variables; using all as measure variables > > mm$new = paste(mm$variable,mm$value,sep='_') > > mm variable value new 1 X1 0 X1_0 2 X1 1 X1_1 3 X1 0 X1_0 4 X2 0 X2_0 5 X2 0 X2_0 6 X2 1 X2_1 7 X3 1 X3_1 8 X3 0 X3_0 9 X3 0 X3_0 mm$new is the column you want. A: Maybe this is what you want: > df$X1 = ifelse(df$X1==0,'green','yellow') > df$X2 = ifelse(df$X2==0,'red','blue') > df$X3 = ifelse(df$X3==0,'black','white') > > df X1 X2 X3 row1 green red white row2 yellow red black row3 green blue black > > unlist(df) X11 X12 X13 X21 X22 X23 X31 X32 X33 "green" "yellow" "green" "red" "red" "blue" "white" "black" "black"
{ "language": "en", "url": "https://stackoverflow.com/questions/25839962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't the ttf fonts work with Vue CLI? I am working with Vue CLI, and I want to use a font downloaded from the Internet. I think I have configured everything but it just doesn't work. The structure of the project is like this: +--node_modules +--public | +--index.html +--src | +--assets | | +--css | | +--font | | | +--font.css | | | +--FZYXJW.ttf | +--components | +--App.vue | +--main.js +--babel.config.js +--vue.config.js +--package.json Here are the relative codes: // font.css @font-face { font-family: 'Youxian'; src: url("FZYXJW.ttf"); } // vue.config.js module.exports = { chainWebpack: config => { config.module .rule('font') .test(/\.(woff2?|eot|ttf|otf)(\?.*)?$/) .use('url-loader') .loader('url-loader') .end() } }; // App.vue <template> <div id="app"> <router-view></router-view> </div> </template> <script> export default { name: 'app' } </script> <style> @import "/assets/font/font.css"; #app { font-family: 'Youxian'; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } </style> I expected the font to change to "Youxian", but actually nothing happened.
{ "language": "en", "url": "https://stackoverflow.com/questions/55667026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot upload chunked video to twitter I have been trying to upload video chunks to twitter using twurl as in the example on the page: https://blog.twitter.com/2015/rest-api-now-supports-native-video-upload However, I get the "unsupported video" error. I am able to upload smaller sized videos without breaking them into chunks. I am running twurl on Ubuntu 12.04 A: It means exactly "unsupported video". Twitter has a strict video format requirement: https://dev.twitter.com/rest/public/uploading-media#videorecs. Example: sample mp4 files containing 6-channel audio won't be supported. Check out my project: https://github.com/mtrung/TwitterVideoUpload.
{ "language": "en", "url": "https://stackoverflow.com/questions/30599580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Studio, on Windows: ADB not responding. If you'd like to retry, then please manually kill "adb.exe" and click 'Restart' I downloaded Android Studio on windows, and I am trying to run the default HelloWorld application. However, when I run that app, I get a dialog box with the following: ADB not responding. If you'd like to retry, then please manually kill "adb.exe" and click 'Restart' I've searched for solutions online and most of it was to kill the adb server and start it again manually, but when I do so in the command line I get: sdk\platform-tools>adb kill-server * server not running * sdk\platform-tools>adb start-server adb server is out of date. killing... ADB server didn't ACK * failed to start daemon * And the first error keeps showing. I restarted my machine, and the problem is still there. Any ideas? Thanks. I tried this fix: http://visualgdb.com/adbfix/#adbfix_download but it did not work. It showed: "No Conflicts Found". Note: I need the app to run on my device. Not on emulator A: I was also facing same issue and I followed these steps and problem went away: 1.close all program in your system then 2.then go to start button and search for %temp% then delete all files inside this folder 3.install Cclean software and clean your system. 4.restart your system A: I was facing same issue in win7 and I took these steps to resolve the problem: When starting Android Studio, it warns you with ADB not responding. If you'd like to retry, then please manually kill the process. You should enter cmd, and input adb kill-server for ten times or more. When the building has finished, input adb start-server and you will see daemon not running. starting it now on port 5037 daemon started successfully
{ "language": "en", "url": "https://stackoverflow.com/questions/28189336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Query regarding looping a response data array using async await I am working with an existing class components based React application and was dumbfounded when I spent almost 3 hours to figure out the root cause of the following code snippet. In componentDidMount which is async btw, I am calling backend API designed with Node.js using axios like this (Note state below is in Class Component which I skipped for obvious reasons) state = { grades = []; } try { const res = await axios.get( `/assignments/getStudentAssignment/${this.props.studentId}` ); const assignments = res.data.assignment.assignments; assignments.forEach((assignment) => { this.setState({grades: [...this.state.grades, assignment.grade]}) })) } catch (err) { 'some logic' } Where res.data.assignment.assignments is an array of each student assignments, and from each assignment I am pushing a new grade in grades array state. In console.log using Chrome browser I saw that the grades array had 8 elements but I couldn't view them in console.log, and the length of array was also set to 0. I consoled assignment within forEach array and also set a counter in order to see that is forEach looping through the entire array or just first element. Console.log only printed first counter number and also first array element I figured out that since the assignments is an array of promises that are yet to be resolved, I cannot loop through the entire array, and then I changed my code to this await assignments.forEach((assignment) => { this.setState({grades: [...this.state.grades, assignment.grade]}) })) And viola, it worked like a charm but I am confused on a couple of things. * *Isn't await supposed to resolve promise res.data.assignment.assignments, meaning I can loop through resolved array data *Why did forEach work for only first element of res.data.assignment.assignments if the array was yet to be resolved? I tried on MDN, by creating a sample array in a promise and then looping through the contents of array in a then chain where each element was printed on console perfectly. Any help will be appreciated EDIT I have changed the original code, axios returns an assignment object which also contains an array of assignments I worked with the following code once again without await, and its working fine. This is the second time, I had trouble with React setState, first time setState wasn't firing for some reason, and then after deleting node_modules and installing all required packages it worked, even though it wasted a day state = { grades = []; } try { const res = await axios.get( `/assignments/getStudentAssignment/${this.props.studentId}` ); const assignments = res.data.assignment.assignments; assignments.forEach((assignment) => { this.setState({grades: [...this.state.grades, assignment.grade]}) })) } catch (err) { 'some logic' }
{ "language": "en", "url": "https://stackoverflow.com/questions/68756064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding new variables to existing data that correlate with one or two existing ones How can I add two more variables with the following conditions? * *Variable "c" that has a 0.7 correlation with variable "a". *If possible, variable "d" that correlates simultaneously with "a" and "b". Simulated data n = 100 d = tibble(a = rnorm(n, 50, 20), b = rnorm(n, 10, 0.4)) d Tidyverse solutions are much appreciated! A: Here is a small function that take a vector x and a desired rho and returns a vector such that cor(<vector>,x) == rho`). f <- function(x,rho) { orth = lm(runif(length(x))~x)$residuals rho*sd(orth)*x + orth*sd(x)*sqrt(1-rho^2) } Now we apply the function to column a to create a column c such that cor(a,c) == 0.7 d %>% mutate(c = f(a,.7)) A: The second is actually more easier (for me at least): just make z-scores out of both a and b and add or average them. It will correlate with both a and b with 0.7 d <- d %>% mutate(d=((a - mean(a)) / sd(a)) + ((b- mean(b)) / sd(b))) A: Using the Iman and Conover method (1982) developed in the mc2d package (a rank correlation structure). library(mc2d) cc <- rnorm(n,50,20) cc <- cornode(cbind(d$a,cc), target=0.7)[,"cc"] d$c <- cc cor(d) For more than one variable, you have to build a matrix of correlation. ## Target (corrTarget <- matrix(c(1, 0.7, 0.7, 0.7, 1, 0.7, 0.7, 0.7, 1), ncol=3)) dd <- rnorm(n,50,20) dd <- cornode(cbind(a=d$a,b=d$b,dd), target=corrTarget) cor(dd) d$b <- dd[,"b"] d$d <- dd[,"dd"] cor(d) The final correlation structure should be checked because it is not always possible to build the target correlation structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/71450770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: 'in' operator with boost::python I have a class which .defines the __getitem__, __setitem__ methods (and keys and items as well), and behaves like a dictionary, where keys are strings. However, the in operator does not behave as expected: >>> myObject=MyClass() >>> 'abc' in myObject.keys() False >>> 'abc' in myObject ArgumentError: Python argument types in MyClass.__getitem__(MyClass, int) did not match the C++ signature: __getitem__(MyClass {lvalue}, std::string) Why is python trying to call __getitem__ with int, when I use the str key? A: It seems that 'abc' in myObject is being evaluated as: for i in myObject: if myObject[i] == 'abc': return true Where i is an integer. Try implementing the __contains__(self, value) magic method.
{ "language": "en", "url": "https://stackoverflow.com/questions/10978814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uncaught TypeError: Cannot read property 'getElementsByClassName' of null | HTML |JS I have an Html page with cards for my memory card game, The user is supposed to match a pair of cards and win an offer mentioned in the card. The offers are for an online grocery shopping application. I get the following error when I flip the card. <div class="deck" id="iPad_Card_layout"> <img id="shelfs" src="shelfs.png" srcset="shelfs.png 1x, shelfs@2x.png 2x"> <div id="Repeat_Grid_5"> <div id="Repeat_Grid_5_0" class="offers"> <!--onclick="application.goToTargetView(event)"--> <div id="card" class="card" data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img class="match-value" id="softdrinks" src="softdrinks.png" srcset="softdrinks.png 1x, softdrinks@2x.png 2x"> <div id="ID25__OFF_on__Soft_Drinks"> <span>25 % OFF on <br/>Soft Drinks</span> </div> </div> </div> </div> <div id="Repeat_Grid_5_1" class="offers"> <div id="card" class="card "data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="vegetables" class="match-value" src="vegetables.png" srcset="vegetables.png 1x, vegetables@2x.png 2x"> <div id="ID10__OFF_on__fruits_veg"> <span>10 % OFF on <br/>Fruits <br>&<br> Vegetables</span> </div> </div> </div> </div> <div id="Repeat_Grid_5_2" class="offers"> <div id="card" class="card" data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="softdrinks" class="match-value" src="softdrinks.png" srcset="softdrinks.png 1x, softdrinks@2x.png 2x"> <div id="ID25__OFF_on__Soft_Drinks"> <span>25 % OFF on <br/>Soft Drinks</span> </div> </div> </div> </div> <div id="Repeat_Grid_5_3" class="offers"> <div id="card" class="card " data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="vegetables" class="match-value" src="vegetables.png" srcset="vegetables.png 1x, vegetables@2x.png 2x"> <div id="ID10__OFF_on__fruits_veg"> <span>10 % OFF on <br/>Fruits <br>&<br> Vegetables</span> </div> </div> </div> </div> <div id="Repeat_Grid_5_4" class="offers"> <div id="card" class="card " data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="dairy_items" class="match-value" src="dairy_items.png" srcset="dairy_items.png 1x, dairy_items@2x.png 2x"> <div id="ID15__OFF_on__Dairy_items"> <span>15 % OFF on <br/>Dairy Products</span> </div> </div> </div> </div> <div id="Repeat_Grid_5_5" class="offers"> <div id="card" class="card " data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="dairy_items" class="match-value" src="dairy_items.png" srcset="dairy_items.png 1x, dairy_items@2x.png 2x"> <div id="ID15__OFF_on__Dairy_items"> <span>15 % OFF on <br/>Dairy Products</span> </div> </div> </div> </div> <div id="Repeat_Grid_5_6" class="offers"> <div id="card" class="card " data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="pringles_offer" class="match-value" src="pringles_offer.png" srcset="pringles_offer.png 1x, pringles_offer@2x.png 2x"> <div id="IDBuy_one_get_free"> <span>Buy any can of <br/>Pringles and get <br>another for <b>FREE!</b></span> </div> </div> </div> </div> <div id="Repeat_Grid_5_7" class="offers"> <div id="card" class="card " data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="pringles_offer" class="match-value" src="pringles_offer.png" srcset="pringles_offer.png 1x, pringles_offer@2x.png 2x"> <div id="IDBuy_one_get_free"> <span>Buy any can of <br/>Pringles and get <br>another for <b>FREE!</b></span> </div> </div> </div> </div> <div id="Repeat_Grid_5_8" class="offers"> <div id="card" class="card " data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="oreo" class="match-value" src="oreo_offer.png" srcset="oreo_offer.png 1x, oreo_offer@2x.png 2x"> <div id="IDOreo_offer"> <span>Oreo Party Pack<br/>for only <br/>Rs.1500.00</span> </div> </div> </div> </div> <div id="Repeat_Grid_5_9" class="offers"> <div id="card" class="card " data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="oreo" class="match-value" src="oreo_offer.png" srcset="oreo_offer.png 1x, oreo_offer@2x.png 2x"> <div id="IDOreo_offer"> <span>Oreo Party Pack<br/>for only <br/>Rs.1500.00</span> </div> </div> </div> </div> <div id="Repeat_Grid_5_10" class="offers"> <div id="card" class="card " data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="dilmah" class="match-value" src="dilmah_offer.png" srcset="dilmah_offer.png 1x, dilmah_offer@2x.png 2x"> <div id="IDdilamah_offer"> <span>Get a Free Pack <br>of Dilmah tea <br>of your choice.</span> </div> </div> </div> </div> <div id="Repeat_Grid_5_11" class="offers"> <div id="card" class="card " data-framework="matchcard"> <div class="card-back card-face"> <svg class="Rectangle_13"> <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172"> </rect> </svg> <svg class="Rectangle_1"> <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64"> </rect> </svg> <div id="logo" class="logo"> <img id="shopping-cart" src="shopping-cart.png" srcset="shopping-cart.png 1x, shopping-cart@2x.png 2x"> <div id="Joeys"> <span>Joey’s</span> </div> </div> </div> <div id="win_card" class=" card-front card-face"> <svg class="Rectangle_31"> <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171"> </rect> </svg> <img id="dilmah" class="match-value" src="dilmah_offer.png" srcset="dilmah_offer.png 1x, dilmah_offer@2x.png 2x"> <div id="IDdilamah_offer"> <span>Get a Free Pack <br>of Dilmah tea <br>of your choice.</span> </div> </div> </div> </div> </div> and the script to flip the cards and see if they are matched is in the script.js file class AudioController{ constructor() { this.flipSound = new Audio('Assets/audio/flip.wav'); this.matchSound = new Audio('Assets/audio/match.wav'); } flip(){ this.flipSound.play(); } match(){ this.matchSound.play(); } } let hasFlippedCard = false; let firstCard, secondCard; class MixORMatch{ constructor(totalChances,cards) { this.cardsArray = cards; this.totalChances = totalChances; this.chancesRemaining = totalChances; this.chances = document.getElementById('chances-remaining'); this.audioController = new AudioController(); //shuffle cards this.shuffleCards(); //start game this.cardToCheck = null; this.totalClicks = 0; this.chancesRemaining = this.totalChances; this.matchedCards = []; } startGame(){ this.cardToCheck = null; this.totalClicks = 0; this.chancesRemaining = this.totalChances; this.matchedCards = []; } flipCard(card) { if(this.canFlipCard(card)){ this.audioController.flip(); this.totalClicks++; card.classList.add('visible'); //first click hasFlippedCard = true; firstCard = this; if (this.canFlipCard(card)){ this.checkForCardMatch(card); }else{ this.cardToCheck = card; } }else{ //second click hasFlippedCard = false; secondCard = this; console.log("flipped") } } hideCards() { this.cardsArray.forEach(card=> { card.classList.remove('visible'); card.classList.remove('matched'); }); } checkForCardMatch(card) { if (this.getCardType(card)===this.getCardType(this.cardToCheck)){ this.cardMatch(card,this.cardToCheck); }else{ this.cardMisMatch(card,this.cardToCheck); } this.cardToCheck = null; } cardMatch(card1,card2){ this.matchedCards.push(card1); this.matchedCards.push(card2); card1.classList.add('matched'); card2.classList.add('matched'); this.audioController.match(); if(this.matchedCards.length === this.cardsArray.length){ console.log("win"); } } cardMisMatch(card1,card2){ setTimeout(()=>{ card1.classList.remove('visible'); card2.classList.remove('visible'); },1000); } shuffleCards(cardsArray){ let cardscount = cardsArray,length; for(let i =cardscount; i>0; i--){ let randIndex = Math.floor(Math.random() * (i+1)); cardsArray[randIndex].style.order = i; cardsArray[i].style.order = randIndex; } } getCardType(card){ return card.getElementsByClassName('match-value')[0].src; } canFlipCard(card){ return true;//(!this.busy && !this.matchedCards.includes(card) && card!== this.cardToCheck); } } function ready(){ let cardDeck = Array.from(document.getElementsByClassName('deck')); let cards = Array.from(document.getElementsByClassName('card')); let game = new MixORMatch(3,cards); /* overlays.forEach(overlay => { overlay.addEventListener('click',()=>{ overlay.classList.remove('visible'); //game.startGame(); }); });*/ cards.forEach(card =>{ card.addEventListener('click',()=>{ //flipping card game game.startGame(); game.flipCard(card); }); }); } if(document.readyState === 'loading'){ document.addEventListener('DOMContentLoaded',ready); }else{ ready(); } I'm not sure why I'm getting this error I have defined the cards to match class as "match-value" which is the image, I the get image src and check whether it matches the one the card user has flipped earlier. But when I flip both cards I get the above mentioned error. In the script in "getCardType". Uncaught TypeError: Cannot read property 'getElementsByClassName' of null A: The issue is in your getCardType() function. You wrote: getCardType(card) { return card.getElementsByClassName('match-value')[0].src; } It should be: getCardType(card){ return document.getElementsByClassName('match-value')[0].src; // ^--- you wrote 'card' here }
{ "language": "en", "url": "https://stackoverflow.com/questions/65731615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set the value of the SelectedItem property in devexpress combobox BarItem? It is example Combobox in which everything is working good and selected value varies depending on changes CurrentPlanSet. <dxe:ComboBoxEdit ItemsSource="{Binding PlanSets, Mode=TwoWay}" DisplayMember="Name" ValueMember="Name" SelectedItem="{Binding CurrentPlanSet, Mode=TwoWay}" /> In this example the selected value does not change depending on CurrentPlanSet changes. <dxb:BarEditItem Content="Plan Sets" EditWidth="350"> <dxb:BarEditItem.EditStyle> <Style TargetType="{x:Type dxe:ComboBoxEdit}"> <Setter Property="SelectedIndex" Value="{Binding CurrentPlanSet, Mode=TwoWay}"/> </Style> </dxb:BarEditItem.EditStyle> <dxb:BarEditItem.EditSettings > <dxe:ComboBoxEditSettings ItemsSource="{Binding PlanSets, Mode=TwoWay}" ValueMember="Id" DisplayMember="Name" /> </dxb:BarEditItem.EditSettings> </dxb:BarEditItem> How to correctly set the value of the SelectedItem property in second code example? A: SelectedIndex is not the same as SelectedItem. This is the same as with the default WPF Controls. SelectedIndex is the Index of the CollectionItem, you have selected/set selected (Integer). The SelectedItem is the Item Object itself. Example: Lets take this Collection: new ObservableCollection<string>(){ "String1", "String2", String3"} If the SelectedItem is/should be String1 the SelectedIndex is 0. So just replace <Setter Property="SelectedIndex" Value="{Binding CurrentPlanSet, Mode=TwoWay}"/> with <Setter Property="SelectedItem" Value="{Binding CurrentPlanSet, Mode=TwoWay}"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/39016433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Coroutines: Can't return value after finish work In my android app I need after executed some long network operation to return result (e.g. after 10 seconds) here snippet: import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch GlobalScope.launch(Dispatchers.Main) { lateinit var response: Response<Void> response = executeOperations.await() return response } but I get compile error in this line: return response Error message: 'return' is not allowed here A: It doesn't work like that. Your return is not allowed there because you are inside a coroutine context on those { } But actually the best way to do it is to create some method and handle that response instead of returning it. On your case I'm a little confused: Transform: GlobalScope.launch(Dispatchers.Main) { lateinit var response: Response<Void> response = executeOperations.await() return response } Into: GlobalScope.launch(Dispatchers.IO) { lateinit var response: Response<Void> response = executeOperations.await() withContext(Dispatchers.Main){ handleResponse(response) } } Plus, your heavy work musn't happen in the Dispatchers.Main but in Dispatchers.IO
{ "language": "en", "url": "https://stackoverflow.com/questions/56564066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I do a Quicksearch or autocomplete on a selectbox populated from a database? I have a select box populated a from a database and would like to do a quicksearch or a autocomplete to search the elements inside the select box. Below is my code: <? print("<table>"); print("<tr>"); print("<td>"); //print("<div id='searchable-form' >"); // print("<div id='searchable'>Search: <input type='text' id='searchFILE' size='33' autocomplete='off' /></div>"); print("<select name='lktyp' id='lktypSearch' size='10' >"); //Create new SQL object $db = new NSC_SQL($db2config); $db->from($bllcust1,"BCUST#,BNAME"); $db->order("BCUST#"); $db->select(); $results = $db->fetchAssoc(); $db->dspSQL(); foreach($results as $row) { $bcust = trim($row['BCUST#']); $bname = trim($row['BNAME']); print("<option value='$bcust'>$bcust ~ $bname</option>"); } print("</select>"); print("</div>"); print("</td>"); print("</tr>"); print("<tr>"); print("<td colspan='2' align='center'>"); //print("<input type='submit' name='search' value='Search'>"); print("<input type='button' value='Select' onclick='lkp();'>"); print("<input type='button' name='cancel' value='Cancel' onClick='parent.$.fancybox.close();'>"); print("</td>"); print("</tr>"); print("</table>"); ?> A: The simplest way would be to implement Jquery autocomplete. I won't do the code for you but if you find it difficult create a new question posting some of the code you tried and someone will help. A: Two nice alternatives to jQuery autocomplete which was already mentioned are Chosen and Select2. Both of these require jQuery or another supported JS framework. jQuery autocomplete and Select2 have great support for remote datasets.
{ "language": "en", "url": "https://stackoverflow.com/questions/13140803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to export summary statistics of a regression from R studio to Excel I have ran a lm function and produced summary results which I wish to export onto a excel document. Is there a specific package/code that allows me to do this? If so which is best for report presenting? A: Let's assume we have model called "mod" mod <- lm(v1 ~ v2, data= df) You can use "broom" function. library(broom) #create dataframes with results res_mod <- as.data.frame(tidy(mod)) res_mod2 <- as.data.frame(glance(mod)) #then export as two csvs write.csv(res_mod, "res_mod.csv") write.csv(res_mod2, "res_mod2.csv")
{ "language": "en", "url": "https://stackoverflow.com/questions/69714490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Heroku Dataclip, How to export date column into XLS When a column contains a Date field, the dataclip displays it. When the "Export/Share" link is clicked and XLS selected, the resulting Date column is treated like a TEXT column in XLS. Changing the Format in XLS does not seem to have an effect on it. Is there a proper format for export that will make it into a Date cell? I have tried 'MM-DD-YYY', 'MM/DD/YYY' and left it as default display (which puts the date and time in the column). None of these are "dates" in XLS. Thanks A: I have done some tests and I think dates are exported as YYYY-MM-DD. I really don't have Excel installed on this computer right now, but I downloaded an xls file from dataclips and imported it on Googlesheets. Dates were correct without any conversion needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/48591034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WordPress: External call to wp-load.php causes CPU and memory spikes One of my websites on my server is causing big CPU and memory spikes. I've been looking for the cause, and I believe that I've found it. I've been digging in the access logs and every time a peak occurs, there is an external call to wp-load.php. This call looks like this (I've changed a few values): 52.56.220.94 - - [16/Oct/2018:12:57:20 +0200] "POST /wp-load.php?pubkey=c924c49878aec6f8295874888c0d14c1&bvTime=1539687440&bvVersion=0.1&bvMethod=getdata&sha1=true&sig=6d3a8735567bd7baa7e5e12af885afab0d6a399d HTTP/1.0" 200 4809 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" The calls come from a limited range of IP-addresses: 52.56.220.94 54.179.150.144 45.77.97.238 Does anyone recognize this and/or does anyone know a way to track down to which piece of software this call belongs to? Any help is highly appreciated. A: You should add the following to your .htaccess file: <Files "wp-load.php"> Order Deny,Allow Deny from all Allow from localhost Allow from 127.0.0.1 </Files> I can't think of a reason to bootstrap WordPress from an external server ....
{ "language": "en", "url": "https://stackoverflow.com/questions/52849035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: count in div after drop event I have 5 pieces of a image in a div sortable1 which i have to drag and drop in another div sortable2to complete the image. After the image is dropped in another container it will stick to the previous image present in this container.http://jsfiddle.net/binit/JnYB9/ After every drop event i want to check whether all the 5 pieces are collected in 2nd div and if it is yes then change button text. Something like this. if $('#sortable2').find('img').length == 5: document.getElementById('btn-start').text = "end"; But i don't know where to use this logic in my code or what should be the syntax My code: javascript $(function() { $( "#sortable1" ).sortable({ connectWith: "div" }); $( "#sortable2" ).sortable({ connectWith: "div", change: function( event, ui ) { var theID = ui.item.attr('id'); ui.item.addClass(theID + '-style'); } }); }); HTML <div id="sortable1" class="well span10"> <img id="north-img" src="{% static 'images/demo/north.png' %}" > <img id="south-img" src="{% static 'images/demo/south.png' %}" > <img id="east-img" src="{% static 'images/demo/east.png' %}" > <img id="west-img" src="{% static 'images/demo/west.png' %}" > <img id="center-img" src="{% static 'images/demo/center.png' %}" > </div> <div id="sortable2" class="well span7" style="height:800px"> <a id="btn-start" href="/dashboard/save/" class="btn btn-primary btn-embossed">Start</a> </div> A: Use stop function of sortable evry time you sort the element from div with id sortable1. Working Demo stop: function( event, ui ) { if($('#sortable2').find('img').length==5) $('#btn-start').html("end"); } A: You can write a callback function on the sortable method like the following: $( "#sortable1" ).sortable({ connectWith: "div", stop: function() { // your logic goes here } }); You can also use the start callback.
{ "language": "en", "url": "https://stackoverflow.com/questions/21377271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Functions work even when headers have not been included - Visual Studio I routinely notice while working in Visual C++ that some functions work even when their headers have not been included. For example, tolower() works even when ctype.h is not included. This behaviour causes problems for me when I participate in online programming competitions, the program works fine and dandy when I run it on my computer but on submission, gives a function not defined error. Is there any way to stop this behaviour? A: Possible explanations: * *You have your warning level turned right down. *You're using precompiled headers that are including the right files. A: The declaration of your tolower() is in fact included. It could be so in one of the following ways: * *<cctype> or <ctype.h> is included in one of the headers (even standard headers) that you have included. The standard does not forbid standard headers to include other standard headers *one of the headers you have included has the declaration of that funciton. For example, <algorithm> could have int tolower(int); somewhere in its code. You cannot forbid this behavior. What you can do is learn where the function has to be defined/declared and never rely on inclusion of that header by other headers. You know where tolower is declared, so do include <cctype> every time you use this function.
{ "language": "en", "url": "https://stackoverflow.com/questions/15659302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WPF control similar to ObjectListView I'm writing an application using WPF, and I need to make something that looks like this (see image): What control should I use for this? A: If you don’t need the groupings (the “Hire as chef” and “Seek dinner invitation” headings), then DataGrid should get you close. You can bind its ItemsSource to your collection of items, and define custom columns bound to your items’ properties. For example, you can use a DataGridTextColumn for “Occupation”, DataGridCheckBoxColumn for “Tells Jokes?”, and DataGridTemplateColumn for more complex properties which require a custom DataTemplate to visualize, such as the main “Person” column or “Cooking skill”. Edi: It appears that the DataGrid does support grouping as well. A: You should go for ListView http://msdn.microsoft.com/en-us/library/ms754027(v=vs.90).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/10057929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: React Hook "React.useEffect" is called in function "selectmenu" which is neither a React function component or a custom React Hook function Problem: React Hook "React.useEffect" is called in function "selectmenu" which is neither a React function component or a custom React Hook function. Target: I want to Mount Component('component DidMount/WillUnmount) (using useEffect()) only when I click on a button, rather than, mounting while the file (or whole Component) is being loaded. Actual Goal: I want to select(or highlight) a file (custom ) on click. But when the user clicks outside the dimensions of the file (), then the selected file should get deselected (remove highlight). export default function Academics() { let [ ismenuselected, setmenuselection] = useState(0) const selectmenu = () => { console.log("Menu to Select") React.useEffect(() => { console.log('Component DidMount/WillUnmount') return () => { console.log('Component Unmounted') } }, [isfolderselected]); } return ( <div onClick={selectmenu}></div> ) } Note: * *I've tried with the UPPER case of SelectFolder #56462812. Error: Invalid hook call. Hooks can only be called inside of the body of a function component. *I want to try something like this. But with a click of a button (useEffect() should invoke onClick event). A: I think I got what you're trying to accomplish. First, you can't define a hook inside a function. What you can do is trigger the effect callback after at least one of its dependencies change. useEffect(() => { // run code whenever deps change }, [deps]) Though for this particular problem (from what I understood from your description), I'd go something like this: export default function Academics() { let [currentOption, setCurrentOption] = useState() function handleSelectOption(i) { return () => setCurrentOption(i) } function clearSelectedOption() { return setCurrentOption() } return (options.map((option, i) => <button onClick={handleSelectOption(i)} className={i === currentOption ? 'option option--highlight' : 'option'} onBlur={clearSelectedOption} ></button> )) }
{ "language": "en", "url": "https://stackoverflow.com/questions/62866063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove UIBarButtonItem from master view controller when detail view controller is visible I am converting my view controllers into a split view controller with a Universal Storyboard to show two views on screen at the same time, which will only appear on iPad - only one will be visible on iPhone. I have a situation where a UIBarButtonItem is only relevant when only one view controllers is on screen. I want this button removed or hidden when both view controllers in the split view controller are visible. I cannot use Size Classes to do this, since the button I want removed is in the master view controller (actually I have button in both the master and detail that should be removed), which won't have a size class of Regular w Regular h. Plus Interface Builder doesn't provide an "Installed" option for UIBarButtonItems, and I cannot check size classes in code because the app will also run on iOS 7. How can I remove/hide a UIBarButtonItem when both the master and detail view controller are on screen? Or I could not add this button in IB, then add it in code when deemed appropriate, but how would I know if both view controllers will be on screen? A: Here's a nice solution that works great for iOS 8 and iOS 7 on iPhone and iPad. You simply detect if there is a split view controller and if so, check if it's collapsed or not. If it's collapsed you know only one view controller is on screen. Knowing that info you can do anything you need to. //remove right bar button item if more than one view controller is on screen if (self.splitViewController) { if ([UISplitViewController instancesRespondToSelector:@selector(isCollapsed)]) { if (!self.splitViewController.collapsed) { self.navigationController.navigationBar.topItem.rightBarButtonItem = nil; } } else { self.navigationController.navigationBar.topItem.rightBarButtonItem = nil; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/25192180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to define a scoped callback function in a C struct? The C struct AvCodecContext in libav (ffmpeg) has a callback function called get_format. I have a class where each instance has its own AvCodecContext instance, so each one will have an specific callback. Is it possible to create different callbacks for each instance? Here's what the callback should look like: enum AVPixelFormat get_hw_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { const enum AVPixelFormat *p; for (p = pix_fmts; *p != -1; p++) { if (*p == hw_pix_fmt) return *p; } fprintf(stderr, "Failed to get HW surface format.\n"); return AV_PIX_FMT_NONE; } each callback should have a different AVPixelFormat hw_pix_fmt. If the project was C++ only, I could use lambda functions, but it's not. Is there a way?
{ "language": "en", "url": "https://stackoverflow.com/questions/57228864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to print value of a Variable using its memory address? Suppose 0xfe2200 is the memory address of a variable var2 and I want to display the value stored in it, E.g cout<< "Value stored in the given address is : " << 0xfe2200 << " "; I tried following but all in vain cout << "Value is : " << *0xfee2200 << " ; cout << "Value is : " << &0xfee200 << " ; A: Assuming the address points to int, you may do: cout << "Value is : " << *reinterpret_cast<int*>(0xfee2200); as literal 0xfee2200 is an interger type whereas you expected a pointer. A: You have to decide as what type of data you want to interpret the memory content and cast it accordingly: const char* tmp = "foofoo"; // Valid ptr for this example const void* address = tmp; // Set to your address const int* i = reinterpret_cast<const int*>(address); const unsigned short* us = reinterpret_cast<const unsigned short*>(address); const char* c = reinterpret_cast<const char*>(address); std::cout << "i: " << (*i) << "\nus: " << (*us) << "\nc: " << (*c); Output: i: 1718579046 us: 28518 c: f
{ "language": "en", "url": "https://stackoverflow.com/questions/31580616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Publish applet with maker webhook I want to publish my applet with a maker webhook to my raspberry pi. For some reason it doesn't allow me to publish the app when I use a maker webhook in it.I'm not sure why it doesn't allow me or if it's even possible at all. There isn't any error in the applet either as it works perfectly fine in private mode. I also have seen some applets by other users that use the maker webhooks in their applet. So I think it must be possible. If somebody could answer this question who has published an applet before with webhooks or what I could be doing wrong. Thanks in advance !
{ "language": "en", "url": "https://stackoverflow.com/questions/44330206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: I am getting error as unrecognized rule in this lex program %{ #include<stdio.h> int vowel=0; %} %% [aeiouAEIOU] { vowel++; } %% int main() { char str[200]; gets(str); yylex(); printf("Vowels:",vowel); } A: If that is the way you wrote the program, then the error is correct. In Flex, the action for a rule must start on the same line as the pattern. From the flex manual: 5.2 Format of the Rules Section The rules section of the flex input contains a series of rules of the form: pattern action where the pattern must be unindented and the action must begin on the same line. As written, you have supplied { as a pattern. That's not a valid pattern, and so flex complains.
{ "language": "en", "url": "https://stackoverflow.com/questions/46393181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Registering Entity in Objectify having issue during test cases We have an project developed with Objectify4 and Spring3.1 and deployed and running on GAE and we are using IDE as STS. When I do project build locally using Maven(cmd mvn install) the test cases are failing and throwing the following exception. From the exception I observe it is failing while injecting Class1Service service class in test class Class1UnitTest (this is not only in this test class it is giving same exception in every test class wherever we are injecting any service class that extends AbstractBaseImpl). In the exception stacktrace I see it is pointing to line of registering the Entity class(EntityClassA) in AbstractBaseImpl. In the Entitiy class EntityClassA we have used @Mapify, if I remove the @Mapify annotation in the entity class the test case are running without any bean initialisation issues. I tried building project from STS and also from command still getting the same issue. From the functionality point of view the application is working fine if I skip the testcases while building.Can anyone see similar issue with the entity having @Mapify defined and getting issue while registering in test case. Thanks for your time Here are the details, EntityClassA.java @Entity public class EntityClassA { @Index @Mapify( ChildClassAMapper.class ) private Map<Integer, ChildClassA> intervalToReward = new LinkedHashMap<>(); @Embed public static class ChildClassA extends ClassA { private static final long serialVersionUID = 49769454099624971L; private int …; private long …; public ChildClassA( ) { ….. } } public static class ChildClassAMapperMapper implements Mapper<Integer, ChildClassA> { @Override public Integer getKey( ChildClassA value ) { return value.getInterval(); } } } AbstractBaseImpl.java @Component public abstract class AbstractBaseImpl implements BaseService { static { Line-12 ObjectifyService.register( EntityClassA.class ); } } ChallengeServiceImpl.java @Service @Slf4j public class Class1ServiceImpl extends AbstractBaseImpl implements Class1Service { // method to store data using objectify.. } CoreBaseTest.java @ContextConfiguration( locations = { "classpath*:META-INF/spring/core-applicationContext.xml" } ) @RunWith( SpringJUnit4ClassRunner.class ) public abstract class CoreBaseTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( new LocalDatastoreServiceTestConfig().setApplyAllHighRepJobPolicy(), new LocalBlobstoreServiceTestConfig(), new LocalTaskQueueTestConfig(), new LocalMemcacheServiceTestConfig() ); } Class1UnitTest.java public class Class1UnitTest extends CoreBaseTest { @Resource( name = "class1Service" ) private Class1Service class1Service; //Testcases… } core-applicationContext.xml <bean id="class1Service" class="com.suvs.app.core.spring.services.Class1ServiceImpl" /> Exception TestCrud(test.core.Class1UnitTest') Time elapsed: 0.163 sec <<< ERROR! org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test.core.Class1UnitTest': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'class1Service' defined in URL [file:/Users/suvs/core-app/target/classes/META-INF/spring/core-applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.AssertionError at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:307) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175) at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'class1Service' defined in URL [file:/Users/suvs/core-app/target/classes/META-INF/spring/core-applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.AssertionError at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:443) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:417) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:559) at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:304) ... 32 more Caused by: java.lang.AssertionError at com.googlecode.objectify.impl.translate.CreateContext.enterCollection(CreateContext.java:70) at com.googlecode.objectify.impl.translate.CollectionTranslatorFactory.create(CollectionTranslatorFactory.java:49) at com.googlecode.objectify.impl.translate.TranslatorRegistry.create(TranslatorRegistry.java:90) at com.googlecode.objectify.impl.translate.ClassTranslator.(ClassTranslator.java:52) at com.googlecode.objectify.impl.translate.EmbedClassTranslatorFactory.create(EmbedClassTranslatorFactory.java:43) at com.googlecode.objectify.impl.translate.TranslatorRegistry.create(TranslatorRegistry.java:90) at com.googlecode.objectify.impl.translate.MapifyTranslatorFactory.create(MapifyTranslatorFactory.java:62) at com.googlecode.objectify.impl.translate.TranslatorRegistry.create(TranslatorRegistry.java:90) at com.googlecode.objectify.impl.translate.ClassTranslator.(ClassTranslator.java:52) at com.googlecode.objectify.impl.translate.EntityClassTranslator.(EntityClassTranslator.java:46) at com.googlecode.objectify.impl.Transmog.(Transmog.java:49) at com.googlecode.objectify.impl.ConcreteEntityMetadata.(ConcreteEntityMetadata.java:58) at com.googlecode.objectify.impl.Registrar.register(Registrar.java:74) at com.googlecode.objectify.ObjectifyFactory.register(ObjectifyFactory.java:180) at com.googlecode.objectify.ObjectifyService.register(ObjectifyService.java:62) at com.suvs.app.core.spring.services.AbstractBaseImpl.(AbstractBaseImpl.java:12) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990) ... 45 more A: Does ChildClassA also contain a collection, thus you are trying to nest two embedded collections? It looks like it from that stacktrace. This is not possible in Objectify4. I highly recommend the upgrade to 5.
{ "language": "en", "url": "https://stackoverflow.com/questions/26753094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Segmentation Fault using double pointers I'm getting segmentation fault while handling with double pointer in the below code. I've spent way too much time and couldn't find what the error was. #include<iostream> using namespace std; int main(){ int *p,**pp,n=2; p=new int; pp=&p; for(int i=0;i<n;i++) { cin>>*(*(pp+i))>>*(*(pp+i)+1); } for(int i=0;i<n;i++) { cout<<*(*(pp+i))<<" "<<*(*(pp+i)+1)<<endl; } return 0; } Not sure if this is a noob question. A: Maybe this is what you need: int *p, **pp, n = 2; p = new int[n * 2]; pp = &p; for(int i = 0;i < n;i++) cin >> *(*pp + n*i + i) >> *(*pp + n*i + i + 1); for(int i = 0;i < n;i++) cout << *(*pp + n*i + i) << " " << *(*pp + n*i + i + 1) << endl; delete []p; return 0;
{ "language": "en", "url": "https://stackoverflow.com/questions/53594437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: NSURLConnectionDownloadDelegate methods not getting called when downloading files over 50 MB via cellular Supposing I have a snippet of code like this: [assetDownload downloadWithDelegate:self]; All the three delegate methods are implemented: – connection:didWriteData:totalBytesWritten:expectedTotalBytes: – connectionDidResumeDownloading:totalBytesWritten:expectedTotalBytes: – connectionDidFinishDownloading:destinationURL: And everything works (the delegate methods get called) fine when there is a WI-FI connection for files of any size, and for files under 50 MB when on cellular network. When the file is bigger and the connection is cellularnone of the methods get called. Is this a normal behavior and what should I do to handle it properly?
{ "language": "en", "url": "https://stackoverflow.com/questions/21047794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: peculiar Java 7 Web Start failure I maintain a legacy application that was written with the Java 6 JDK. We deploy it as a stand alone application downloaded from the web as a JNLP. The application talks to a servlet that serves up data from a database, and since the data involved can get lengthy, the JNLP app provides a 'progress meter' to show how much data has transferred and how much is left to go. It was working all just fine - until, apparently, the latest Java 7 update. Now, when the JNLP application is run, during data transfer from the servlet, the progress meter stops working. It appears to get hung, yet data is continuing to be transferred (the servlet part is working just fine). But to our end users, the app appears to fail! I can run the app locally without Webstart, and it works fine. Any idea what the problem could be, and how to fix it?.
{ "language": "en", "url": "https://stackoverflow.com/questions/13143967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python create an arbitrary score based off certain criteria I want to create a formula that will create an arbitrary score based on certain variables. For example, given a dataframe with the following columns: import pandas as pd import numpy as np df = pd.DataFrame({'Name': ['Joe', 'Bob'], 'Score': [0.75, 0.8], 'Length': [10, 20]}) I want to create a new column, Result, based off the following criteria, In this order of importance * *Length closest to 10 has the most weight *The highest score has the most weight *'Bob' has more weight than 'Joe' Some more info: * *Opt. assume that there are more than 2 names, with an option to specify which names are more important than the others *Score is a decimal from 0 to 1 *Length is an int from 1-200 Basically, I am having trouble coming up with a function that captures these desires weights/importances. What would such a function look like? A: You can set up a temporary DataFrame with custom columns to sort and use its index to reorder the original: idx = (df .assign(Length=-df['Length'].sub(10).abs(), Name=pd.Categorical(df['Name'], categories=['Joe', 'Bob'], ordered=True) ) .sort_values(by=['Length', 'Score', 'Name'], ascending=False) .index ) # reorder values based on priority sorted_df = df.loc[idx] Alternative if only some names have a priority: d = {'Bob': 2} # in the assign of the previous code #.assign( Name=df['Name'].map(d).fillna(0) #) If you want to add a rank instead of sorting: df.loc[idx, 'rank'] = range(len(df))
{ "language": "en", "url": "https://stackoverflow.com/questions/73072701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R - How to pass encrypted password in a GET request I am pulling data from a server using this API. In order to get an authToken I need to pass my username and password. The password input description says "Hashed password. May be passed as clear text, or as RSA-encrypted hash (see above for RSA public key)." To encrypt the password I am using the below code. library(openssl) aqKey <- read_pubkey("public_key.pem") user_name <- "UserName" password <- rsa_encrypt(charToRaw(askpass()), aqKey) pw <- rawToChar(password) This gives me a string with a bunch of unusable characters that produce a 400 error when used in the URL. /GetAuthToken?user=USERNAME&encPwd=ˆ Ù\026Õ©1tÐÆ®IßÊ/ÛÅÆwéÙeµèB¾kz–V\t–ü˜ÞO«~=ñcѪÿC'p‰-zòjEü,\r¯eÑ}d‹ã\fÀ\030DR·W\026Â\022‰Å:™¶í©«cózÆlE\032Ï4$é¹Þ,ù«…s\021…–ì\026}h¯~?\nC\021ôj-†\032K}ò\026 If I use base64_encode() or URLencode() on either password or pw I get a 200 status but do not receive a token. This is equivalent to an incorrect password. When I pass the password as plaintext I get a token. My question is, how should I be formatting the password once it has been encrypted so that the server will recognize it as an encrypted password?
{ "language": "en", "url": "https://stackoverflow.com/questions/50144544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "Msiexec REINSTALL=ALL REINSTALLMODE=vamus" is not cleaning old entries I created an installer "test.msi" . It is version-1. test.msi contains 2 components "comp1", "comp2" comp1 contains 2 files "comp1_file1", "comp1_file2" In version 2 of test.msi , --> a new component added "comp3". It contains 1 file "comp3_file1" --> "comp1" component is updated. "comp1_file2" file removed and new file "comp1_file3" added Now it contains 2 files (comp1_file1, comp1_file3) if i upgrade test.msi from version-1 to version-2 using "msiexec /i test.msi REINSTALL=ALL REINSTALLMODE=vamus", in installation folder still i can see version-1 file "comp1_file2". if i downgrade from version-2 to version-1 using "msiexec /i test.msi REINSTALL=ALL REINSTALLMODE=vamus", in installation folder version-2 related files exist (comp3_file1, comp1_file3). How to remove old entries(components/files) at reinstall time? i am using installshield 2008 premier edition. A: Transitive components are the way to go. MS describes them here: http://msdn.microsoft.com/en-us/library/aa372462%28v=vs.85%29.aspx To follow up on what Chris said, playing with the reinstallmode can do some nasty things. This is particularly true if you're including any shared components. You can backlevel components that other applications are depending on, and you can find yourself prompted to stop seemingly unrelated applications based on files in the shared components being in use. It's a really good thing to avoid if you possibly can. A: As Cosmin suggested you cannot remove components during repair, but you can uninstall the previous versions before starting the install process for the new version. One way to go with InstallShiled 2008 is to create a major upgrade that will do this. Video Tutorial. Edit As Christopher said: There are ways to remove components in minor upgrades / repairs. Comment below.
{ "language": "en", "url": "https://stackoverflow.com/questions/4710997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Import big xls file into mysql database I want to import big xlsx ( spreadsheet file ) into mysql database. I did it before by phpmyadmin , but this file is too big ( 205000 rows ). so when I wanna do it by phpmyadmin,it has taken a long time and wasn't done. what is best and fast way to import it to mysql database? A: You can do it using the LOAD DATA command in MySQL: http://blog.tjitjing.com/index.php/2008/02/import-excel-data-into-mysql-in-5-easy.html Save your Excel data as a csv file (In Excel 2007 using Save As) Check the saved file using a text editor such as Notepad to see what it actually looks like, i.e. what delimiter was used etc. Start the MySQL Command Prompt (I usually do this from the MySQL Query Browser – Tools – MySQL Command Line Client to avoid having to enter username and password etc.) Enter this command: LOAD DATA LOCAL INFILE ‘C:\\temp\\yourfile.csv’ INTO TABLE database.table FIELDS TERMINATED BY ‘;’ ENCLOSED BY ‘”‘ LINES TERMINATED BY ‘\r\n’ (field1, field2); [Edit: Make sure to check your single quotes (') and double quotes (") if you copy and paste this code] Done! A: You can try use Navicat MySQL. I've done this with 250MB+ xlsx file and Navicat handle it flawlessly without breaking a sweat. Just make sure your MySQL is configured to be able to receive large amount of data by changing the max_allowed_packet option in your my.ini to a larger amount, say, 128M. A: Toad for MySQL (Freeware) would be another alternative.
{ "language": "en", "url": "https://stackoverflow.com/questions/10283535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to return a collection of strings from C# to C++ via COM interop I hav created a com componet for some Display method in C# it returns a String List as shown below. In v++ i hav used std::lst to catch the return value from Disp() but it gives compiler error that Disp is not a member of class. I i make return type a s void then it works fine. what i can modify so that Disp return a List and in main(c++) i have to use this return value. Public interface ITest { List<string> Disp(); } class TestLib:ITest { List<string> Disp() { List<string> li=new List<string>(); li.Add("stack"); li.Add("over"); li.Add("Flow"); return li; } } compiled and created Test.dll successfully and also test.tlb. Now in main function that is written in c++ #include<list> #import "..\test.tlb" using namespace Test; void main() { HRESULT hr=CoInitialize(null); ITestPtr Ip(__uuidof(TestLib)); std::list<string> li=new std::list<string>(); li=Ip->Disp(); } What's wrong in my code when i try to compile this it shows 'Disp':is not a member of TestLib:ITest how to solve this plz help me ....when i make it return type as void in Class it works fine .what mistake i did???? A: This just isn't going to work, even if you fix the typos. COM interop doesn't have a standard mapping from List<T> to something in COM, and it certainly won't map it to std::list. Generics aren't allowed to appear in COM interfaces. UPDATE I tried using ArrayList as the return type, as that's non-generic I thought maybe the tlb would include type information for it. That didn't work so I tried IList. That didn't work either (the #import statement produced a .tlh file that referred to IList but had not definition for it.) So as a workaround I tried declaring a simple list interface. The code ends up like this: [Guid("7366fe1c-d84f-4241-b27d-8b1b6072af92")] public interface IStringCollection { int Count { get; } string Get(int index); } [Guid("8e8df55f-a90c-4a07-bee5-575104105e1d")] public interface IMyThing { IStringCollection GetListOfStrings(); } public class StringCollection : List<string>, IStringCollection { public string Get(int index) { return this[index]; } } public class Class1 : IMyThing { public IStringCollection GetListOfStrings() { return new StringCollection { "Hello", "World" }; } } So I have my own (very simplistic) string collection interface. Note that my StringCollection class doesn't have to define the Count property because it inherits a perfectly good on from List<string>. Then I have this on the C++ side: #include "stdafx.h" #import "..\ClassLibrary5.tlb" #include <vector> #include <string> using namespace ClassLibrary5; int _tmain(int argc, _TCHAR* argv[]) { CoInitialize(0); IMyThingPtr thing(__uuidof(Class1)); std::vector<std::string> vectorOfStrings; IStringCollectionPtr strings(thing->GetListOfStrings()); for (int n = 0; n < strings->GetCount(); n++) { const char *pStr = strings->Get(n); vectorOfStrings.push_back(pStr); } return 0; } I have to manually copy the contents of the string collection a proper C++ standard container, but it works. There may be a way to get proper type info from the standard collection classes, so you don't have to make your own collection interfaces, but if not, this should serve okay. Alternatively, have you looked at C++/CLI? That would work pretty seamlessly, although it still wouldn't convert CLR collections to std containers automatically. A: There look like there are several typos. In the C# you declare a class called TestLib, but are trying to construct a TestCls. In addition, neither the class not the method are public (which should be a compile error at least on Disp, since the interface has to be implemented publicly). A: Guess: Disp() is not declared public
{ "language": "en", "url": "https://stackoverflow.com/questions/1032060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: If, g , h are functions such that f(n) = O(g(n)) and g(n) = O(h(n)) prove f(n) = O(h(n)) I'm currently taking my first discrete math class and I'm having a bit of trouble. This is my first encounter with big Oh and I'm having a bit of trouble understanding this particular problem. I understand proofing that n <= O(n) because I can mathematically prove that there is such constant that will hold true for all values of n >= k if f, g , h are functions such that f(n) = O(g(n)) and g(n) = O(h(n)) use the definition of big oh given in class to prove that f(n) = O(h(n)) My answer was |f(n)| <= U1|g(n)| for all n >= k |g(n)| <= U2|h(n)| for all n >= j thus |f(n)| <= U3|h(n)| for all n >= i Hence f(x) = O(h(x)) I tried to see the professor in her office hours but she said my proofing was incorrect, but would't really say why. I've spent so long on this I don't even know what to do. Any help would be great... Okay! Let me try this again! |f(n)| <= U1|g(n)| for all n >= k |g(n)| <= U2|h(n)| for all n >= j let i equal the largest of either k ∨ j. let U3 equal U1 * U2 f(n) <= U3|h(n)| for all n >= i thus f(n) = O(h(n)) Better? A: Using Big O definition: f = O(g) iff exist c, n0 > 0 such that forall n >= n0 then 0 <= f(n) <= cg(n) g = O(h) iff exist k, n1 > 0 such that forall n >= n1 then 0 <= g(n) <= kh(n) Now take the last unequality and divide all members by c: 0 <= f(n)/c <= g(n) and we can substitute g(n) in the second inequality: 0 <= f(n)/c <= kh(n). Finally multiply all members by c and you obtain 0 <= f(n) <= kch(n) that is the definition of f = O(h): f = O(h) iff exist j, n2 > 0 such that forall n >= n2 then 0 <= f(n) <= jh(n) In our case it is: n2 = max(n0, n1) and j = ck. A: You can use limits interpretation of Bachmann–Landau notations. Then you can use the following reasoning: A: If you substitute the second inequalty into the first you should end up with U3 = U1 * U2, but what you called "i" is the crucial point. I think (but my theoretic days are far away in the past, so I could be wrong) that you could end up elegantly with a n >= argmax{ k, j }.
{ "language": "en", "url": "https://stackoverflow.com/questions/14426989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: .htaccess 301 redirect only work for 1 new link I have .htaccess file with redirect 301 on it and placed right under the rewriteengine <IfModule mod_rewrite.c> RewriteEngine On #now this is the redirect Redirect 301 /blog.php?slug=konsolidasi-tanah-frequently-asked-questions https://jpi.or.id/blog/2021/02/11/pengertian-konsolidasi-tanah Redirect 301 /blog/2021/02/11/konsolidasi-tanah-frequently-asked-questions https://jpi.or.id/blog/2021/02/11/pengertian-konsolidasi-tanah </IfModule> only 2nd redirect works, the one with the get method are not redirected, am i doing wrong? EDITED : this is my entire mod rewrite : RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*)$ $1.php RewriteRule ^index\.php$ / [R=301,L] RewriteRule ^(.*)/index\.php$ /$1/ [R=301,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [L] # Permanent URL redirect Redirect 301 /blog.php?slug=konsolidasi-tanah-frequently-asked-questions https://jpi.or.id/blog/2021/02/11/pengertian-konsolidasi-tanah # Permanent URL redirect Redirect 301 /blog/2021/02/11/konsolidasi-tanah-frequently-asked-questions https://jpi.or.id/blog/2021/02/11/pengertian-konsolidasi-tanah Redirect 301 /blog.php?slug=konsolidasi-tanah-frequently-asked-questions /blog/2021/02/11/pengertian-konsolidasi-tanah RewriteRule ^blog/2021/02/11/pengertian-konsolidasi-tanah /blog.php?slug=konsolidasi-tanah-frequently-asked-questions A: It is usually not a good idea to mix RewriteRule and Redirect 301 directives. They can conflict with each other in unexpected ways. You depend of RewriteRule so you should implement your redirects with more of them. Redirect 301 can't redirect based on query strings (?...) in the URL, so you need to implement RewriteRules for that redirect anyway. When you have rules for redirecting specific URLs, they should go at the top of the .htaccess file so that they take precedence over the other more general rules. I would recommend disabling the directory index because I fear it would conflict with your RewriteRule ^index\.php$ / [R=301,L] rule. I don't see RewriteEngine On in your .htaccess file, despite that your snippet you posted to start with has it. Try this as your .htaccess: # Disable index.html, index.php default functionality DirectoryIndex disabled RewriteEngine On # Permanent URL redirect RewriteCond %{QUERY_STRING} ^slug=konsolidasi-tanah-frequently-asked-questions$ RewriteRule ^blog\.php$ https://jpi.or.id/blog/2021/02/11/pengertian-konsolidasi-tanah [R=301,L] RewriteRule ^blog/2021/02/11/konsolidasi-tanah-frequently-asked-questions$ https://jpi.or.id/blog/2021/02/11/pengertian-konsolidasi-tanah [R=301,L] # Forward URLs without .php extension to existing PHP file RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*)$ $1.php # Redirect index.php URLs to the directory RewriteRule ^index\.php$ / [R=301,L] RewriteRule ^(.*)/index\.php$ /$1/ [R=301,L] # Use index.php as a front controller RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [L]
{ "language": "en", "url": "https://stackoverflow.com/questions/71411212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XAML designer: 'FileNotFoundException' I'm working on an extensible WPF application using C#. For the extensibility, I use MEF (Managed Extensibility Framework). But since today, the XAML designer doesn't work for the MainWindow.xaml anymore. It throws a FileNotFoundException with this message: Could not load file or assembly 'System.ComponentModel.Composition.CodePlex, Version=4.1.2.0, Culture=neutral, PublicKeyToken=13e5ffd4e05db186' or one of its dependencies. The specified module could not be found. But the strange thing is, that the file does exist. I copied it into the bin\debug folder. And added it to the references (Yes, I tried to re-add it, but that didn't help). Yet another strange thing is, that it seems like it is caused by the XAML code, because the designer works for all other windows. I've already tried to mark some suspicious parts (ItemControls that list plugins) as comment (I don't want to remove them). Well, it worked once, but then I built the solution and the designer crashed (out of memory). Since then I have the same problem again. Edit: I found out, that the XAML wasn't the problem. When I remove the reference to System.ComponentModel.Composition.CodePlex and every code that uses this library, the problem is fixed - until I restart Visual Studio or the Designer. A: Try removing items/controls from the xaml until the issue no longer manifests itself. By doing that you can divine the origination of the issue and possibly resolve or at least provide StackOverflow with a specific situation which we can help resolve. A: I've found two buttons in the <Window.Style> tag that (seem to) cause the designer to crash: <Button Command="{x:Static local:MainWindow.Maximize}" Loaded="MaximizeLoaded" Content="&#xf065;" ToolTip="{lex:Loc Bukkit Manager:UI:maximize}" Style="{StaticResource CaptionButton}" shell:WindowChrome.IsHitTestVisibleInChrome="True"/> <Button Command="{x:Static local:MainWindow.Minimize}" Content="&#xf068;" ToolTip="{lex:Loc Bukkit Manager:UI:minimize}" Style="{StaticResource CaptionButton}" shell:WindowChrome.IsHitTestVisibleInChrome="True"/> But a strange thing is, that every control's Command= attribute is marked as error. Although the commands (and their bindings) exist. On mouse over it shows a tooltip saying Could not load file or assembly 'System.ComponentModel.Composition.CodePlex, Version=4.1.2.0, Culture=neutral, PublicKeyToken=13e5ffd4e05db186' or one of its dependencies. The specified module could not be found. That only happens, when the designer is running, but I can still debug (and run) the application. When I terminate the designer procces, the errors are gone. A: I've noticed that the System.ComponentModel.Composition.CodePlex.dll in the bin\debug folder has a different version than the one that Visual Studio is searching for. VS tries to find a file with version 4.1.2.0 but the one in the directory is 1.1.0.0. A: Open the file System.ComponentModel.Composition.CodePlex.dll from the referenced location in Visual Studio as file type 'Resource Files'. Change the FILEVERSION and PRODUCTVERSION to 4,1,2,0 and rebuild the projects. This is a workaround to get the designer working. The clean fix is to request the CodePlex dll to have proper product & file version for these assemblies. A: You can simply remove this error by setting CopyLocal=true for the mentioned dll. This way it will not conflict between the existing installed one and the newly added one from the Nuget Package.
{ "language": "en", "url": "https://stackoverflow.com/questions/22258937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: React with Webpack-huge bundle sizes I've got an app which is pretty basic, but the bundle size is 6.7MB in dev and 1.8MB in production. The lion's share (94%) is Node Modules. Is there a straightforward way to only bundle those modules which are required? I tried Webpack Node Externals, but that broke everything-the app didn't know what 'require' meant anymore, for instance. I'm using Webpack 3.8. Here are my config files: webpack.config: const loaders = require('loaders'); const CompressionPlugin = require('compression-webpack-plugin'); var Visualizer = require('webpack-visualizer-plugin'); var nodeExternals = require('webpack-node-externals'); module.exports = { entry: ['./src/index.js'], output: { path: __dirname, publicPath: '/', filename: 'bundle.js', sourceMapFilename: 'bundle.js.map' }, module: { loaders: [ loaders.css, loaders.url, { exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['react', 'es2015', 'stage-1'] } } ] }, resolve: { extensions: ['*', '.js', '.jsx'] }, plugins: [ new CompressionPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/, threshold: 10240, minRatio: 0.8 }), new Visualizer() ], devServer: { historyApiFallback: true, contentBase: './' } }; webpack.production.config: // Webpack config for creating the production bundle. var path = require('path'); var webpack = require('webpack'); var writeStats = require('./util/writeStats'); var strip = require('strip-loader'); const CompressionPlugin = require('compression-webpack-plugin'); var nodeExternals = require('webpack-node-externals'); var assetsPath = path.join(__dirname, '../static/dist'); module.exports = { context: path.resolve(__dirname, '..'), entry: { main: './src/client.js' }, output: { path: assetsPath, filename: '[name]-[chunkhash].js', chunkFilename: '[name]-[chunkhash].js', publicPath: '/dist/' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: [strip.loader('debug'), 'babel?stage=0&optional=runtime'] } ] }, progress: true, resolve: { modulesDirectories: ['src', 'node_modules'], extensions: ['*', '.json', '.js'] }, plugins: [ // new webpack.DefinePlugin({__CLIENT__: true, __SERVER__: false}), // ignore dev config new webpack.IgnorePlugin(/\.\/dev/, /\/config$/), // set global vars new webpack.DefinePlugin({ 'process.env': { // Mainly used to require CSS files with webpack, which can happen only on browser // Used as `if (process.env.BROWSER)...` BROWSER: JSON.stringify(true), // Useful to reduce the size of client-side libraries, e.g. react NODE_ENV: JSON.stringify('production') } }), // optimizations new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new CompressionPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/, threshold: 10240, minRatio: 0.8 }), // stats function() { this.plugin('done', writeStats); } ] };
{ "language": "en", "url": "https://stackoverflow.com/questions/48361250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compiling mod_auth_token for windows I have access to both Windows machine ( Win 7 ) & Linux ( Ubuntu 10.04 ), I would like to know how can I compile mod_auth_token on my Linux machine and get it working on Windows. If I take the .so file from the Linux machine will it work on windows?? Can any one help me out, If you can compile it for me & put it somewhere for download or just let me know a way that will work (I don't have Visual Studio nor any compile related programs on windows that's why I need to do it on Linux then move it over to windows and just link it in the config file). Version I need help on compiling mod_auth_token-1.0.6-beta Location: http://code.google.com/p/mod-auth-token/ A: The Windows version has been released by ApacheHaus recently. They have this module for both Apache 2.2 and 2.4 (x86 and x64 both). here is the link https://www.apachehaus.net/modules/mod_auth_token/
{ "language": "en", "url": "https://stackoverflow.com/questions/10499701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WP REST API v2 give a mixed up output for custom taxonomies on custom posts I used a theme (with included plugins) that created custom taxonomies and post_types on WP. Both are exposed on REST endpoints with show_in_rest => true. All were doing great until I realized the output of custom taxonomies are mixed up. Example post_type = pokemon taxonomy = pokemon_category request: /wp-json/wp/v2/pokemon output: [ { "id": 1, "slug": "ditto", "pokemon_category": [] }, { "id": 2, "slug": "snorlax", "pokemon_category": [ 1, 1 ] } ] expected output: [ { "id": 1, "slug": "ditto", "pokemon_category": [1] }, { "id": 2, "slug": "snorlax", "pokemon_category": [1] } ] I saw nothing odds on the source code and it seems already followed a handbook from wordpress. Update: It seems it's the problem of WPML. The problem is shown when I set the post type as translatable with: "Translatable: only show translated items". The issue disappears when I choose "Translatable: use translation if available or fallback to default language" A: what is the expected result? mixed up = the “pokemon_category” array?
{ "language": "en", "url": "https://stackoverflow.com/questions/72585390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disk filter driver on Windows Phone 8 We are using Disk filter driver developed for Windows 8 OS. Please let me know whether it is possible to use same driver on Windows 8 Phone OS. Please let me know the forum, if this forum is not the right place to discuss Windows 8 Phone drivers. Thanks, Raphel A: No you can not use the same driver on windows phone (windows 8). you have to develop the same driver from scratch by following Windows CE and Mobile Driver development for windows phone 7 that might work on windows 8.but ddk is not open for all better ask msdn support for the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/16521265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List Comprehensions in Python : efficient selection in a list Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a distance to an other element). I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code result = [ ( myFunction(C), C) for C in originalList if myFunction(C) < limit ] But myFunction is a very time-consuming function, and the originalList quite big. So doing like that, myFunction will be call twice for every selected element. So, is there a way to avoid this ?? I have two other possibilities, but they are not so good: * *the first one, is to create the unfiltered list unfiltered = [ (myFunction(C),C) for C in originalList ] and then sort it result = [ (dist,C) for dist,C in unfiltered if dist < limit ] but in that case, I duplicate my originalList and waste some memory (the list could be quite big - more than 10,000 elements) *the second one is tricky and not very pythonic, but efficient (the best we can do, since the function should be evaluated once per element). myFunction stores it last result in a global variable (lastResult for example), and this value is re-used in the List comprehension result = [ (lastResult,C) for C in originalList if myFunction(C) < limit ] Do you have any better idea to achieve that, in an efficient and pythonic way ?? Thanks for your answers. A: Sure, the difference between the following two: [f(x) for x in list] and this: (f(x) for x in list) is that the first will generate the list in memory, whereas the second is a new generator, with lazy evaluation. So, simply write the "unfiltered" list as a generator instead. Here's your code, with the generator inline: def myFunction(x): print("called for: " + str(x)) return x * x originalList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] limit = 10 result = [C2 for C2 in ((myFunction(C), C) for C in originalList) if C2[0] < limit] # result = [C2 for C2 in [(myFunction(C), C) for C in originalList] if C2[0] < limit] Note that you will not see a difference in the printout from the two, but if you were to look at memory usage, the second statement which is commented out, will use more memory. To do a simple change to your code in your question, rewrite unfiltered as this: unfiltered = [ (myFunction(C),C) for C in originalList ] ^ ^ +---------- change these to (..) ---------+ | v unfiltered = ( (myFunction(C),C) for C in originalList ) A: Don't use a list comprehension; a normal for loop is fine here. A: Just compute the distances beforehand and then filter the results: with_distances = ((myFunction(C), C) for C in originalList) result = [C for C in with_distances if C[0] < limit] Note: instead of building a new list, I use a generator expression to build the distance/element pairs. A: Some options: * *Use memoization *Use a normal for loop *Create an unfiltered list, then filter it (your option 1). The 'wasted' memory will be reclaimed by the GC very quickly - it's not something you need to worry about. A: Lasse V. Karlsen has an excellent reply to your question. If your distance computation is slow, I guess your elements are polylines, or something like that, right ? There are lots of ways to make it faster : * *If the distance between bounding boxes of objects is > X, then it follows that the distance between those objects is > X. So you only need to compute distance between bounding boxes. *If you want all objects that are at a distance less than X from object A, only objects whose bounding box intersect A's bounding box enlarged by X are potential matches. Using the second point you can probably drop lots of candidate matches and only do the slow computation when needed. Bounding boxes must be cached beforehand. If you really have a lot of objects you could also use space partitioning... Or convex enclosing polys if you are in 3D A: Rather than using a global variable as in your option 2, you could rely on the fact that in Python parameters are passed by object - that is, the object that is passed into your myFunction function is the same object as the one in the list (this isn't exactly the same thing as call by reference, but it's close enough). So, if your myFunction set an attribute on the object - say, _result - you could filter by that attribute: result = [(_result, C) for C in originalList if myFunction(C) < limit] and your myFunction might look like this: def myFunction(obj): obj._result = ... calculation .... return obj._result A: What's wrong with option 1? "duplicate my originalList and waste some memory (the list could be quite big - more than 10,000 elements)" 10,000 elements is only 10,000 pointers to tuples that point to existing objects. Think 160K or so of memory. Hardly worth talking about.
{ "language": "en", "url": "https://stackoverflow.com/questions/1222677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: SQL Server - copy all data from all tables from one server to another server with identical structure I want to copy all data from all tables from one SQL server database to another existing SQL server database of the same structure. I have a script to initially delete all contents of all tables in my output database before proceeding so that it is 'fresh' for the copy. I understand that 'select into' statements can get this done but I want to be able to do it in bulk. I want to emulate the behavior that works very well in Management Studio of: * *Right-click a DB *Select 'Tasks' *Select 'Export Data...' In here, I can select an output DB and then select all tables. The transfer goes straight through without issue. I cannot find a command line way to achieve this. The reason I am after this is that we want a daily copy of the prod database in a testing environment, so need to task schedule this process to run each night. Due to some contstraints, I can't use a bacpac in this case. A: Using the import/export task in SSMS, the last step has 2 options. Run immediately or save as SSIS package. So - save it as a SSIS package. You can then run this package whenever you want. And yes - you will need to do this twice. Once for export, once for import. You can also do exactly the same thing using SSIS btw. So how do you execute a package from the command line? Like you do for any question, you should search first. Some suggestions/examples are here. And if needed, you can schedule this using the agent.
{ "language": "en", "url": "https://stackoverflow.com/questions/46903214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP image gallery and items in row My images gallery has a xhtml like below: <div class="row"> <ul class="ul"> <li><a href="#"><img src=....></a></li> <li><a href="#"><img src=....></a></li> <li><a href="#"><img src=....></a></li> </ul> </div> <div class="row"> <ul class="ul"> <li><a href="#"><img src=....></a></li> <li><a href="#"><img src=....></a></li> <li><a href="#"><img src=....></a></li> </ul> </div> I want to do this: Insert only 3 <li> in <ul> and close the after 3 <li> What is the best way to do this? position ($pos = 0, $pos++) , array_chunk or anything else? Thanks in advance A: You have to prepare array of data. We way you prepare it doesn't really matter. You can use $pos++ and set column markers in the data array. and then output in in the template like this: <? foreach ($DATA as $row): ?> <? if($row['ul']): ?> <div class="row"> <ul class="ul"> <? endif ?> <li><a href="<?=$row['url']?>"><img src="<?=$row['src']?>"></a></li> <? if($row['/ul']): ?> </ul> </div> <? endif ?> or you can use array_chunk and then use nested foreaches: <? foreach ($DATA as $arr): ?> <div class="row"> <ul class="ul"> <? foreach ($arr as $row): ?> <li><a href="<?=$row['url']?>"><img src="<?=$row['src']?>"></a></li> <? endforeach ?> </ul> </div> <? endforeach ?> The latter one looks neat, I have to admit A: you can do for ($i=0 ; $i < 5; $i++){ echo '<div class="row"> <ul class="ul">'; for ($j=0;$j<3;$j++){ echo '<li><a href="#"><img src=....></a></li>'; } echo '</ul> </div>'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/3156244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SNMP v1 - Agent IP I'm sending SNMP traps using Net-SNMP utils (5.3). I'm setting the agent to a valid server IP but the NMS is receiving the trap as if it was a trap for the server generating it and not for the other server that I'm using in the agent field . I'm totally confused as to why this would be happening, other servers are using the same package and it works fine! Thanks, PJ A: Can you capture wireshark log to see if the IP address in SNMP level TRAP message is the same as the sender IP address in IP level?
{ "language": "en", "url": "https://stackoverflow.com/questions/1007978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I mutate all columns in a data set to keep only distinct values? Considering the data mtcars something like mtcars %>% select(mpg,cyl,disp,hp) %>% mutate_all(distinct()) I want to have all the distinct values only, I understand this will make the length of data- frame column unequal, so I wanted to also know if we can insert NAs for that? in short, I want to apply unique() across all columns separately without having to write something like unique(mtcars$cyl) for each of the rows. This will make the length of df unequal, A: A base solution: lapply(mtcars, unique) Here, unique() accepts a vector x and returns a (possibly shorter) vector consisting of the unique values. As you noted, the lengths of each unique collection will differ, so we use lapply() to obtain the answer as a list. Given what I think you're trying to do, this might be a more sensible approach than padding NA entries, because it seems like the only thing you want is the list of unique values. A: If I understand correct you are looking for this: To achieve your aim first transform the dataframe columns to list of vectors. Then replace the duplicates with NA to get the same length and wrap it around map_dfr: library(tidyverse) mtcars %>% dplyr::select(mpg,cyl,disp,hp) %>% as.list() %>% map_dfr(~replace(., duplicated(.), NA)) mpg cyl disp hp <dbl> <dbl> <dbl> <dbl> 1 21 6 160 110 2 NA NA NA NA 3 22.8 4 108 93 4 21.4 NA 258 NA 5 18.7 8 360 175 6 18.1 NA 225 105 7 14.3 NA NA 245 8 24.4 NA 147. 62 9 NA NA 141. 95 10 19.2 NA 168. 123 # ... with 22 more rows
{ "language": "en", "url": "https://stackoverflow.com/questions/71742710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dependency Injection Error in Worker Service Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: ProjectName.WS.Worker': Cannot consume scoped service 'ProjectName.Service.IServiceManager' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.) Program.cs Code IHost host = Host.CreateDefaultBuilder(args) .UseWindowsService(options => { options.ServiceName = "Service Name"; }) .ConfigureLogging(logging => { logging.AddSerilog(); }) .ConfigureServices((builder, services) => { services.AddHostedService<Worker>(); services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")) ); services.AddIdentity<IdentityUser, IdentityRole>().AddDefaultTokenProviders() .AddEntityFrameworkStores<AppDbContext>(); services.AddScoped<IServiceManager, ServiceManager>(); services.AddScoped<IRepoManager, RepoManager>(); }) .Build(); await host.RunAsync(); Worker.cs file Code public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; private readonly IServiceManager _serviceManager; private readonly IRepoManager _repoManager; public Worker(ILogger<Worker> logger, IServiceManager serviceManager, IRepoManager repoManager) { _logger = logger; _serviceManager = serviceManager; _repoManager = repoManager; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { var ewr = _serviceManager.CountryService.GetAll(); _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } } Service Manager File Code -- public class ServiceManager : IServiceManager { private IRepoManager _repoManager { get; set; } public ServiceManager(IRepoManager repoManager) { _repoManager = repoManager; CountryService = new CountryService(_repoManager.CountryRepo); } public ICountryService CountryService { get; set; } } Remo Manager File Code -- public class RepoManager : IRepoManager { private AppDbContext _db; public RepoManager(AppDbContext db) { _db = db; CountryRepo = new CountryRepo(_db); } public ICountryRepo CountryRepo { get; private set; } } Country Service File Code -- public class CountryService : ICountryService { private readonly ICountryRepo _repo; public CountryService(ICountryRepo repo) { _repo = repo; } } Country Repo File Code -- public class CountryRepo : ICountryRepo { private readonly AppDbContext _db; public CountryRepo(AppDbContext db) { _db = db; } } AppDBContext file code -- public class AppDbContext : IdentityDbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Country> Country { get; set; } } A: The service can not be initialized using the constructor instead you should do it like this: protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { using (IServiceScope scope = _serviceProvider.CreateScope()) { var _localServiceManager = scope.ServiceProvider.GetRequiredService<IServiceManager>(); var ewr = _serviceManager.CountryService.GetAll(); _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } } This is an example of microsoft
{ "language": "en", "url": "https://stackoverflow.com/questions/72529792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete row from a huge csv file in python I have a huge(240mb) csv file in which the top 2 rows are junk data.I want to remove this junk data and use the data starting after that. I would like to know what the best options are .Since its a large file creating a copy of the file and editing it would be a time taking process. Below is the csv eg:- junk,,, ,,,, No,name,place,destination 1,abx,India,SA What I would like to have is No,name,place,destination 1,abx,India,SA A: You can do this with tail quite easily tail -n+3 foo > result.data You said top 3 rows but the example has remove the top 2? tail -n+2 foo > result.data You can find more ways here https://unix.stackexchange.com/questions/37790/how-do-i-delete-the-first-n-lines-of-an-ascii-file-using-shell-commands A: Just throw those lines away. Use Dictreader to parse the header import csv with open("filename") as fp: fp.readline() fp.readline() csvreader = csv.DictReader(fp, delimiter=',') for row in csvreader: #your code here A: Due to the way file systems work, you cannot simply delete the lines from the file directly. Any method to do so will necessarily involve rewriting the entire file with the offending lines removed. To be safe, before deleting your old file, you'll want store the new file temporarily until you are sure the new one has been successfully created. And if you want to avoid reading the entire large file into memory, you'll want to use a generator. Here's a generator that returns every item from an iterable (such as a file-like object) after a certain number of items have already been returned: def gen_after_x(iterable, x): # Python 3: yield from (item for index,item in enumerate(iterable) if index>=x) # Python 2: for index,item in enumerate(iterable): if index>=x: yield item To make things simpler, we'll create a function to write the temporary file: def write_file(fname, lines): with open(fname, 'w') as f: for line in lines: f.write(line + '\n') We will also need the os.remove and os.rename functions from the os module to delete the source file and rename the temp file. And we'll need copyfile from shutil to make a copy, so we can safely delete the source file. Now to put it all together: from os import remove, rename from shutil import copyfile src_file = 'big_file' tmp_file = 'big_file_temp' skip = 2 with open(src_file) as fin: olines = gen_after_x(fin, skip) write_file(tmp_file, olines) src_file_copy = src_file + '_copy' copyfile(src_file, src_file_copy) try: remove(src_file) rename(tmp_file, src_file) remove(src_file_copy) except Exception: try: copyfile(src_file_copy, src_file) remove(src_file_copy) remove(tmp_file) except Exception: pass raise However, I would note that 240 MB isn't such a huge file these days; you may find it faster to do this the usual way since it cuts down on repetitive disk writes: src_file = 'big_file' tmp_file = 'big_file_temp' skip = 2 with open(src_file) as f: lines = f.readlines() for _ in range(skip): lines.pop(0) with open(tmp_file, 'w') as f: f.write('\n'.join(lines)) src_file_copy = src_file + '_copy' copyfile(src_file, src_file_copy) try: remove(src_file) rename(tmp_file, src_file) remove(src_file_copy) except Exception: try: copyfile(src_file_copy, src_file) remove(src_file_copy) remove(tmp_file) except Exception: pass raise ...or if you prefer the more risky way: with open(src_file) as f: lines = f.readlines() for _ in range(skip): lines.pop(0) with open(src_file, 'w') as f: f.write('\n'.join(lines))
{ "language": "en", "url": "https://stackoverflow.com/questions/36588336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TypeError: b is undefined when appending I know I have issue in referring value to this after seeing some similar questions on this site, but not able to solve this in my context. any one could help me to solve this , how do I refer value of splitInput to this as when I replace this with splitInput it is giving errors as splitInput is not an function here is my code snippet of only js <script type="text/javascript"> function styleBox(){ var userInput= document.getElementById('invite-emails').value; var splitInput=userInput.split(","); for(var i=0; i< splitInput.length; i++) { $(this).append("<span style='background-color:red'>"+splitInput[i]+((i< splitInput.length-1) ? ",":"")+"</span>"); } }; $(function(){ $(".team-btn").click(function(e) { $('.team-intro').replaceWith($(".team-invite").show()); }); }); $("#invite-emails").keypress(function(e){ if(e.which == 32) { styleBox(); } }); A: You call styleBox without setting this reference, you need to do styleBox.apply(this) $("#invite-emails").keypress(function(e){ if(e.which == 32) { styleBox.apply(this); } }); Than inside styleBox this will be showing to #invite-emails
{ "language": "en", "url": "https://stackoverflow.com/questions/43917785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dash Live Streaming on Nginx 404 Not Found on Cross Origin Request I want to set up a Dash Live Streaming nginx server to stream to a node.js app. I am new to nginx so tried finding the solution a lot, but no luck. I have all the required modules installed and I want to display the dash stream via Shaka Player. My nginx server is running on port 8080 and my node.js app is running on port 3000. I configured the server such that anyone on the Local Area Network can stream to this server via OBS. It is getting and storing the stream files properly. But every time my node app requests for the .mpd via shaka player, it displays: GET http://192.168.0.107/dash/test.mpd net::ERR_CONNECTION_REFUSED The Shaka Player script displays error 1002, which I found to be related to CORS. I tried so so many ways to Allow Cross Origin Request but none worked. Here is my current nginx.config file: worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; tcp_nopush on; keepalive_timeout 65; server { listen 8080; location / { root html; index index.html index.htm; } location /dash { add_header Access-Control-Allow-Origin * always; add_header Cache-Control no-cache always; root usr/local/nginx/stream/dash; } } } rtmp { server { listen 1935; chunk_size 4096; application dash { live on; record off; dash on; dash_nested on; dash_path usr/local/nginx/stream/dash; dash_fragment 3; dash_playlist_length 120; dash_cleanup on; } } } My current nginx version is 1.15.7. I tested both on windows and Ubuntu 17.10, with other versions too. I was unable to fix the problem. I also want to know whether add_header arguments need to be within quotes or not because I saw both versions on different places. Update: Changed request url to http://192.168.0.107:8080/dash/test/index.mpd and http://192.168.0.107:8080/dash/test.mpd, changed nginx.conf /dash root to usr/local/nginx/stream/dash and usr/local/nginx/stream but none worked. A: Thanks a lot sideshowbarker for your help. I changed the dash_path to /usr/local/nginx/stream/dash and root location to /usr/local/nginx/stream and it works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/53796523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: markov chains stationary distribution's condition about the init state As a property of the markov chain, the stationary distribution has been widely used in many fields like page_rank etc. However, since the distribution is just a property about the transition matrix and has nothing to do with the init state of the markov chain. So what's the condition of the transition matrix make the init state has nothing to do with markov chain so it will finally arrive at the stationary distribution after nth iteration. A: Markov chains aren't guaranteed to have unique stationary distributions. For example, consider a two state Markov Chain where the transition matrix is the identity matrix. That means that whatever the initial state is, it never changes. So in that case there is no stationary distribution that is independent of the initial case. Where there is a stationary distribution, unless the initial state is the stationary distribution, the stationary distribution is only reached in the limit as n tends to infinity. So iteration n+1 will be closer to it that iteration n, but however large n is, it won't ever actually be the stationary distribution. However, for practical purposes (i.e. to the limit of the accuracy of floating point numbers in computers), the stationary state may well be reached after a handful of iterations. A: You need the underlying graph to be strongly connected and aperiodic. If you want to find the stationary distribution of a periodic Markov chain just by running some chain, add "stay put" transitions with some constant probability to each node and scale the other transitions down appropriately.
{ "language": "en", "url": "https://stackoverflow.com/questions/16749280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inside ListView multiple toggleButton is getting on ,on clicking one toggleButton I have an ExpandableListView and inside each Parent Row . I am having a ToggleButton ,when I switch on one toggle button ,on scrolling below i am getting multiple toggleButton switched on. Why is this happening, I am getting groupPosition everything correctly in my log? here is my code : public class WifiAPListAdapter extends BaseExpandableListAdapter { private WifiAPListActivity context; public ArrayList<ExpandListGroup> groups; private WifiManager wifiManager; WifiStatus checkWifiStatus; public ToggleButton togglebtn; int pos; Holder holder; int previousPosition = -1; private static final int CHILD_COUNT = 1; public WifiAPListAdapter(WifiAPListActivity context, ArrayList<ExpandListGroup> result) { this.context = context; this.groups = result; wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); checkWifiStatus = new WifiStatus(context); } public Object getChild(int groupPosition, int childPosition) { return groups.get(groupPosition); } public long getChildId(int groupPosition, int childPosition) { return groupPosition; } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) { previousPosition = groupPosition; ExpandListGroup child = (ExpandListGroup) getChild(groupPosition, groupPosition); // Log.i("", "getChildView: "+childPosition); if (view == null) { holder = new Holder(); LayoutInflater infalInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = infalInflater.inflate(R.layout.list_child_item, null); holder.label_ssid = (TextView) view.findViewById(R.id.label_ssid); holder.tv_ssid = (TextView) view.findViewById(R.id.tvssid); holder.label_bssid = (TextView) view.findViewById(R.id.label_bssid); holder.tv_bssid = (TextView) view.findViewById(R.id.tvbssid); holder.label_capabilities = (TextView) view .findViewById(R.id.label_capabilities); holder.tv_capabilities = (TextView) view .findViewById(R.id.tvcapabilities); holder.label_signalStrength = (TextView) view .findViewById(R.id.label_signalstrength); holder.tv_signalStrength = (TextView) view .findViewById(R.id.tvsignalstrength); holder.wifi_signalimg = (ImageView) view.findViewById(R.id.signal); view.setTag(holder); } else { holder = (Holder) view.getTag(); } // *********************setting data to the child list************** holder.tv_ssid.setText(child.getSSID()); holder.tv_bssid.setText(child.getBSSID()); holder.tv_capabilities.setText(child.getCapabilities()); holder.tv_signalStrength.setText(child.getData()); Bitmap bitmap = setSignalImage(Integer.parseInt(child.getData())); holder.wifi_signalimg.setImageBitmap(bitmap); return view; } public int getChildrenCount(int groupPosition) { Log.i("", "getChildrenCount: " + groupPosition); return CHILD_COUNT; } public Object getGroup(int groupPosition) { return groups.get(groupPosition); } public int getGroupCount() { Log.i("", "getGroupCount: " + groups.size()); return groups.size(); } public long getGroupId(int groupPosition) { return groupPosition; } public View getGroupView(int groupPosition, boolean isLastChild, View view, ViewGroup parent) { Log.i("", "getGroupView: " + groupPosition); if (view == null) { holder = new Holder(); LayoutInflater inf = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inf.inflate(R.layout.list_parent_items, null); holder.tv_ssid = (TextView) view.findViewById(R.id.ssid); holder.tv_bssid = (TextView) view.findViewById(R.id.bssid); holder.btn_toggle = (ToggleButton) view.findViewById(R.id.togBtn); // holder.btn_toggle.setTag(groups.get(groupPosition).getBSSID()); view.setTag(holder); } else { holder = (Holder) view.getTag(); } // holder.btn_toggle.setTag(groups.get(groupPosition).getBSSID()); holder.tv_ssid.setText(groups.get(groupPosition).getSSID()); holder.tv_bssid.setText(groups.get(groupPosition).getBSSID()); return view; } public void toggle(View v) { if (holder.btn_toggle.isChecked()) { } Log.i("", "toggle"); } public boolean hasStableIds() { return true; } public boolean isChildSelectable(int arg0, int arg1) { return true; } can any body tell a good method to avoid this problem without removing holder because if i would have n number of items then its not a good idea to draw view every time we should use holder. A: remove holder and close if loop for inflate like how i am closed also use logic for toggle inside getGroupView .because every time u scroll the listview the getGroupView get called so every time it this method has to check the condition. private WifiAPListActivity context; public ArrayList<ExpandListGroup> groups; private WifiManager wifiManager; WifiStatus checkWifiStatus; public ToggleButton togglebtn; int pos; Holder holder; int previousPosition = -1; private static final int CHILD_COUNT = 1; public WifiAPListAdapter(WifiAPListActivity context, ArrayList<ExpandListGroup> result) { this.context = context; this.groups = result; wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); checkWifiStatus = new WifiStatus(context); } public Object getChild(int groupPosition, int childPosition) { return groups.get(groupPosition); } public long getChildId(int groupPosition, int childPosition) { return groupPosition; } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) { previousPosition = groupPosition; ExpandListGroup child = (ExpandListGroup) getChild(groupPosition, groupPosition); // Log.i("", "getChildView: "+childPosition); if (view == null) { holder = new Holder(); LayoutInflater infalInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = infalInflater.inflate(R.layout.list_child_item, null); } label_ssid = (TextView) view.findViewById(R.id.label_ssid); tv_ssid = (TextView) view.findViewById(R.id.tvssid); label_bssid = (TextView) view.findViewById(R.id.label_bssid); tv_bssid = (TextView) view.findViewById(R.id.tvbssid); label_capabilities = (TextView) view .findViewById(R.id.label_capabilities); tv_capabilities = (TextView) view .findViewById(R.id.tvcapabilities); label_signalStrength = (TextView) view .findViewById(R.id.label_signalstrength); tv_signalStrength = (TextView) view .findViewById(R.id.tvsignalstrength); wifi_signalimg = (ImageView) view.findViewById(R.id.signal); // *********************setting data to the child list************** tv_ssid.setText(child.getSSID()); tv_bssid.setText(child.getBSSID()); tv_capabilities.setText(child.getCapabilities()); tv_signalStrength.setText(child.getData()); Bitmap bitmap = setSignalImage(Integer.parseInt(child.getData())); wifi_signalimg.setImageBitmap(bitmap); return view; } public int getChildrenCount(int groupPosition) { Log.i("", "getChildrenCount: " + groupPosition); return CHILD_COUNT; } public Object getGroup(int groupPosition) { return groups.get(groupPosition); } public int getGroupCount() { Log.i("", "getGroupCount: " + groups.size()); return groups.size(); } public long getGroupId(int groupPosition) { return groupPosition; } public View getGroupView(int groupPosition, boolean isLastChild, View view, ViewGroup parent) { Log.i("", "getGroupView: " + groupPosition); if (view == null) { holder = new Holder(); LayoutInflater inf = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inf.inflate(R.layout.list_parent_items, null); } tv_ssid = (TextView) view.findViewById(R.id.ssid); tv_bssid = (TextView) view.findViewById(R.id.bssid); btn_toggle = (ToggleButton) view.findViewById(R.id.togBtn); // holder.btn_toggle.setTag(groups.get(groupPosition).getBSSID()); // holder.btn_toggle.setTag(groups.get(groupPosition).getBSSID()); tv_ssid.setText(groups.get(groupPosition).getSSID()); tv_bssid.setText(groups.get(groupPosition).getBSSID()); return view; } public void toggle(View v) { if (btn_toggle.isChecked()) { } Log.i("", "toggle"); } public boolean hasStableIds() { return true; } public boolean isChildSelectable(int arg0, int arg1) { return true; } A: This is happening because of mechanism of Recycling of Views. I had written a blog post for the same taking into consideration ListView. If you are not aware about recycling of views then probably you must read this blog to get exact idea about how recycling of view works!
{ "language": "en", "url": "https://stackoverflow.com/questions/18013409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TextInputLayout - Cursor doesn't follow user typing at the end of the view Description: User starts to type a long text and when the cursor "hits" the end of the view, the EditText not scroll horizontally and all the letters typed by user after that is not shown. To see the text typed, user needs to scroll the EditText manually. In others words, the cursor is not following the end of the text that user types as normal. Source code: On XML: <com.google.android.material.textfield.TextInputLayout android:id="@+id/tilEmail" android:layout_width="0dp" android:layout_height="wrap_content"> <EditText android:id="@+id/etEmail" android:inputType="textEmailAddress" android:layout_width="match_parent" android:layout_height="wrap_content"/> </com.google.android.material.textfield.TextInputLayout> On gradle api 'androidx.legacy:legacy-support-v4:1.0.0' api 'androidx.appcompat:appcompat:1.1.0' api 'androidx.core:core-ktx:1.0.2' api "com.google.android.material:material:1.0.0" Android API version: Tested on API 28 Device: Pixel 3 Update I found out that the problem was partially resolved when I put the attribute android:scrollbars="vertical" on my EditText. "Partially resolved", because when I use this in a Activity that has android:windowSoftInputMode="adjustPan", the problem keep happening. A: Use a TextInputEditText instead of a EditText <com.google.android.material.textfield.TextInputLayout ...> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" .../> </com.google.android.material.textfield.TextInputLayout> Automatically with layout_height="wrap_content" the content uses multiple lines. Also try the latest version 1.1.0-alpha10. A: Using TextInputEditText. Try android: scrollbars="vertical". Version api "com.google.android.material: material: 1.0.0"
{ "language": "en", "url": "https://stackoverflow.com/questions/58141329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible send HTTP/2 GET request with socket? I need to use HTTP/2 protocol in Python but all libs which support it can't send request with HTTPS proxy. Only HTTP. How can I send it with socket and HTTPS proxy?
{ "language": "en", "url": "https://stackoverflow.com/questions/64407276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: querySelectorAll ":not" doesn't work in IE8, does jQuery's version? Unfortunately I have to support IE8 and need to select inputs using the :not modifier. I know that IE8 doesn't support this in querySelectorAll but does jQuery's version support IE8 for this? querySelectorAll: domElement.querySelectorAll( "input:not([name*='[statistic]']):not([type=button]),textarea:not([name*='[statistic]'])" ); jQuery: jQuery( "input:not([name*='[statistic]']):not([type=button]),textarea:not([name*='[statistic]'])", domElement ); A: Short answer: Yes. One of the main things that made jQuery popular in the first place was that it allowed older browsers to support the new selectors like :not. So yes, you will be able to use :not and other selectors in jQuery code. You can't use :not with querySelectorAll() in IE8 because IE8 simply doesn't support it. IE8 supports CSS2.1 which was the current standard at the time it was released. :not simply wasn't in the picture. And you can't use querySelectorAll() at all in older IE versions than that. jQuery was created specifically to deal with these issues and allow developers to support older IE versions while still allowing us to use modern browser features. There may be people today saying that you don't need jQuery any more, but if you need to support old IE versions, the need for jQuery is just as much as it always was.
{ "language": "en", "url": "https://stackoverflow.com/questions/32466245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Copy XML file structure (incl.) directories with XSLT (2.0) Meta * *XSLT 2.0 *XML (with nested links to other XML files) *Saxon XSLT processor *Oxygen Editor I want to write a stylesheet (XSLT 2.0) that simply copies a whole file structure (I use a XML root file with linked other files in it) and places the result(s) into a certain destination folder. How can I do this? What would be the best and effective way of doing this? A: Assuming that you have a good reason for doing this in XSLT (like, it's part of a larger task, or XSLT is your only programming language), you should take a look at the EXPath file module. The file:copy() function copies a directory. http://expath.org/spec/file#fn.copy It's available in Saxon-PE 9.6 or later/higher. A: To expand on Xephon's answer: you could generate an Ant script that then does the copying. If you have Oxygen then you also have the D4P net.sourceforge.dita4publishers.common.xslt plugin, which has code for generating an Ant copy script--it's used by the EPUB transform to manage the copying of resources from the source area to the EPUB temp directory from which the EPUB zip is created. In that same plugin is the relpath_util.xsl module, which provides general XSLT functions for working with URLs and file paths in a Java-like way. Mike's solution is obviously the easiest but is dependent on extensions. A: thank you for describing your toolset. If possible, you should simply do this using the Ant Copy Task. The DITA Open Toolkit uses Ant and Oxygen XML ships Ant as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/34059344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.Net Media Suite - Review Does anyone have a review of ASP.Net Media Suite located on http://www.aspnetmedia.com/ The tool seems pretty nice, but i've never heard of the company. I'm hesitant to purchase and install something from an unknown source. Can anyone vouch for the product? A: well, i have sent many emails, and never got an answer, if you ask me you are better with many other alternatives, like there is an a amazing flash control i use http://www.flash-control.net/ it does everything to implement flash like XHTML valid inclusion, Option to install flash if not available, Flash Vars, etc... then you can choose of millions of flash mp3 players, video players on net which use XML, then simply you create the XML in code and hook any special Flashvars with this control and you have a great media player. here is a nice site i always got to for such stuff www.flashden.net. hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/680104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Data Binding RibbonComboBox? I am using wpf 4 and the Microsoft Ribbon. My binding shows the names of each user in the Users list but the selection is not showing in the RibbonComboBox after the drop down closes. Thanks A: This worked for me: XAML: ... <r:RibbonComboBox IsEditable="True"> <r:RibbonGallery > <r:RibbonGalleryCategory ItemsSource="{Binding}" Name="userBox" /> </r:RibbonGallery> </r:RibbonComboBox> ... C# ... userBox.ItemsSource = LoadComboBoxUser(); ...
{ "language": "en", "url": "https://stackoverflow.com/questions/5237319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to set the description of a local group to blank Consider the following code: # create test group New-LocalGroup -Name 'Group1' -Description 'xxx' # update test group description to blank Set-LocalGroup -Name 'Group1' -Description '' # fails Set-LocalGroup -Name 'Group1' -Description $null # fails On the contrary it is possible to create a group without description: New-LocalGroup -Name 'Group2' How is it possible to update the group description of a local group to blank without removing the group first? This happens on PowerShell 5.1. A: As Set-LocalGroup fails on that, the only other way I can think of is using ADSI: $group = [ADSI]"WinNT://$env:COMPUTERNAME/Group1,group" $group.Description.Value = [string]::Empty $group.CommitChanges() It's a workaround of course and I agree with iRon you should do a bug report on this. A: Although there are some AD attributes that requires the Putex method, that doesn't count for the Description attribute. Meaning my assumption in the initial comment to the question is wrong, and it is possible to clear the Description attribute with just the Put method`: $Name = 'Group1' New-LocalGroup -Name $Name -Description 'xxx' $Group = [ADSI]"WinNT://./$Name,group" $Group.Put('Description', '') $Group.SetInfo() Get-LocalGroup -Name $Name Name Description ---- ----------- Group1 The issue lays purely in the cmdlet parameter definitions. Without going into the C# programming, you might just pull this from the proxy command: $Command = Get-Command Set-LocalGroup $MetaData = [System.Management.Automation.CommandMetadata]$Command $ProxyCommand = [System.Management.Automation.ProxyCommand]::Create($MetaData) $ProxyCommand [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium', HelpUri='https://go.microsoft.com/fwlink/?LinkId=717979')] param( [Parameter(Mandatory=$true)] [ValidateNotNull()] # <-- Here is the issue [ValidateLength(0, 48)] [string] ${Description}, ... In other words, to quick and dirty workaround this with a proxy command: function SetLocalGroup { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium', HelpUri='https://go.microsoft.com/fwlink/?LinkId=717979')] param( [Parameter(Mandatory=$true)] [AllowEmptyString()] # <-- Modified [ValidateLength(0, 48)] [string] ${Description}, [Parameter(ParameterSetName='InputObject', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNull()] [Microsoft.PowerShell.Commands.LocalGroup] ${InputObject}, [Parameter(ParameterSetName='Default', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNull()] ${Name}, [Parameter(ParameterSetName='SecurityIdentifier', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNull()] [System.Security.Principal.SecurityIdentifier] ${SID}) end { if ($Description) { Set-LocalGroup @PSBoundParameters } elseif ($Name) { $Group = [ADSI]"WinNT://./$Name,group" $Group.Put('Description', '') $Group.SetInfo() } } } SetLocalGroup -Name 'Group1' -Description '' Related bug report: #16049 AllowEmptyString()] for -Description in Set-LocalGroup/SetLocalUser
{ "language": "en", "url": "https://stackoverflow.com/questions/69041644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Data mining with postgres in production environment - is there a better way? There is a web application which is running for a years and during its life time the application has gathered a lot of user data. Data is stored in relational DB (postgres). Not all of this data is needed to run application (to do the business). However form time to time business people ask me to provide reports of this data data. And this causes some problems: * *sometimes these SQL queries are long running *quires are executed against production DB (not cool) *not so easy to deliver reports on weekly or monthly base *some parts of data is stored in way which is not suitable for such querying (queries are inefficient) My idea (note that I am a developer not the data mining specialist) how to improve this whole process of delivering reports is: * *create separate DB which regularly is update with production data *optimize how data is stored *create a dashboard to present reports Question: But is there a better way? Is there another DB which better fits for such data analysis? Or should I look into modern data mining tools? Thanks! A: Do you really do data mining (as in: classification, clustering, anomaly detection), or is "data mining" for you any reporting on the data? In the latter case, all the "modern data mining tools" will disappoint you, because they serve a different purpose. Have you used the indexing functionality of Postgres well? Your scenario sounds as if selection and aggregation are most of the work, and SQL databases are excellent for this - if well designed. For example, materialized views and triggers can be used to process data into a scheme more usable for your reporting. A: There are a thousand ways to approach this issue but I think that the path of least resistance for you would be postgres replication. Check out this Postgres replication tutorial for a quick, proof-of-concept. (There are many hits when you Google for postgres replication and that link is just one of them.) Here is a link documenting streaming replication from the PostgreSQL site's wiki. I am suggesting this because it meets all of your criteria and also stays withing the bounds of the technology you're familiar with. The only learning curve would be the replication part. Replication solves your issue because it would create a second database which would effectively become your "read-only" db which would be updated via the replication process. You would keep the schema the same but your indexing could be altered and reports/dashboards customized. This is the database you would query. Your main database would be your transactional database which serves the users and the replicated database would serve the stakeholders. This is a wide topic, so please do your diligence and research it. But it's also something that can work for you and can be quickly turned around. A: If you really want try Data Mining with PostgreSQL there are some tools which can be used. * *The very simple way is KNIME. It is easy to install. It has full featured Data Mining tools. You can access your data directly from database, process and save it back to database. *Hardcore way is MADLib. It installs Data Mining functions in Python and C directly in Postgres so you can mine with SQL queries. Both projects are stable enough to try it. A: For reporting, we use non-transactional (read only) database. We don't care about normalization. If I were you, I would use another database for reporting. I will desing the tables following OLAP principals, (star schema, snow flake), and use an ETL tool to dump the data periodically (may be weekly) to the read only database to start creating reports. Reports are used for decision support, so they don't have to be in realtime, and usually don't have to be current. In other words it is acceptable to create report up to last week or last month.
{ "language": "en", "url": "https://stackoverflow.com/questions/29593171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Advantage of var keyword in C# 3.0 Duplicate: What to use var or object name type I couldn't understand the need of var keyword in C# 3.0 What is the advantage in using it. i saw this question but did not understand the real purpose of using it A: The primary reason for its existence is the introduction of anonymous types in C#. You can construct types on the fly that don't have a name. How would you specify their name? The answer: You can't. You just tell the compiler to infer them for you: var user = users.Where(u=> u.Name == "Mehrdad") .Select(u => new { u.Name, u.Password }); A: It's mostly present for LINQ, when you may use an anonymous type as the projection: var query = from person in employees where person.Salary > 10000m select new { FullName=person.Name, person.Department }; Here the type of query can't be declared explicitly, because the anonymous type has no name. (In real world cases the anonymous type often includes values from multiple objects, so there's no one named class which contains all the properties.) It's also practically useful when you're initializing a variable using a potentially long type name (usually due to generics) and just calling a constructor - it increases the information density (reduces redundancy). There's the same amount of information in these two lines: List<Func<string, int>> functions = new List<Func<string, int>>(); var functions = new List<Function<string, int>>(); but the second one expresses it in a more compact way. Of course this can be abused, e.g. var nonObviousType = 999999999; but when it's obvious what the type's variable is, I believe it can significantly increase readability. A: It's a shorthand way of declaring a var. Although "int i = new int()" isn't too much to type, when you start getting to longer types, you end up with a lot of lines that look like: SomeReallyLong.TypeName.WithNameSpaces.AndEverything myVar = new SomeReallyLong.TypeName.WithNameSpaces.AndEverything(); It eventually occurred to someone that the compiler already knew what type you were declaring thanks to the information you were using to initialize the var, so it wouldn't be too much to ask to just have the compiler do the right thing here. A: * *Linq expressions don't return a predefined type, so you need a 'generic' variable declaration keyword to capture that and other places where anonymous types are used. *Used carefully, it can make refactoring easier by decoupling a method's return type from the variable that captures it. *Having to put the same name on the same line twice for the same statement is really kind of silly. It's a pain to type something like this: . ReallyLongTypeName<SomeOtherLongTypeName> MyVariable = new ReallyLongTypeName<SomeOtherLongTypeName>(); A: Here are a couple of advantages * *Less typing with no loss of functionality *Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types *Makes it so you don't have to write the same name twice in a variable declaration. *Some features, such as declaring a strongly typed anonymous type local variable, require the use of var Shameless self promotion. I wrote a blog entry on this subject awhile back that dived into when I thought the use of var was appropriate and contains relative information to this topic. * *http://beta.blogs.msdn.com/jaredpar/archive/2008/09/09/when-to-use-type-inference.aspx A: In short: * *minimize the need for typing the variable type twice *essential in supporting anonymous types, e.g. as returned by LINQ queries A: The real need for the var keyword was to support anonymous types in C# 3.0--which in turn were required to properly support LiNQ (Language Integrated Querying). Without using var you could never do something like this: var person = new { Name = "Peter", Age=4}; Which means that you couldn't execute execute the following linq query because you wouldn't know how to assign it to a variable: [var/sometype] dogsFixedQuery = from myDog in kennel select new {dogName = myDog.FirstName + " " + myDog.OwnerLastName, myDog.IsNeutered, dogLocation = kennel.Address}; The utility of anonymous types will be more apparent if you start to create more complex linq queries with multiple levels of returns and joins. The fact that you can use var in other ways to avoid typing out something like IEnumerable<Dictionary<List<string>,IOrderedCollection<DateTime>> myBadDesign = getBadDesignController().BadDesignResults("shoppingCart"); is just a side-effect/bonus in case you're a lazy typer =) There are cons for readability if you start calling vars in disparate locations but if you're using var for a strong type and the compiler can determine the type of your variable than any reader should be able to determine it as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/884555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Getting constraint error on updating the constraint in cellforRow I have a UITableViewCell with collectionView inside it. constraint are pretty simple leading 0 , trailing 0 , top 10 and bottom 10 and height constraint of UICollection view is 160 . Connected an IBOutlet to height constraint. In cell for row I am updating the heigth constraint. But getting error in debug Code of cell for row is func videoCell(for tableView:UITableView ,with indexPath:IndexPath , videos:[VideoCollectionViewCellConfigure] ) -> VideoTableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "VideoTableViewCell", for: indexPath) as! VideoTableViewCell cell.videoConfigurators = videos cell.collectionCellClickedBlock = self.videoCollectionCellClicked(_:_:) if videos.count > 0 { let video = videos[0] cell.videoCollectionViewHeightConstraint.constant = video.height } cell.videoCollectionView.reloadData() return cell } 2018-04-16 12:42:10.815998+0530 CineBee[5280:74417] [LayoutConstraints] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. ( "<NSLayoutConstraint:0x6000006878a0 UICollectionView:0x7f86109c4c00.height == 180 (active)>", "<NSLayoutConstraint:0x604000885870 V:[UICollectionView:0x7f86109c4c00]-(10)-| (active, names: '|':UITableViewCellContentView:0x7f8615803ca0 )>", "<NSLayoutConstraint:0x604000888de0 V:|-(10)- [UICollectionView:0x7f86109c4c00] (active, names: '|':UITableViewCellContentView:0x7f8615803ca0 )>", "<NSLayoutConstraint:0x60400088dde0 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7f8615803ca0.height == 180.5 (active)>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x6000006878a0 UICollectionView:0x7f86109c4c00.height == 180 (active)> A: Try this override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { var defaultHeight = /*your default height*/ if videos.count > 0 { let video = videos[0] return video.height + 10 + 10 // video height + top padding + bottom padding } return defaultHeight } Also remove the collectionView height constraint from the Interface builder. Now you don't have to set constraint in the cellForItemAtIndexPath. A: According to your error report, it seems like the case I was attempting to address in this SO question. If the conflicting constraints contain UIView-Encapsulated-Layout-Height it means the conflict arises during calculating dynamic height based on autolayout. Just lower one of the vertical constraints priority to 999 - if the code works, it's ok and you are good to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/49851611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to detect circular dependency in mysql I have a table which stores a parent reference. The parent reference is the another entry in same table. Table structure is something like CREATE TABLE `mytable` ( `Id` int(11) NOT NULL, `ParentId` int(11) NOT NULL, PRIMARY KEY (`Id`), KEY `ParentId` (`ParentId`), CONSTRAINT `mytable_ibfk_1` FOREIGN KEY (`ParentId`) REFERENCES `mytable` (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 How to find circular/cyclic dependency in hierarchy or sub-hierarchy? We don't want to find it necessarily at the time of insert. We can run the solution post data is inserted too. We are using Mysql version 5.7
{ "language": "en", "url": "https://stackoverflow.com/questions/67514642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Automatic ID generation with create! block in model I'm trying to use the following inside my model: create!( :title => entry.title, :link => entry.url, :published_date => entry.published, :entry_id => entry.id, :category => thing, :author => entry.author, :user_id => user.id ) This fails with Mysql2::Error: Duplicate entry '0' for key 'PRIMARY' when adding anything past the first entry since the id column is being set as 0. Is there a way to auto-increment the id using the above code? Thanks A: You should never need to manually specify the ID when creating new instances; Rails will automatically create the auto-incrementing column to handle generating unique IDs for you. In this case, if you have tampered with the ID column and changed its type, the easiest way to reset this is to simply recreate the table.
{ "language": "en", "url": "https://stackoverflow.com/questions/16533930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sh shell double if statement Can anyone see what I did wrong here? I keep getting the following error message: [[: not found read INPUT if [[ "$INPUT" -ge 1 ]] && [[ "$INPUT" -le 10 ]]; then Do something else printf "Please enter a value between 1 and 10" fi A: [[ is not available in scripts which start with #!/bin/sh, or which are started with sh yourscript. Start your script with #!/bin/bash if you want to use it. See also http://mywiki.wooledge.org/BashGuide/Practices#Choose_Your_Shell If you are going to use bash, by the way, there's a better syntax for numeric comparisons: if (( input >= 1 && input <= 10 )); then ... Note that lower-case variable names are preferred for local use -- all-upper-case names are reserved for environment variables and shell builtins. If you're not going to use bash, use the POSIX test operator: if [ "$input" -ge 1 ] && [ "$input" -le 10 ]; then ... Note that when using [ ] correct quoting is essential, whereas with [[ ]] it is often superfluous; also, [ ] is missing some extensions such as pattern-matching and regular-expression operators. A: It's complicated: First, there are three separate ways of constructing your if statement. Each way has its own unique syntax on how to join two booleans. (Actually, there are four ways since one way allows you to use list operators). A little background... The if command is a compound command built into the shell. The if command executes the commands following the if. If that command returns a zero value, the if statement is considered true and the then clause executes. Otherwise, if it exists, the else clause will execute. Remember, the if is just a command. You can do things like this: if ! mv "$foo" "$bar" then echo "I can't move $foo to $bar" exit 2 fi What we need is a command to do some testing for us. If the test succeeds, that test command returns an exit code of zero. If not, it returns a non-zero exit code. Then, it could be used with the if command! The test command (Yes, there's really one!). The [ is an alias for the test command which was created to allow you to test files, strings, and numbers for the if statement. (This is now a built in command in Bash, but its roots are actually part of /bin/test and /bin/[). These are the same: if test "$foo" -eq "$bar" then ... fi and if [ "$foo" -eq "$bar" ] then ... fi The test command (if you read the manpage has a -a And test and a -o Or test. You could have done: if [ "$INPUT" -ge 1 -a "$INPUT" -le 10 ] then .... fi This is a single test statement with three test parameters (-ge, -a, and -le). Using List Operators This isn't the only way to do a compound boolean test. The Bash shell has two list operators: && and ||. The list operators go in between two commands. If you use && and the left hand command returns a non-zero exit code, the right hand command is not executed, and the entire list returns the exit value of the left-hand command. If you use ||, and the left hand command succeeds, the right hand command is not executed, and the entire list returns a zero exit value. If the first command returns a non-zero exit value, the right-hand command is executed, and the entire list returns the exit value of the right-hand command. That's why you can do things like this: [ $bar -eq 0 ] || echo "Bar doesn't have a zero value"! Since [ ... ] is just a command that returns a zero or non-zero value, we can use these list operators as part of our test: if [ "$INPUT" -ge 1 ] && [ "$INPUT" -le 10 ] then ... fi Note that this is two separate tests and are separated by a && list operator. Bash's Special [[ compound command In Kornshell, Zsh, and Bash, there are special compound commands for testing. These are the double square brackets. They appear to be just like the single square brackets command, but because they're compound commands, parsing is affected. For example: foo="This has white space" bar="" #No value if [ ! $foo = $bar ] # Doesn't work! then The shell expands $foo and $bar and the test will become: if [ This has white space = ] which just doesn't work. However, if [[ $foo != $bar ]] works fine because of special parsing rules. The double brackets allow you to use parentheses for grouping and && and || as boolean operators. Thus: if [[ $INPUT -ge 1 && $INPUT -le 10 ]] then ... fi Note that the && appears inside a single set of double square brackets. (Note there's no need for quotation marks) Mathematical Boolean Expression Bash has built in mathematical processing including mathematical boolean expressions. If you put something between double parentheses, Bash will evaluate it mathematically: if (( $INPUT >= 1 && $INPUT <= 10 )) then ... fi In this case, (( $INPUT >= 1 && $INPUT <= 10 )) is evaluated. If $INPUT is between 1 and 10 inclusively, the mathematical expression will evaluate as true (zero exit code), and thus the then clause will be executed. So, you can: * *Use the original test (single square brackets) command and use the -a to string together two boolean statements in a single test. *Use list operators to string together two separate test commands (single square brackets). *Use the newer compound test command (double square brackets) that now include && and || as boolean operators, so you have a single compound test. *Forget about test command and just use mathematical evaluation (double parentheses) to evaluate boolean expressions. A: Test Constructs Can Vary by Shell As has been mentioned in other posts, [[ is a Bash shell keyword that isn't present in the Bourne shell. You can see this from a Bash prompt with: type '[[' [[ is a shell keyword In a Bourne shell, you will instead get "command not found." Be More Portable: Use the -a Test Operator A more portable construct is to use the -a test operator to join conditions (see man test for details). For example: if [ "$INPUT" -ge 1 -a "$INPUT" -le 10 ]; then : # do something when both conditions are true else : # do something when either condition is false fi This will work in every Bourne-compatible shell I've ever used, and on any system that has a /bin/\[ executable.
{ "language": "en", "url": "https://stackoverflow.com/questions/24897321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax with set Interval OR SignalR I have a scenario, where i need check if my Database has received new orders (restaurant). Signalr seems to be the best option. But I can wait 2-3 minutes to update with AJAX. Given this long range I can expect, and thinking of a large scale, would not ajax be better? A: Although this looks like a duplicate of: Is SignalR a suitable substitute for jQuery Ajax (or similar), I'd say you should use SignalR, based on the chosen answer to the similar question. SignalR is perfect for notifying users real-time. You can call client functions from the server and vice versa. This makes it very dynamic. I think it would be more heavier to call an endpoint every 2 minutes – even if there was no order placed – then only perform an action when an order has been placed. The capacity for concurrent connections depends on the performance of the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/52795123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: instanceof in SpEL i have a class with the method: Code: List<Entity> getData() {...} and some classes which extends Entity: Project, Phase, Invoice, Payment. and i would like to do something like this: @PostFilter("filterObject instanseof Project ? filterObject.manager == principal : filterObject instanceof Phase ? filterObject.project.manager == principal : filterObject instanceof Invoice ? filterObject.phase.project == principal : filterObject instanceof Payment ? filterObject.invoice.phase.project.manager == principal : true") is it a legal? or how to use "instanceof" correctly? A: The correct syntax for SpEL would be like filterObject instanceof T(Project). (Please see SpEL section 6.5.6.1 - Relational operators)
{ "language": "en", "url": "https://stackoverflow.com/questions/7628437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: RecyclerViews inside NestesScrollView I want to place two RecyclerViews inside a NestedScrollView where all items of each RecyclerView should be displayed: Desired: Current: --------------------- --------------------- Fixed Header content Fixed Header content --------------------- --------------------- <NestedScrollView> <NestedScrollView> EditText EditText EditText EditText ... ... <RecyclerView> <RecyclerView> (scrollable> Item 1 Item 1 Item 2 </RecyclerView> ... <RecyclerView> (scrollable> Item N Item 2 </RecyclerView> </RecyclerView> <RecyclerView> </NestedScrollView> Item 1 -------------------- Item 2 ... Item M </RecyclerView> </NestedScrollView> ---------------------- Currently, only the first item of each RecyclerView is displayed and you can scroll down to the other items within this limited space. I have tried to set RecyclerView.setNestedScrollingEnabled(false); with the effect that still only the first item of the RecyclerView is displayed, and the RecyclerView is not scrollable anymore. This all is contained in a Fragment which is included in an Activity hosting a BottomNavigationView. Activity layout: <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout 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:id="@+id/coordinatorLayoutMain" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".gui.activity.MainActivity"> <android.support.design.widget.AppBarLayout android:id="@+id/appBarLayout" app:elevation="0dp" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> </android.support.design.widget.AppBarLayout>--> <FrameLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <android.support.design.widget.BottomNavigationView android:id="@+id/bottomNavigationView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:background="@color/white" app:itemTextColor="@color/bottom_navigation_item_color" app:itemIconTint="@color/bottom_navigation_item_color" app:menu="@menu/menu_bottom_main_activity" /> </android.support.design.widget.CoordinatorLayout> Fragment layout: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white"> ... fixed header content ... <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/header" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:isScrollContainer="true" > <android.support.design.widget.TextInputLayout ... /> <TextView android:id="@+id/catHeader1" style="@style/Me.CatHeader" android:layout_below="@id/dummy1" android:text="@string/textCat1" /> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/catHeader1" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <TextView android:id="@+id/action1" style="@style/Me.AddText" android:layout_below="@id/recyclerView1" android:text="@string/action1" android:visibility="gone" /> <TextView android:id="@+id/catHeader2" style="@style/Me.CatHeader" android:layout_below="@id/action1" android:text="@string/textCat2" /> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/catHeader2" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <TextView android:id="@+id/action2" style="@style/Me.AddText" android:layout_below="@id/recyclerView2" android:text="@string/action2" android:visibility="gone" /> </RelativeLayout> </android.support.v4.widget.NestedScrollView> </RelativeLayout> Both RecyclerViews use a vertical LinearLayoutManager. Using match_parent on the RecyclerViews height doesn't change anything. AppCompat version: 25.1.0 What am I missing, what am I doing wrong? A: Found the problem: The root layout for the items had layout_height = match_parent, setting it to layout_height = ?listPreferredItemHeight solved it all.
{ "language": "en", "url": "https://stackoverflow.com/questions/41920184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lost connection to the debugger on iPhone simulator running Big sur11.4 I have face the issue while running my app on Big sur 11.4.While run the app I got "Build succeeded" message but after app is automatically stops then showing a popup message like Lost connection to the debugger on “iPhone 12”. Domain: IDEDebugSessionErrorDomain Code: 4 Recovery Suggestion: Restore the connection to “iPhone 12” and run “APP_TARGET_NAME” again, or if “APP_TARGET_NAME” is still running, you can attach to it by selecting Debug > Attach to Process > APP_TARGET_NAME. -- System Information macOS Version 11.4 Xcode 12.1 (17222) Please help me how to resolve the issue. A: This usually happens with apps with lots of dependencies so they take too long to launch, making the debugger to abort and time out. A temporary solution would be: * *Create (or edit in case you already have) a .lldbinit file in your home directory. vim ~/.lldbinit. *Add this to the end of file: settings set plugin.process.gdb-remote.packet-timeout 300. *Restart Xcode and try again. A: I have tried this way and it is working like uncheck debug executable option. Choose Edit Schema->Info->uncheck Debug executable
{ "language": "en", "url": "https://stackoverflow.com/questions/67937309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to open new tab on Chrome browser using Selenium I've tried the following solutions but it didn't work, I am using Selenium 3.9.1 and Chrome v66.0.3, do we have any other alternate solutions: Solution 1: driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "/t"); ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles()); driver.switchTo().window(tabs.get(1)); driver.get("http://google.com"); Solution 2: Actions act = new Actions(driver); act.keyDown(Keys.CONTROL).sendKeys("t").keyUp(Keys.CONTROL).build().perform(); A: The only way to open links in new tabs is by simulating key-board shortcuts. The following hold true in FFX, Chrome & IE * *Ctrl+t will open a blank new tab, and switch focus to it. *Holding Ctrl, then clicking the link will open the link in a new tab but leave focus on the existing tab. *Holding Ctrl AND Shift, then clicking will open the link in a new tab AND move focus onto the new tab. *Ctrl+w will close the current tab and switch focus to the last open tab (although note that Ctrl+W i.e. Ctrl+Shift+w will close ALL tabs!) Selenium doesn't (currently) have any concept of tabs within a browser window, so in order to open the tab and then test it you HAVE to use option 3. Try something like this: WebDriver driver = new ChromeDriver(); driver.get("http://yahoo.com"); ((JavascriptExecutor)driver).executeScript("window.open()"); ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles()); driver.switchTo().window(tabs.get(1)); driver.get("http://google.com"); P.S Look at here for this bug -> https://github.com/SeleniumHQ/selenium/issues/5462 A: Why not use JavaScriptExecutor to open a new window and switch to it? Now sure about the Java syntax, but in Protractor it may be something like this browser.executeScript('window.open()').then(function () { browser.getAllWindowHandles().then(function (handles) { var secondWindow = handles[1]; browser.ignoreSynchronization = true; browser.switchTo().window(secondWindow).then(function () { browser.get('https://google.com'); }); }); }); A: String baseUrl = "http://www.google.co.uk/"; driver.get(baseUrl); ((JavascriptExecutor) driver).executeScript("window.open()"); Set<String> tabs = new HashSet<String>(); tabs = driver.getWindowHandles(); List<String> li = new ArrayList<String>(tabs); driver.switchTo().window(li.get(1)); driver.get("https://www.fb.com");
{ "language": "en", "url": "https://stackoverflow.com/questions/50168773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Directive for loading forms into a single page app lost controller binding I'm creating a single page app using AngularJS. I have created a main page with a custom directive for loading a form URL. I want to change the the forms based on a variable in my controller. However, I lost my bindings once I compiled and linked the form from URL <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script> <div ng-app="tradesman" ng-controller="application" class="form-horizontal" role="form"> Hello {{applicant.name}} <my-form name="formName"> </my-form> </div> var tradesman = angular.module("tradesman") tradesman.controller("application",function application($scope){ $scope.formName="personals"; $scope.applicant={}; }); tradesman.directive("myForm",function($http,$compile){ return { restrict:"E", scope:false, replace:true, link:function(scope,element,attrs){ var url="http://tradesman.local/views/"+scope.formName+".html"; $http.get(url).then(function(response){ scope.$watch(function(){ element.html(response.data); $compile(element.contents())(scope); }); }); } }; }); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script> This has successfully loaded my personals page but lost the binding in that page. More over I want a new form to be loaded whenever I change my formName in controller. What needs to be done to make form loading and binding work simultaneously
{ "language": "en", "url": "https://stackoverflow.com/questions/39031135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setter Property Required primitive dependency is not explicitly defined I have Asp.Net MVC Application and I have used structuremap, I use custom ThrottleAttribute ActionFilter. follow rate limiting in asp.net mvc public enum TimeUnit { Minute = 60, Hour = 3600, Day = 86400 } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class ThrottleAttribute : ActionFilterAttribute { public TimeUnit Time { get; set; } public int Count { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var seconds = Convert.ToInt32(Time); var key = string.Join( "-", seconds, filterContext.HttpContext.Request.HttpMethod, filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName, filterContext.HttpContext.Request.UserHostAddress ); // increment the cache value var cnt = 1; if (HttpRuntime.Cache[key] != null) { cnt = (int)HttpRuntime.Cache[key] + 1; } HttpRuntime.Cache.Insert( key, cnt, null, DateTime.UtcNow.AddSeconds(seconds), Cache.NoSlidingExpiration, CacheItemPriority.Low, null ); if (cnt >= Count) { filterContext.Result = new ContentResult { Content = "You are allowed to make only " + Count + " requests per " + Time.ToString().ToLower() }; filterContext.HttpContext.Response.StatusCode = 429; } } } after I use ThrottleAttribute throw Exception: Setter Property 'Time' (ActionFilters.TimeUnit): Required primitive dependency is not explicitly defined And my ActionFilter Registry: public class ActionFilterRegisteryClass : StructureMap.Registry { public ActionFilterRegisteryClass(Func<StructureMap.IContainer> containerFactory) { For<IFilterProvider>().Use( new StructurMapFilterProvider(containerFactory)); Policies.SetAllProperties(x => { x.Matching(p => p.DeclaringType.CanBeCastTo(typeof(ActionFilterAttribute)) && ( p.DeclaringType.Namespace.StartsWith("MyNamespace") ) && !p.PropertyType.IsPrimitive && p.PropertyType != typeof(string) ); }); } } Exception is fire in: container.BuildUp(filter.Instance); public class StructurMapFilterProvider : FilterAttributeFilterProvider { private readonly Func<StructureMap.IContainer> _Container; public StructurMapFilterProvider(Func<StructureMap.IContainer> container) { _Container = container; } public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) { var filters = base.GetFilters(controllerContext, actionDescriptor); var container = _Container(); foreach (var filter in filters) { container.BuildUp(filter.Instance); yield return filter; } } } Setter Property 'Time' (ActionFilters.TimeUnit): Required primitive dependency is not explicitly defined What should I do? How explicitly defined PrimitiveTypes? A: The problem was in Registering ActionFilterClass in structuremap. I have changed it as follows: public class ActionFilterRegisteryClass : StructureMap.Registry { public ActionFilterRegisteryClass(Func<StructureMap.IContainer> containerFactory) { For<IFilterProvider>().Use( new StructurMapFilterProvider(containerFactory)); Policies.SetAllProperties(x => { x.Matching(p => p.DeclaringType.CanBeCastTo( !p.PropertyType.IsPrimitive && !p.PropertyType.IsEnum && p.PropertyType != typeof(string)); }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/40404444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Making Test(s) Fail if the `application-context` Encounters an Exception When running mvn clean install against my Maven project, Build Success showed up. However, running an individual test in IntelliJ showed that a test had failed since my test-application-context had encountered a RuntimeException. Since this application-context failed to start the test environment, a few Maven tests did not run since they depended on the test-application-context to start up. But, even though these tests were skipped, Build Success still appeared. I'd like Maven to fail those "skipped" tests if the application-context encounters a RuntimeException. How can I configure the POM to show these tests as failures?
{ "language": "en", "url": "https://stackoverflow.com/questions/25431757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stepper on tableview cell (swift) I put stepper both outlets and action into tableview cell and using protocol delegate to connect it to tableview. When i tapped stepper in first row, stepper value appear normaly in first row but its also appear in some random row. how to fix this? TableViewCell protocol ReviewCellDelegate{ func stepperButton(sender: ReviewTableViewCell) } class ReviewTableViewCell: UITableViewCell { @IBOutlet weak var countStepper: UIStepper! @IBOutlet weak var stepperLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func stepperButtonTapped(sender: UIStepper) { if delegate != nil { delegate?.stepperButton(self) stepperLabel.text = "x \(Int(countStepper.value))" } } ViewController func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "reviewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ReviewTableViewCell var imageView: UIImageView? let photoG = self.photos[indexPath.row] imageView = cell.contentView.viewWithTag(1) as? UIImageView //let layout = cell.goodiesImage let tag = indexPath.row // +1 cell.tag = tag photoG.fetchImageWithSize(CGSize(width: 1000, height: 1000), completeBlock: { image, info in if cell.tag == tag { imageView?.image = image cell.goodiesImage.image = image } }) func stepperButton(sender: ReviewTableViewCell) { if let indexPath = tableView.indexPathForCell(sender){ print(indexPath) } } A: Reset the value of stepper while loading your cell. you can reset the cell property values in cell's prepareForReuse method. add the following method in your ReviewTableViewCell class. override func prepareForReuse() { super.prepareForReuse() countStepper.value = 0.0 } A: In tableViewCell VC: 1 - add these field var cellDelegate: cellProtocol? var index: IndexPath? 2 - then add this in the delegate: func onStepperClick(index: Int, sender: UIStepper) 3 - when you have dragged your stepper over as an action use this: @IBAction func cellStepper(_ sender: UIStepper) { cellDelegate?.onStepperClick(index: (index?.row)!, sender: sender) sender.maximumValue = 1 //for incrementing sender.minimumValue = -1 //for decrementing //this will make sense later } In ViewController 1 - add these to the tableView function that has the cellAtRow variable. cell.cellDelegate = self cell.index = indexPath 2 - Use this instead of your stepperButton function func onStepperClick(index: Int, sender: UIStepper) { print(index) if sender.value == 1.0{ //positive side of stepper was pressed }else if sender.value == -1.0{ //negative side of stepper was pressed } sender.value = 0 //resetting to zero so sender.value produce different values on plus and minus } Hope this works for you A: As mentioned by @A-Live, your component is being reused and so need to be updated. So in your view controller: func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "reviewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ReviewTableViewCell var imageView: UIImageView? let photoG = self.photos[indexPath.row] imageView = cell.contentView.viewWithTag(1) as? UIImageView //let layout = cell.goodiesImage let tag = indexPath.row // +1 cell.tag = tag photoG.fetchImageWithSize(CGSize(width: 1000, height: 1000), completeBlock: { image, info in if cell.tag == tag { imageView?.image = image cell.goodiesImage.image = image } }) cell.countStepper.value = XXX[indexPath.row].value; //Here you update your view cell.stepperLabel.text = "x \(Int(cell.countStepper.value))" //And here And func stepperButton(sender: ReviewTableViewCell) { if let indexPath = tableView.indexPathForCell(sender){ print(indexPath) XXX[sender.tag].value = sender.counterStepper.value //Here you save your updated value } A: NOTE: 1.MY Cell class is just normal..All changes are in viewcontroller class 2.I have taken stepper and over it added ibAddButton with same constraint as ibStepper class cell: UITableViewCell { @IBOutlet weak var ibAddButton: UIButton! @IBOutlet weak var ibStepper: UIStepper! @IBOutlet weak var ibCount: UILabel! @IBOutlet weak var ibLbl: UILabel! } 1.define empty int array [Int]() var countArray = [Int]() 2.append countArray with all zeros with the number of data u want to populate in tableview for arr in self.responseArray{ self.countArray.append(0) } 3.in cell for row at func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cell let dict = responseArray[indexPath.row] as? NSDictionary ?? NSDictionary() cell.ibLbl.text = dict["name"] as? String ?? String() if countArray[indexPath.row] == 0{ cell.ibAddButton.tag = indexPath.row cell.ibStepper.isHidden = true cell.ibAddButton.isHidden = false cell.ibCount.isHidden = true cell.ibAddButton.addTarget(self, action: #selector(addPressed(sender:)), for: .touchUpInside) }else{ cell.ibAddButton.isHidden = true cell.ibStepper.isHidden = false cell.ibStepper.tag = indexPath.row cell.ibCount.isHidden = false cell.ibCount.text = "\(countArray[indexPath.row])" cell.ibStepper.addTarget(self, action: #selector(stepperValueChanged(sender:)), for: .valueChanged)} return cell } 4.objc functions @objc func stepperValueChanged(sender : UIStepper){ if sender.stepValue != 0{ countArray[sender.tag] = Int(sender.value) } ibTableView.reloadData() } @objc func addPressed(sender : UIButton){ countArray[sender.tag] = 1//countArray[sender.tag] + 1 ibTableView.reloadData() }
{ "language": "en", "url": "https://stackoverflow.com/questions/34872540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to fix a database login issue? I'm a beginner, and I want to ask about a problem I've got with my app. I try to log with the data I put into the database but it recognizes nothing. Here's the code of the DatabaseHelper Java file. I think the problem is with my checkData_pseudo_pass function. Thanks in advance for the response! DatabaseHelper.java package com.example.tp5; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "database.db"; public static final String TABLE_NAME = "tp4_table"; /* public static final String COL_1 = "ID"; public static final String COL_2 = "NOM"; public static final String COL_3 = "PRENOM"; public static final String COL_4 = "PSEUDO"; public static final String COL_5 = "PASS"; */ public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NOM TEXT,PRENOM TEXT,PSEUDO TEXT,PASS TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); onCreate(db); } public boolean InsererData(String nom, String prenom, String pseudo, String pass){ SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("nom",nom); contentValues.put("prenom",prenom); contentValues.put("pseudo", pseudo); contentValues.put("pseudo", pass); long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues); if(result == -1){ return false; }else{ return true; } } /* public boolean insertData(String nom, String prenom, String pseudo, String pass) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_2,nom); contentValues.put(COL_3,prenom); contentValues.put(COL_4,pseudo); contentValues.put(COL_5,pass); long result = db.insert(TABLE_NAME,null ,contentValues); if(result == -1) return false; else return true; } */ public Cursor getAllData() { SQLiteDatabase db = this.getWritableDatabase(); Cursor res = db.rawQuery("select * from "+TABLE_NAME,null); return res; } /* public Boolean checkData_Pass(String pass){ SQLiteDatabase db = this.getWritableDatabase(); Cursor res_pass = db.rawQuery("select * from tp4_table where PASS=? ",new String[]{pass}); if(res_pass.getCount()>0) return false; else { return true; } } */ public Boolean checkData_pseudo_pass(String pseudo, String pass){ SQLiteDatabase db = this.getReadableDatabase(); Cursor res_unique = db.rawQuery("select * from tp4_table where PSEUDO=? and PASS=?", new String[]{pseudo, pass}); if(res_unique.getCount()>0) return false; else { return true; } } } MainActivity3.java package com.example.tp5; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity3 extends AppCompatActivity{ DatabaseHelper myDb_connexion; // création de l'objet mydb de type DatabaseHelper private Button valider_connexion2 = null; private EditText pseudo_connexion = null; private EditText pass_connexion = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activitymain3); myDb_connexion = new DatabaseHelper(this); valider_connexion2 = findViewById(R.id.button3); pseudo_connexion = findViewById(R.id.edit_pseudo_connexion); pass_connexion = findViewById(R.id.edit_pass_connexion); //EditText textView_pseudo = (EditText) findViewById(R.id.edit_pseudo_connexion); //EditText textView_pass = (EditText) findViewById(R.id.edit_pass_connexion); valider_connexion2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String _str_pseudo = pseudo_connexion.getText().toString().trim(); String _str_pass = pass_connexion.getText().toString().trim(); Intent intent3 = new Intent(MainActivity3.this, MainActivity4.class); Boolean check_Pseudo_Pass = myDb_connexion.checkData_pseudo_pass(_str_pseudo, _str_pass); //Si Check_Pseudo_Pass affiche le pseudo et le pass //if (check_Pseudo_Pass == true && !str_pseudo.equals("") && !str_pass.equals("")) if (check_Pseudo_Pass == true) { intent3.putExtra("pseudo", _str_pseudo); intent3.putExtra("pass", _str_pass); startActivity(intent3); Toast.makeText(MainActivity3.this,"Connexion réussie !",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity3.this,"Connexion raté !",Toast.LENGTH_SHORT).show(); } // Question 7:Connexion unique Login="Admin",pass="root" et Extra enregistre le pseudo et le mot de passe pour le récupérer à la pas MainActivité /* Intent intent3 = new Intent(MainActivity3.this, MainActivity4.class); // if (!str_pseudo.equals("") && !str_pass.equals("") ) { if (str_pseudo.equals("Admin") && str_pass.equals("root") ) { intent3.putExtra("pseudo", str_pseudo); intent3.putExtra("pass", str_pass); Toast.makeText(MainActivity3.this,"Connexion réussie !",Toast.LENGTH_SHORT).show(); startActivity(intent3); }else{ Toast.makeText(MainActivity3.this,"Connexion raté !",Toast.LENGTH_SHORT).show(); } */ } }); } } A: Consider this method: public Boolean checkData_pseudo_pass(String pseudo, String pass){ SQLiteDatabase db = this.getReadableDatabase(); Cursor res_unique = db.rawQuery("select * from tp4_table where PSEUDO=? and PASS=?", new String[]{pseudo, pass}); if (res_unique.getCount() > 0) { return false; } else { return true; } } This returns false if any of the rows in tp4_table matches the given pseudo and pass and true otherwise. In other words, it fails if the username and password are correct. The logic of the test is backwards. It should be: if (res_unique.getCount() > 0) { return true; } else { return false; } or better still, just this: return res_unique.getCount() > 0; If you still have a problem after this change, then it is somewhere else in the code. For example, you may not have populated the database correctly. And you should return boolean not Boolean. And you should fix the numerous stye errors in your code, starting the many cases of identifiers that do not follow the style rules: * *variable names and method names start with a lowercase letter *no underscores (_) as in variable names, method names, class names or package names *use camel case instead of underscores between words (except for constant names).
{ "language": "en", "url": "https://stackoverflow.com/questions/59705029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: QT Compile on Linux: Cross Compilation failed with mxe / mingw / Linux, Debian I cannot compile the Windows Wallet, it shows me everytime this Error: What have I missed here? I am Using Debian. Source Code: https://github.com/rat4/blackcoin Content of compile-gtc.sh: #!/bin/bash MXE_INCLUDE_PATH=/mnt/mxe/usr/i686-w64-mingw32.static/include MXE_LIB_PATH=/mnt/mxe/usr/i686-w64-mingw32.static/lib i686-w64-mingw32.static-qmake-qt5 \ BOOST_LIB_SUFFIX=-mt \ BOOST_THREAD_LIB_SUFFIX=_win32-mt \ BOOST_INCLUDE_PATH=$MXE_INCLUDE_PATH/boost \ BOOST_LIB_PATH=$MXE_LIB_PATH \ OPENSSL_INCLUDE_PATH=$MXE_INCLUDE_PATH/openssl \ OPENSSL_LIB_PATH=$MXE_LIB_PATH \ BDB_INCLUDE_PATH=$MXE_INCLUDE_PATH \ BDB_LIB_PATH=$MXE_LIB_PATH \ MINIUPNPC_INCLUDE_PATH=$MXE_INCLUDE_PATH \ MINIUPNPC_LIB_PATH=$MXE_LIB_PATH \ QMAKE_LRELEASE=/mnt/mxe/usr/i686-w64-mingw32.static/qt5/bin/lrelease blackcoin-qt.pro make -f Makefile.Release After some minutes i started ./compile-gtc.sh I got this Error: /mnt/mxe/usr/i686-w64-mingw32.static/lib/libdb_cxx.a(os_pid.o):os_pid.c:(.text+0x25): undefined reference to `pthread_self' collect2: error: ld returned 1 exit status Makefile.Release:427: recipe for target 'release/blackcoin-qt.exe' failed make: *** [release/blackcoin-qt.exe] Error 1 Thank you,
{ "language": "en", "url": "https://stackoverflow.com/questions/41485979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }