input
stringlengths
51
42.3k
output
stringlengths
18
55k
"Authorization has been denied for this request" in production environment only <p>I'm using WebAPI and Owin with the following authentication setup. Locally, I can register, get a token, and make API requests that have the [Authorize] annotation on them. In production, I can register <strong>and get a token</strong>, but I get the error in the title when I try to hit an endpoint with the [Authorize] annotation.</p> <p>Given that it works locally, I'm skeptical that it's a code problem. And I build and deploy all .dlls to the production server, so the references should all be the same version. Could it be a difference in IIS configuration? Comparing the two, I don't see anything jumping out at me, but I could be missing something.</p> <p>And in case it matters, I use Web Deploy from Visual Studio to push the site to production. I also use the exact same web.config for both environments, except that I transform the connection string for production.</p> <p><strong>Startup.cs</strong></p> <pre><code>[assembly: OwinStartup(typeof(MyProject.API.Startup))] namespace MyProject.API { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } } </code></pre> <p><strong>App_Start\Startup.Auth.cs</strong></p> <pre><code>namespace MyProject.API { public partial class Startup { public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } public static string PublicClientId { get; private set; } public void ConfigureAuth(IAppBuilder app) { // Allow access_token to be passed as a query parameter app.Use(async (context, next) =&gt; { if (context.Request.QueryString.HasValue) { if (string.IsNullOrWhiteSpace(context.Request.Headers.Get("Authorization"))) { var queryString = HttpUtility.ParseQueryString(context.Request.QueryString.Value); string token = queryString.Get("access_token"); if (!string.IsNullOrWhiteSpace(token)) { context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) }); } } } await next.Invoke(); }); app.CreatePerOwinContext(MyProjectDbContext.Create); app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; app.UseOAuthBearerTokens(OAuthOptions); } } } </code></pre> <p><strong>Global.asax.cs</strong></p> <pre><code>protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); DependencyInjectorConfig.RegisterDependencies(); MappingConfig.RegisterMappings(); // Autofac stuff Database.SetInitializer(new MyProjectInitializer()); } </code></pre>
<p>Ah! The login call was using the LOCAL api, while the rest of the routes were using the production api. Fixing that solved my problem.</p>
Spring integration kafka how to handle error when produce to kafka <p>While using int-kafka:outbound-channel-adapter to produce to kafka, there seems no error-channel available. In this case how to handle message failed to produce to kafka after reties times?</p> <p>Any error that could cause produce to kafka failure. (Following code just code snippet from internet, just wondering how to add error handle to it)</p> <pre><code>&lt;int-kafka:outbound-channel-adapter id="kafkaOutboundChannelAdapter" kafka-producer-context-ref="kafkaProducerContext" auto-startup="true" channel="inputToKafka" topic="test"&gt; &lt;int:poller fixed-delay="1000" time-unit="MILLISECONDS" receive-timeout="0" task-executor="taskExecutor"/&gt; &lt;/int-kafka:outbound-channel-adapter&gt; &lt;task:executor id="taskExecutor" pool-size="5" keep-alive="120" queue-capacity="500"/&gt; &lt;int-kafka:producer-context id="kafkaProducerContext" producer-properties="producerProps"&gt; &lt;int-kafka:producer-configurations&gt; &lt;int-kafka:producer-configuration broker-list="XXXXXX:6667" key-class-type="java.lang.String" value-class-type="java.lang.String" topic="rating" value-serializer="kafkaSerializer" key-serializer="kafkaSerializer" compression-type="none"/&gt; &lt;/int-kafka:producer-configurations&gt; &lt;/int-kafka:producer-context&gt; &lt;util:properties id="producerProps"&gt; &lt;prop key="queue.buffering.max.ms"&gt;500&lt;/prop&gt; &lt;prop key="topic.metadata.refresh.interval.ms"&gt;3600000&lt;/prop&gt; &lt;prop key="queue.buffering.max.messages"&gt;10000&lt;/prop&gt; &lt;prop key="retry.backoff.ms"&gt;100&lt;/prop&gt; &lt;prop key="message.send.max.retries"&gt;2&lt;/prop&gt; &lt;prop key="send.buffer.bytes"&gt;5242880&lt;/prop&gt; &lt;prop key="socket.request.max.bytes"&gt;104857600&lt;/prop&gt; &lt;prop key="socket.receive.buffer.bytes"&gt;1048576&lt;/prop&gt; &lt;prop key="socket.send.buffer.bytes"&gt;1048576&lt;/prop&gt; &lt;prop key="request.required.acks"&gt;1&lt;/prop&gt; &lt;/util:properties&gt; </code></pre>
<p>Please, follow answers to this question <a href="http://stackoverflow.com/questions/39915579/exception-handling-in-int-jpaupdating-outbound-gateway">exception handling in int-jpa:updating-outbound-gateway</a>. </p> <p>Since you have there <code>&lt;polled&gt;</code>, you can specify <code>error-channel</code> and handle errors in the flow on that channel. </p>
Wrapping a #include directive for a standard C++ header in extern "C" { ... }? <p>I recently saw this block at the beginning of a <code>.h</code> file.</p> <pre><code>#ifdef __cplusplus extern "C" { #include &lt;cstddef&gt; #include &lt;cstdint&gt; #else #include &lt;stddef.h&gt; #include &lt;stdint.h&gt; #endif /* __cplusplus */ </code></pre> <p>Does wrapping a <code>#include</code> directive for a standard C++ header in <code>extern "C" { ...</code> actually do anything? Is it functionally different from:</p> <pre><code>#ifdef __cplusplus #include &lt;cstddef&gt; #include &lt;cstdint&gt; extern "C" { #else #include &lt;stddef.h&gt; #include &lt;stdint.h&gt; #endif /* __cplusplus */ </code></pre> <p>I was under the impression that this makes no difference, but I'm seeing it so often I am becoming curious.</p>
<p>Based on the "If ...def" statement in that header file, the </p> <p>"if" block : "if you use the particular header file in C++" </p> <p>"else" block : "if you use the particular header file not in C++, could be C"</p> <p>if you do not wrap the headers in "extern C" in the "if" block(which is meant for C++), the "C" linkage wont be maintained for the function names.</p> <p>"C" do not have function over loading concept, but where as C++. So C++ compiler does some function name mangling for "extern C" functions.</p> <p>Here is a very nice article. In C++ source, what is the effect of extern “C”? - in stack over flow.</p> <p>For regular standard C libraries, the extern wrapper not required. Mostly it is taken care by standard C.</p> <p>ex: something like below (yvals.h on windows).</p> <pre><code> #define _C_LIB_DECL extern "C" { /* C has extern "C" linkage */ #define _END_C_LIB_DECL } #define _EXTERN_C extern "C" { #define _END_EXTERN_C } </code></pre>
How to ignore dashes or hyphens in JS comparisons <p>I want to compare two input values on a page. One input value is always entered with hyphens as spaces. ie "first-value" The other input value is never entered with hyphens as spaces. ie "first value"</p> <p>"first-test" == "first test" this views them as different. Is there an operator that would view these as the same?</p>
<p>Dashes may come in more varieties thank you'd expect. Especially if people copy/paste their input from MS Word and the likes. For example, would you consider - or ‐ or ‑ or ‒ or – or — or ― all to be dashes? (they're all different unicode characters)</p> <p>If the parts that you care about are only alphanumeric, you're better off stripping away everything else.</p> <p>Do you regard <code>first-test</code> and <code>firs ttest</code> to be equal? If yes, then simply removing all non-alphanumeric chars will do:</p> <pre class="lang-js prettyprint-override"><code>str1 = str1.replace(/[^a-z0-9]/gi,''); str2 = str2.replace(/[^a-z0-9]/gi,''); var doMatch = (str1 == str2); </code></pre> <p>If no, then replace all non-alphanumeric parts with single spaces:</p> <pre class="lang-js prettyprint-override"><code>str1 = str1.replace(/[^a-z0-9]+/gi,' '); str2 = str2.replace(/[^a-z0-9]+/gi,' '); // trim to ignore space at begin or end str1 = str1.replace(/^\s+|\s+$/g,''); str2 = str2.replace(/^\s+|\s+$/g,''); var doMatch = (str1 == str2); </code></pre> <p>This also allows for people copy/pasting values with an accidental extra space at the end. Which sometimes happens but is barely noticeable, and could cause lots of headaches if you consider that different.</p>
How to show both markers on Google Maps? <p>I have a maps activity that displays an origin and a destination location (Point A and Point B). However, when the origin and destination locations are inputted. Only the Origin is displayed initially. You would have to zoom out to see the destination on the map. How can I show both markers at the same time? </p> <p>I would like it to fill the entire fragment</p>
<p>You need to set up a LatLng bounds to fit all of your points (in this case, just two) within the Map's camera. Take this code for example:</p> <pre><code>final LatLngBounds.Builder builder = new LatLngBounds.Builder(); builder.include(markerA.getPosition()); // this is a LatLng value builder.include(markerB.getPosition()); mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100)); </code></pre>
Time Complexity of a recursive Reverse String <p>I want to find the Time complexity in Big O of the following code:</p> <pre><code>ReverseString(S,x,y) if x &lt; y swap(S,x,y) return ReverseString(S,x+1,y-1) </code></pre> <p>The equation I got was </p> <pre><code>T(1) = 1 T(n) = 3 + T(n+1)+ T(n-1) </code></pre> <p>If I'm right how would I go about solving this.</p> <p>If I'm not right what is the correct equation.</p>
<p>Assuming that x and y are pointers to string ends, then your equation is wrong. This is a simple, single recursion, but you've assumed double. Also, there is the serious problem of making T(n) depend on T(n+1); you really don't want to go <em>up</em> in subscripts without a guaranteed, finite bounded decrease.</p> <p>Think this way: each iteration gets x and y closer to each other by one character on each end. Your single recursion loops through the halves of the string. I would put the relation as</p> <pre><code>T(n) = 3 + T(n-1) </code></pre> <p>where n is half the length of the string (truncated if odd).</p>
Open a file in linux machine on a Mac Text Editor <p>I have problem with my <strong>FTP client</strong>, so that's not an option. </p> <hr> <p>I SSH into my Ubuntu server, and tried to open up a file with my Mac Text editor application such <strong>Text Edit</strong>, or <strong>Sublime Text</strong>. </p> <p>Is there a command that will help me do that ?</p> <p>I would do this - if I am on a Mac</p> <pre><code>open -a TextEdit /home/forge/rsm/resources/views/layouts/internal/master2/dashboard.blade.php </code></pre> <p>Any directions on this will be great !!</p>
<p>Try using sshfs. Mount the Linux drive on your system and then you will be able to use the folders like there were local. This will allow you to open the file. </p>
Is it possible to create an auto scaling Elastic Beanstalk without a load balancer? <p>We have an application which consists of an API and many microservices. The API writes to queues from which the microservices are listening. We currently have 25 microservices - none of which need load balancers. At the cost of nearly 5k per year, we'd like to do without these microservice load balancers if possible. The difficulty is that these microservices need to be autoscaled based on CPU usage - so simply setting the application to single-instance environment as described <a href="http://stackoverflow.com/questions/8014046/elastic-beanstalk-without-elastic-load-balancer">here</a> won't cut it.</p> <p>Is there any way to have an autoscaling elastic beanstalk group which does not have a load balancer? We're using CloudFormation to describe our deployments and would like to remove the load balancer via our cloudformation template. I've gone through the <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html" rel="nofollow">command option descriptions</a> and can't seem to find anything which fits this use case.</p>
<p>You need to make a worker tier in Elastic Beanstalk. So no loadbalancer would be needed. This page describes it in detail. </p> <p><a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features-managing-env-tiers.html" rel="nofollow">http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features-managing-env-tiers.html</a></p>
Responsive banner image for all resolutions <p>I am trying to have a banner image, spanning 100% width of the screen An example of what I want to achieve is found here:</p> <p><a href="http://www.aha.io/roadmapping/where-aha-fits" rel="nofollow">http://www.aha.io/roadmapping/where-aha-fits</a></p> <p>Look at it in full screen. The banner is 100% width, and maybe 15% of the screen height.</p> <p>When you shrink the window size, the banner still uses 100% of the screen width, but seems to crop the left size, I think, and reduced in height, maintaining the screen height of around 15%. </p> <p>I created a demo of what I am trying to do here:</p> <p><a href="http://www.bootply.com/Hrxwy8BjTT" rel="nofollow">http://www.bootply.com/Hrxwy8BjTT</a></p> <p>What I end up with is, in 'mobile' version, a very very thin banner.</p> <p>How can I make it crop a bit, and maintain around 10% (in my case) of the screen height (And not creating a scroll bar)?</p>
<p>This would be a good case to use Media Queries.The code below targets specific widths in a mobile-first pattern. This way the style for #background depends on the width of the device.</p> <pre><code>#background { background: url(http://snowdebts.com/images/banner-thin.png); background-position: center; background-size: cover; height: 225px; width: 100%; } @media (min-width: 480px) { #background { height: 200px; } } @media (min-width: 768px) { #background { height: 150px; } } @media (min-width: 992px) { #background { height: 100px; } } </code></pre> <p>I took the liberty of removing your image tag, and setting it in CSS instead. So, for your HTML, you need the following:</p> <pre><code> &lt;div class="tab-content"&gt; &lt;div id="background"&gt; &lt;/div&gt; &lt;div style="padding-left: 20px;"&gt; Hello &lt;/div&gt; &lt;/div&gt; </code></pre> <p>You can modify the heights into percentages or fixed widths depending on what you need. Also, since we've set up the image as a background for the div element, we don't need to worry about the scroll bar, just the size of the div.</p>
Transition from tableView to detailView passing Firebase data <p>I have a current app which displays articles in a tableview like so: </p> <p><img src="http://i.stack.imgur.com/VqHtv.jpg" alt="TableView"></p> <p>The data is displayed correctly, however, when I tap each cell, it does not populate with the corresponding data. Instead, it populates with the most recent data added into the database. I am currently using the following to populate the detail view. </p> <pre><code>import UIKit import FirebaseStorage import FirebaseDatabase class Article: UIViewController { var roomId: String! var rooms = [Room]() @IBOutlet weak var thumbTitle: UITextView! @IBOutlet weak var thumbContent: UITextView! @IBOutlet weak var thumbImage: UIImageView! @IBOutlet weak var thumbAuthor: UITextField! @IBOutlet weak var thumbDate: UITextField! override func viewDidLoad() { super.viewDidLoad() self.navigationController!.navigationBar.barTintColor = UIColor(red:0.65, green:0.10, blue:0.18, alpha:1.0) Data.dataService.fetchData { (room) in self.rooms.append(room) self.configureView(room) } } func configureView(_ room: Room) { self.thumbTitle.text = room.title self.thumbDate.text = room.date self.thumbAuthor.text = room.author self.thumbContent.text = room.story if let imageURL = room.thumbnail { if imageURL.hasPrefix("gs://") { FIRStorage.storage().reference(forURL: imageURL).data(withMaxSize: INT64_MAX, completion: { (data, error) in if let error = error { print("Error downloading: \(error)") return } self.thumbImage.image = UIImage.init(data: data!) }) } else if let url = URL(string: imageURL), let data = try? Foundation.Data(contentsOf: url) { self.thumbImage.image = UIImage.init(data: data) } } } } </code></pre> <p>Thank you all for your help! </p> <p><strong>EDIT</strong>:</p> <p>This is the <code>fetchData()</code> func: </p> <pre><code> func fetchData(_ callback: @escaping (Room) -&gt; ()) { Data.dataService.ROOM_REF.observe(.childAdded, with: { (snapshot) in let room = Room(key: snapshot.key, snapshot: snapshot.value as! Dictionary&lt;String, AnyObject&gt;) callback(room) }) } </code></pre>
<p>I assume the code you are providing is the one for your detail controller.</p> <p>Seems like you don't give parameter to <code>Data.dataService.fetchData</code>, you're probably returning a 'room' independently of the detail you're in. I recommend you to read some documentation or tutorials about how to pass data between 2 controllers.</p> <p><a href="http://stackoverflow.com/questions/28430663/send-data-from-tableview-to-detailview-swift">Send data from TableView to DetailView Swift</a></p> <p><a href="https://www.appcoda.com/storyboards-ios-tutorial-pass-data-between-view-controller-with-segue/" rel="nofollow">https://www.appcoda.com/storyboards-ios-tutorial-pass-data-between-view-controller-with-segue/</a></p> <p>EDIT:</p> <p>You should pass an object or datas directly to your detail view controller in the performseguewithidentifier() method in your parent view (where you should already have this to initialize your cells).</p>
How to upgrade openssl 0.9.8 to 1.0.2 with mod_ssl in Apache 2.2.9 <p>I am asked to recompile <code>mo_ssl</code> with openssl 1.0.2 in SuseSE11SP3. However, I am a newbie to Suse, but know a little bit of linux. </p> <ul> <li>OS : Suse SE11SP3 </li> <li>Openssl : 0.9.8j &lt;-which comes with original Suse linux</li> <li>Web Server : Apache httpd 2.2.9</li> </ul> <p>Here is limitation I have. I cannot use <code>zypper</code> or <code>rpm</code> because company security policy does not allow me to do it. It is absurd, this is how it goes here. Another limitation I have is this system is used by other web servers which I don't have permission. I have to make it as locally as possible. </p> <p>What I want it to happen is that when I recompile apache server, I like to see <code>mod_ssl</code> is linked to newer version Openssl library. </p> <p>So, I downloaded Openssl 1.0.2h source file:</p> <pre><code>./confgiure --prefix=//PREFIX/openssl --opendir=/PREFIX/openssl make test make install </code></pre> <p>Successfully, I installed openssl on local directory. </p> <p>and then I attempted to recompile httpd2.2.9 which already exists. so I went to source file in httpd 2.2.9</p> <pre><code>make clean export LIBS=-ldl export LD_LIBRARY_PATH="/PREFIX/openssl" export LIBS="-L/PREFIX/openssl" export CPPFLAGS="-I/PREFIX/include/openssl" ./configure --prefix=/PREFIX/apache22 --enable-so --enable-ssl=ssl -with-ssl=/PREFIX/openssl --enable-module=shared CC=/usr/bin/gcc make install </code></pre> <p>There were some errors but I kind of figured out and make it compiled. However, the final result for <code>mod_ssl</code> is still linked to old Openssl 0.9.8 instead of newer version 1.0.2h </p> <p>What did I miss in these steps? Or where did I go wrong?</p> <hr> <pre><code>//openssl install ./config -fPIC shared --prefix=/PREFIX/openssl --openssldir=/PREFIX/openssl make make test make install // install apache2 //recompiling after apache2 is installed with openssl export LIBS=-ldl export LD_LIBRARY_PATH="/PREFIX/openssl/lib" export LDFLAGS="-L/PREFIX/openssl" export CPPFLAGS="-I/PREFIX/openssl/include/openssl" export CFLAGS="-Wl,-rpath=/PREFIX/openssl:/usr/lib -I/PREFIX/openssl/include/openssl" ./configure --prefix=/PREFIX/apache22 --enable-so --enable-ssl=shared -with-ssl=/PREFIX/openssl --enable-module=shared CC=/usr/bin/gcc make make install </code></pre> <p>The above command creates mod_ssl.so under "apache22/modules" but when I did ldd mod_ssl.so it came out like the following</p> <pre><code>linux-vdso.so.1 =&gt; (0x00007fffef8f2000) libssl.so.1.0.0 =&gt; not found libcrypto.so.1.0.0 =&gt; not found libpthread.so.0 =&gt; /lib64/libpthread.so.0 (0x00007ffe6a48d000) libc.so.6 =&gt; /lib64/libc.so.6 (0x00007ffe6a116000) /lib64/ld-linux-x86-64.so.2 (0x00007ffe6a913000) </code></pre> <p>libssl.so, libcrypto.so is not linked .. I don't know whatelse I can do it here to link mod_ssl.so to different version of openssl. </p> <p>please help me. </p>
<p>Due to Alvits's help, I could write this answer in stackoverflow for the first time. </p> <p><strong>!! Kudos to Alvits !!</strong></p> <p>My original task was that I need to install different version of openssl in local direcotry which is different from system openssl. But I like to make mod_ssl which is linked to newer openssl. </p> <p>First, I installed openssl with shared option, which I originally forgot about it and mod_ssl was not created. so be careful not forgetting it. </p> <pre><code>cd openssl_source_direcotry ./config -fPIC shared --prefix=/PREFIX/openssl --openssldir=/PREFIX/openssl make make test make install </code></pre> <p>Next step, I added some environment variables. PREFIX is my local directory. When you install please use different name instead of PREFIX. </p> <pre><code>export LIBS=-ldl export LD_LIBRARY_PATH="/PREFIX/openssl/lib" export LDFLAGS="-L/PREFIX/openssl" export CPPFLAGS="-I/PREFIX/openssl/include/openssl" export CFLAGS="-Wl,-rpath=/PREFIX/openssl/lib:/usr/lib -I/PREFIX/openssl/include/openssl" </code></pre> <p>Next step is to recompile apache server. I assumed that apache server is already installed on your server. </p> <pre><code>./configure --prefix=/PREFIX/apache22 --with-apr=/PREFIX/apache22/bin --with-apr-util=/PREFIX/apache22/bin --enable-so --enable-ssl=shared -with-ssl=/PREFIX/openssl --enable-module=shared CC=/usr/bin/gcc make install </code></pre> <p>Next, go to apache22/modules to confirm whether mod_ssl.so is correctly linked. </p> <pre><code>ldd mod_ssl.so linux-vdso.so.1 =&gt; (0x00007fff823ff000) libssl.so.1.0.0 =&gt; /PREFIX/openssl/lib/libssl.so.1.0.0 (0x00007fb3b32d4000) libcrypto.so.1.0.0 =&gt; /PREFIX/openssl/lib/libcrypto.so.1.0.0 (0x00007fb3b2e8c000) libpthread.so.0 =&gt; /lib64/libpthread.so.0 (0x00007fb3b2c3e000) libc.so.6 =&gt; /lib64/libc.so.6 (0x00007fb3b28c7000) libdl.so.2 =&gt; /lib64/libdl.so.2 (0x00007fb3b26c2000) /lib64/ld-linux-x86-64.so.2 (0x00007fb3b377d000) </code></pre> <p>One more tiem, I really appreciate Alvits for his help. without his help, I couldn't make this far. </p>
C# WPF Prism ViewModelLocator in different Class Libraries/Projects <p>is there a way for the Prism ViewModelLocator to autowire the views and viewmodels from different class library beside just the WPF project?</p> <p>Currently my WPF MainWindow.xaml is in a Views folder in the WPF project and is auto wired to link with MainWindowViewModel in a ViewModels folder. The datacontext is wired and works fine.</p> <p>My MainWindow view used other views(usercontrols) that's in a class library and the Prism ViewModelLocactor doesnt seem to auto wire the views and viewmodels. Is there a way for this to work? The datacontext is link if I manually inject the viewmodels, but once I comment the code and expect Prism to handle it, the datacontext is not wired.</p>
<p>Yes. Either change the ViewModelLoctor convention to fit your needs, or use the ViewModelLocationProvider.Register method to specify which VM should be used for a view.</p> <p><a href="http://brianlagunas.com/getting-started-prisms-new-viewmodellocator/" rel="nofollow">http://brianlagunas.com/getting-started-prisms-new-viewmodellocator/</a></p>
Aggregate/project sub-document as top-level document in mongo <p>After a few aggregation steps (pipeline steps) in one of my collections, I'm ending up with the following result:</p> <pre><code>{ "_id" : ObjectId("574e7722bffe901713d383bb"), "eventname" : "Ball Passed", "command" : { "_id" : ObjectId("57ec6b6f6c61e919b578fe7c"), "name" : "Run", "strike" : 15, "score" : true, "duration" : 123 } } { "_id" : ObjectId("57ec6b6f6c61e919b578ff8a"), "eventname" : "Ball Passed", "command" : { "_id" : ObjectId("573d688d080cc2cbe8aecbbc"), "name" : "Run", "strike" : 12, "score" : false, "duration" : 597 } } </code></pre> <p>Which is fine! </p> <p>However, in the next step of the aggregation, I'd like to get the following result:</p> <pre><code>{ "_id" : ObjectId("57ec6b6f6c61e919b578fe7c"), "name" : "Run", "strike" : 15, "duration" : 123 } { "_id" : ObjectId("573d688d080cc2cbe8aecbbc"), "name" : "Run", "strike" : 12, "duration" : 597 } </code></pre> <p>If you have notices, the <code>command</code> field should become the top-level document, and <code>command.score</code> should be skipped.</p> <p>How can I achieve this in a single step? If that is not possible in a single step, then in multiple steps? I guess I've to use <code>$project</code>?</p>
<p>As you have guessed, <code>$project</code> allows you to do that:</p> <pre><code>db.col.aggregate([ { $project : { _id: "$command._id", name: "$command.name", strike: "$command.strike", duration: "$command.duration" } } ]).pretty() </code></pre> <p>I inserted your previous results and the above query returned this:</p> <pre><code>{ "_id" : ObjectId("57ec6b6f6c61e919b578fe7c"), "name" : "Run", "strike" : 15, "duration" : 123 } { "_id" : ObjectId("573d688d080cc2cbe8aecbbc"), "name" : "Run", "strike" : 12, "duration" : 597 } </code></pre> <p>So <em>piping</em> your query with this <code>$product</code> should produce the result you are looking for.</p> <h1>Update after comments</h1> <p>If the exact structure is not your main concern, but rather the exclusion of few fields (wihtout having to list all fields to include), then you may use <code>find()</code> instead of <code>aggregate()</code>. </p> <p><code>aggregate</code>'s product only lets you exclude _id. This means you need to manually list all fields to include.</p> <p><code>find</code> however, lets you list the fields to hide.</p> <h3>Alternative</h3> <p><strong>(1)</strong> You could redirect your aggregate result to another collection using <a href="https://docs.mongodb.com/v3.2/reference/operator/aggregation/out/" rel="nofollow">$out</a> :</p> <pre><code>{ $out : "commands" } </code></pre> <p><strong>(2)</strong> Even though the structure won't be exactly as you'd like, you'll then be able to do a <code>find</code> query and hide fields: </p> <pre><code>db.commands.find({}, {_id:0, "command.score":0, eventname:0}).pretty() </code></pre> <p>It returns this, which is pretty close to what you were looking for:</p> <pre><code>{ "command" : { "_id" : ObjectId("57ec6b6f6c61e919b578fe7c"), "name" : "Run", "strike" : 15, "duration" : 123 } } </code></pre>
drawLayer:inContext not displaying drawing <p>I'm trying to draw a blue circle inside a <em>UIView</em> subclass on Xcode 8, Swift 3. Inside a Cocoa Touch file that I'm using as the class for a <em>View</em> object in the <em>Storyboard</em>, I wrote the following code, but the circle is not displayed:</p> <pre><code>import UIKit class testView: UIView { override func draw(_ layer: CALayer, in ctx: CGContext) { ctx.addEllipse(in: CGRect(x: 0, y: 0, width: 100, height: 100)) ctx.setFillColor(UIColor.blue.cgColor) ctx.fillPath() } } </code></pre> <p>This version with <em>UIKit</em> doesn't display the circle neither:</p> <pre><code>override func draw(_ layer: CALayer, in ctx: CGContext) { UIGraphicsPushContext(ctx) let p = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100)) UIColor.blue.setFill() p.fill() UIGraphicsPopContext() } </code></pre> <p>What am I doing wrong?</p> <p>Thanks!</p>
<p>I was working on your question and this are my results, first of all you need to get you CurrentGraphicsContent, if you don't do this, you can't draw anything, so try with this code</p> <pre><code>override func draw(_ rect: CGRect) { super.draw(rect) if let ctx = UIGraphicsGetCurrentContext() { ctx.setFillColor(UIColor.blue.cgColor) ctx.addEllipse(in: CGRect(x: 0, y: 0, width: 100, height: 100)) ctx.fillPath() UIGraphicsEndImageContext() } // Drawing code } </code></pre> <p>I hope this helps you</p>
Trying to scan values with scanf within a loop. Requires secondary input to print the first input <p>I'm having trouble with scanf (and before anyone mentions it, I have to use it. I can't use <code>getchar()</code>, <code>fgets()</code>, and various other things). In my code below, I need to add (or subtract) two real numbers or integers, and store the sum to memory. I think I can sort out the memory stuff myself, but the problem is with printing the result of the sum.</p> <p>I have to type '6+6', press enter, and then input another character for the original sum to be displayed. Also if I type '6+6+' the program acts I want it to. </p> <p>I imagine I've made a very basic error. I'm very tired.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(){ char memoryExitSwitch[256]; int q =1; double operandOneHalf; double operandTwo; double result = 0.0; while(q == 1){ scanf("%lf" "%lf ", &amp;operandOneHalf, &amp;operandTwo); scanf( " %s", memoryExitSwitch); switch (memoryExitSwitch[0]) { case 'p': result = memoryExitSwitch[1] + operandTwo; printf("ANS1= %lf\n", result); memoryExitSwitch[1] = result; break; case 'q': q = 0; break; default: result = operandOneHalf + operandTwo; printf("ANS2= %lf\n", result); memoryExitSwitch[1] = result; break; }//switch }//main while loop q return 0; } </code></pre>
<p>Various problems</p> <ol> <li><p>The trailing space <code>"%lf "</code> obliges <code>scanf()</code> to detect following non-white-space after the number, delaying <code>scanf()</code> return. <a href="http://stackoverflow.com/questions/39968870/trying-to-scan-values-with-scanf-within-a-loop-requires-secondary-input-to-prin/39969571#comment67217567_39968870">@Jonathan Leffler</a>. The <code>" "</code> says to consume all optional following white-space. <code>scanf()</code> needs to see some non-white-space to know it has seen all the following white-space.</p> <pre><code>// scanf("%lf" "%lf ", &amp;operandOneHalf, &amp;operandTwo); // v--- no space if (scanf("%lf" "%lf", &amp;operandOneHalf, &amp;operandTwo) != 2) return -1; </code></pre></li> <li><p>Good code limits the input width to prevent buffer overflow</p> <pre><code>char memoryExitSwitch[256]; // scanf( " %s", memoryExitSwitch); // v ---- space not needed // |255 - lit input to 1 less than buffer size // | | v--- Check result if (scanf( "%255s", memoryExitSwitch) != 1) return -1; </code></pre></li> </ol>
How can i get 2 classes by id inside the same function <p>I need to target two div elements and toggle their classes simultanouesly.</p> <p>I understand that I can get multiple divs "by ID" by using <code>.querySelectorAll</code></p> <p>but when I get to <code>.classlist.toggle ("NewClassName");</code> how can I target two classes??</p> <p>So here's some code: </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#small-div{ background-color:#aaaaaa; border: 3px solid #aaaaaa; padding: 0px 0px 0px 0px; margin: auto 10px auto auto; border-radius: 10px; overflow: auto; } .tobetoggled{ width: 45%; float: left; } #small-div2{ background-color:#aaaaaa; border: 3px solid #aaaaaa; padding: 0px 0px 0px 0px; margin: auto 10px auto auto; border-radius: 10px; overflow: auto; } .tobetoggled2{ width: 45%; float: right; } .toggletothis{ width: 100%; float: left; position: fixed; display: block; z-index: 100; } .toggletothis2{ width: 100%; float: left; position: fixed; display: block; z-index: 100; } .whensmalldivistoggled{ display: none; }/* when small-div is clicked, small-div toggles to class "tobetoggled" while small-div 2 simultaneously toggles to class "whensmalldivistoggled" (the display none class) */</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="container"&gt; &lt;div class="tobetoggled" onclick="function()" id="small-div"&gt; &lt;/div&gt; &lt;div class="tobetoggled2" onclick="separatefunction()" id="small-div2"&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- end container --&gt; &lt;script&gt; function picClicktwo() { document.querySelectorAll("small-div, small-div2").classList.toggle("toggletothis, whensmalldivistoggled"); } &lt;/script&gt;</code></pre> </div> </div> </p> <p>So as you can see one div is on the right, the other is on the left, each set to 45% width. So if I toggle one div to 100% width the browser still respects the other divs space instead of taking the whole 100%.</p> <p>So I'm thinking if I can get the div on the right ,for example, to not display when the div on the left is toggled, it will be out of the way so the left div can take all 100%</p> <p>Maybe im going about this the wrong way. Any help is welcome. Thanks.</p>
<p>You can create a single javascript function that sets appropriate classes on each element. Since you have only two elements it is not too complex.</p> <p>HTML</p> <pre><code>&lt;div id="container"&gt; &lt;div id="lefty" onclick="toggle('lefty', 'righty')"&gt;Lefty&lt;/div&gt; &lt;div id="righty" onclick="toggle('righty', 'lefty')"&gt;Righty&lt;/div&gt; &lt;/div&gt; </code></pre> <p>JS</p> <pre><code>function toggle(target, other) { var t = document.getElementById(target); var o = document.getElementById(other); if (!t.className || t.className == "inative") { t.className = "active"; o.className = "inactive"; } else { t.className = ""; o.className = ""; } } </code></pre> <p>CSS</p> <pre><code>#container { background-color: lightgreen; padding: 15px 0; } #container div { color: white; width: 45%; display: inline-block; } #lefty { background-color: blue; } #righty { background-color: purple; } #container div.active { width: 90%; } #container div.inactive { display:none; } </code></pre> <p><a href="https://jsfiddle.net/dLbu9odf/1/" rel="nofollow">https://jsfiddle.net/dLbu9odf/1/</a></p> <p>This could be made more elegant or capable of handling more elements with something like <code>toggle(this)</code> and then some DOM traversal and iteration in javascript, but that's a bit beyond scope. If that were the case I would recommend jQuery.</p>
How do I go to a specific page in React based on a URL param <p>As an example when entering <code>http://localhost:3000/ui/?goto=/ui/entity/e2</code> in the browser I'd like to go to the Entity component e2.</p> <p>This is my router:</p> <pre><code>&lt;Route path="/ui/" component={App}&gt; &lt;IndexRoute component={EntitiesPage} /&gt; &lt;Route component={Entity} path="entity/:id" /&gt; &lt;Route component={NotFound} path="*" /&gt; &lt;/Route&gt; </code></pre> <p>This is the App component:</p> <pre><code>import React from 'react' const App = React.createClass( { render() { let gotoUrl = this.props.location.query.goto; if (gotoUrl) { // go here: gotoUrl; } else { return ( &lt;div className="App"&gt; {this.props.children} &lt;/div&gt; ) } } }) export default App </code></pre> <p>this.context is empty. this.props has:</p> <ul> <li>history </li> <li>location</li> <li>route</li> <li>routeParams (empty)</li> <li>routes</li> </ul> <p>UPDATE: I've ended up using this:</p> <pre><code>import React from 'react' import { withRouter } from 'react-router' const App = React.createClass( { componentWillMount() { let gotoUrl = this.props.location.query.goto; if (gotoUrl) { this.props.router.replace(gotoUrl); } }, render() { return ( &lt;div className="App"&gt; {this.props.children} &lt;/div&gt; ); } }) export default withRouter(App) </code></pre>
<p>You should use <code>browserHistory</code></p> <pre><code>import { browserHistory } from 'react-router'; ... if (gotoUrl) { browserHistory.push(gotoUrl) } </code></pre> <p>Let me know if this works</p>
Two select query at a time python <p>I want to calculate distance between two points. For that for each point in one table i have to calculate distance with all the other point in another table in same database. I am using python for that but I am not able to execute two query at a time. </p> <pre><code>import mysql.connector from haversine import haversine cnx = mysql.connector.connect(host='localhost',user='xxxxx',passwd='xxxxxx',db='xxxxxx') cursor = cnx.cursor() cursor2 = cnx.cursor() query = ("select longitude,latitude from roadData limit 5") cursor.execute(query) query2=("SELECT geo_coordinates_latitude, geo_coordinates_longitude from tweetmelbourne limit 2") cursor2.execute(query2) for (longitude,latitude) in cursor: print longitude print latitude for (geo_coordinates_longitude,geo_coordinates_latitude) in cursor2: print geo_coordinates_longitude print geo_coordinates_latitude cursor.close() cnx.close() </code></pre> <p>But, I am getting error for second query execution </p> <blockquote> <p>InternalError: Unread result found.</p> </blockquote> <p>I tried buffer=true for cursor but still same error. And also is it efficient to do like this or any other better way.</p>
<p>One trick you could use here would be to cross join the two tables together:</p> <pre><code>SELECT t1.longitude, t1.latitude, t2.geo_coordinates_latitude, t2.geo_coordinates_longitude FROM ( SELECT longitude, latitude FROM roadData LIMIT 5 ) t1 CROSS JOIN ( SELECT geo_coordinates_latitude, geo_coordinates_longitude FROM tweetmelbourne LIMIT 2 ) t2 </code></pre> <p>This should work because the way you iterate over the result set in your Python code resembles a cross join. In this case, using the above query you would only need to iterate once over the entire result set.</p>
Access local variable in another function without using global <p>I need to match the value of multiple <code>textareas</code> to the properties of an object. It should only be a match if :</p> <ol> <li>the value of the <code>textarea</code> being used is equal to the person's name contained in the object <strong>and</strong> </li> <li>if the index of the textarea is equal to the person's ID. (Cf boolean in my fiddle : <a href="https://jsfiddle.net/Lau1989/hxcpstty/1/" rel="nofollow">https://jsfiddle.net/Lau1989/hxcpstty/1/</a>)</li> </ol> <p>To do this I need to access the object <code>test = {}</code> from this function :</p> <pre><code>function make_test(name, job, ID) { var test = {}; //local variable to be used in 'function suggest(index)' test.name = name; test.job = job; test.ID = ID; return test; } new make_test("Paul", "manager", 1); new make_test("John", "employee", 2); new make_test("Jan", "employee", 2); </code></pre> <p>Inside this one :</p> <pre><code>function suggest(index) { if (test.ID === index &amp;&amp; test.name == thisInput.value) { thisOutput.innerHTML = "Has job : " + test.job; //should access 'test' properties : test.name, test.job, test.ID } } </code></pre> <p>Problem is that declaring <code>test = {};</code> as a global variable will only allow <code>function suggest(index)</code> to find 'Jan' because it is the last one I declared. But if I declare <code>var test = {};</code> as a local variable it won't work at all because <code>function suggest(index)</code> can't access <code>var test = {};</code> from outside.</p> <p>This is where I'm stuck. My goal is to access <code>var test = {};</code> within <code>suggest()</code> to get every person's job depending on their <code>name</code> and <code>ID</code>. </p> <p>Thanks for your help</p>
<p>Given that your employee IDs don't seem to be unique, I'd suggest you store all the people in an array, then in your <code>suggest()</code> function you can search through the array to check for a match (click <em>Run code snippet</em> to try it out):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function make_test(name, job, ID) { var test = {}; test.name = name; test.job = job; test.ID = ID; return test; } var people = []; people.push(make_test("Paul", "manager", 1)); people.push(make_test("John", "employee", 2)); people.push(make_test("Jan", "employee", 2)); function suggest(index) { var thisInput = document.getElementById("textarea" + index); var thisOutput = document.getElementById("output" + index); thisOutput.innerHTML = "Has job:"; for (var i = 0; i &lt; people.length; i++) { if (people[i].ID === index &amp;&amp; people[i].name == thisInput.value) { thisOutput.innerHTML = "Has job: " + people[i].job; //should access 'test' properties : test.name, test.job, test.ID break; } } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;textarea onkeyup="suggest(1)" name="response" id="textarea1" cols="30" rows="5"&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;td&gt;&lt;div id="output1"&gt;Has job :&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;textarea onkeyup="suggest(2)" name="response" id="textarea2" cols="30" rows="5"&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;td&gt;&lt;div id="output2"&gt;Has job :&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>Note that it doesn't make sense to call your <code>make_test()</code> function with <code>new</code>, because you manually create a new object inside the function.</p>
How to choose a file and download it in ASP.NET MVC <p>I'm trying to let user choose a xls file and generate a new xls file based on it for the user to download. My question is, should I use two actionresults in my Controller? One gets the file path and the other generates the new file and send it back to my View. Or I can just use one actionresult instead? </p>
<p>That is entirely up to you. If you intend to store the original file somewhere, then process it later and return the derivative file, then it would make sense to use two action methods, one to upload and one to process/download. On the other hand, if it's a fairly small and quickly processed file, it might make sense to upload the file, process it, and return the derivative file all in one action method. Either way will work.</p>
How to enable multicore processing with sklearn LogisticRegression? <p>Sklearn's LogisticRegression model refuses to run in parallel. I set n_jobs=-1, and also tried n_jobs=4. No luck -- only one core is engaged. I've run other sklearn models in parallel, e.g., RandomForestClassifier and XGBoostClassifier.</p> <p>I'm running Python 2.7.12 with sklearn 0.18 on Ubuntu 14.04.</p> <p>Other people have asked the same question (e.g., <a href="http://stackoverflow.com/questions/39620185/sklearn-logistic-regression-with-n-jobs-1-doesnt-actually-parallelize">here</a>), thus far without receiving any promising replies. I'm hoping my luck will be better.</p>
<p>From the doco for <code>LogisticRegresssion</code> it looks like the <code>n_jobs</code> parameter is only used for separate cross-validation folds (unlike the case for <code>RandomForestClassifier</code> where the individual trees are computed in parallel). </p> <blockquote> <p>n_jobs : int, default: 1</p> <p>Number of CPU cores used during the cross-validation loop. If given a value of -1, all cores are used.</p> </blockquote> <p>If you need a parallel implementation of logistic regression, you may want to look at a project like <a href="https://spark.apache.org/docs/1.6.0/api/python/pyspark.mllib.html" rel="nofollow"><code>pyspark.mllib</code></a>:</p>
Running Hadoop jar command through Java <p>I want to run this command in linux through java code. I am writing a java code to run all hadoop commands instead of typing one by one. </p> <p><code>hadoop jar WordCount.jar WordCount input/wordcount.txt output</code></p> <p>I tried <strong>Runtime.getRuntime().exec(command)</strong>; it did not work with hadoop. Also, I tried <strong>ProcessBuilder</strong> and it did not work too. Is there anyway to run hadoop command through java code ? </p>
<p>try hadoop jar WordCount.jar ur_pacjage_name.WordCount input/wordcount.txt output</p>
Assiging Random Values to an Array in C <pre><code> #include &lt;conio.h&gt; #include &lt;time.h&gt; int i = 1; int main() { int nums[20]; srand(time(NULL)); while(i &lt; 20){ nums[i] = rand()% 10; i++; } printf("%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n", nums[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]); } </code></pre> <p>when I run this code I am given values I expect, Ie under 10, except for the values for 2, 3, and 4, and more often than not 4 is negative.... Any help on what I have done wrong would be appriciated</p>
<pre><code>nums[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] </code></pre> <p>is equivalent to</p> <pre><code>nums[20] </code></pre> <p>due to the funny <a href="https://en.wikipedia.org/wiki/Comma_operator" rel="nofollow"><code>,</code>-operator</a>.</p> <p>Try enumerating elements like this (starting with <code>0</code>):</p> <pre><code>nums[0], nums[1], ..., num[19] </code></pre> <p>And initialize <code>i</code> to <code>0</code>:</p> <pre><code>i = 0; </code></pre> <p>Or, although it is usually looks suspicious, start at <code>1</code>, but then declare</p> <pre><code>int nums[21]; </code></pre>
Woocommerce add to cart ajax and mini-cart <p>I need to re-populate mini-cart when product added via ajax add to cart. I manage to update cart quantity with filter woocommerce_add_to_cart_fragments like this:</p> <pre><code>add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) { ob_start(); ?&gt; &lt;div class="cart-contents"&gt; &lt;?php echo WC()-&gt;cart-&gt;get_cart_contents_count(); ?&gt; &lt;/div&gt; &lt;?php $fragments['div.cart-contents'] = ob_get_clean(); return $fragments; } ); </code></pre> <p>And my HTML markup is </p> <pre><code>&lt;div class="cart-contents"&gt; &lt;?php echo WC()-&gt;cart-&gt;get_cart_contents_count(); ?&gt; &lt;/div&gt; </code></pre> <p>Bellow that is hidden div witch showing on .cart-contents hover</p> <pre><code>&lt;div class="header-quickcart"&gt;&lt;?php woocommerce_mini_cart(); ?&gt;&lt;/div&gt; </code></pre> <p>I want to update this div content same way or similar to woocommerce_add_to_cart_fragments. Or should I change HTML markup and hold everything in 1 div? What is common way or best practice to doing that?</p>
<p>Ok so I just realized that I can use woocommerce_add_to_cart_fragments filter 2 times, like so:</p> <pre><code>add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) { ob_start(); ?&gt; &lt;div class="cart-contents"&gt; &lt;?php echo WC()-&gt;cart-&gt;get_cart_contents_count(); ?&gt; &lt;/div&gt; &lt;?php $fragments['div.cart-contents'] = ob_get_clean(); return $fragments; } ); add_filter( 'woocommerce_add_to_cart_fragments', function($fragments) { ob_start(); ?&gt; &lt;div class="header-quickcart"&gt; &lt;?php woocommerce_mini_cart(); ?&gt; &lt;/div&gt; &lt;?php $fragments['div.header-quickcart'] = ob_get_clean(); return $fragments; } ); </code></pre> <p>First updating quantity and aother refreshing mini-cart view.</p>
Error consume JSON with JS <p>I have a JS problem with Java using Spring. I made some WebServices and PHP is running smoothly, but I need to access them using JS. I've tried everything, still is not calling my service</p> <p>Below my code in Java</p> <pre><code>@Controller @RequestMapping("/map") public class MapRest { @Autowired private MapService mapService; @RequestMapping(value = "/searchCarByUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity&lt;RetornoMapa&gt; searchCarByUser(@RequestBody User user) { RetornMap retornMap = new RetornMap(); try { List&lt;Car&gt; list = mapService.search(user); retornMap.setListCar(list); } catch (Exception e) { Log.logError("Error", e); } return new ResponseEntity&lt;&gt;(retornMap, HttpStatus.OK); } } </code></pre> <p>Now my code in JS</p> <pre><code>function testeJson() { var user = { id: 1, name: 'Jonh' }; var json = JSON.stringify(user); $.ajax({ type: "POST", url: "http://localhost:8080/orion/webservice/map/searchCarByUser", traditional: true, data: json, contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { alert(data); }, error: function (jqXHR, status) { // error handler console.log(jqXHR); alert('fail' + status.code); } }); } </code></pre> <p>When I call the JS function always returns the status equal to 404.</p> <p>When I use the Advanced REST Client of Chrome, usually calls the service listed above.</p> <p>I would like to know from you where I am going wrong? What should be done?</p>
<p>Remove the first slash from the method <code>@Path</code> annotation:</p> <pre><code>@Controller @RequestMapping("/map") public class MapRest { @Autowired private MapService mapService; @RequestMapping(value = "searchCarByUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity&lt;RetornoMapa&gt; searchCarByUser(@RequestBody User user) { //... </code></pre> <p>The <code>@Path</code> of each method follows the same rules as, say, the path from an <code>href="..."</code> attribute: if it starts with a slash, it's an absolute path, else it's a relative path (in this case relative to the base class' <code>@Path</code>).</p> <p>Having that in mind, your currrent JS code should work if you call <code>http://localhost:8080/orion/webservice/searchCarByUser</code> instead (without the <code>/map</code> part), you can test it if you want.</p>
Mutate a lead or lag column for certain rows in r <p>I have a forecast that doesn't quite align with the moving holidays. I am trying to find a quick fix:</p> <p>Here is the structure of my data frame:</p> <pre><code>df1: Date City Visitors WKN WKN_2015 Holiday 2016-11-06 New York 40000 45 46 No_Holiday 2016-11-13 New York 50000 46 47 No_Holiday 2016-11-20 New York 50000 47 48 Thanksgiving 2016-11-27 New York 100000 48 49 Cyber_Monday 2016-12-04 New York 100000 49 50 No_Holiday 2016-12-11 New York 70000 50 51 No_Holiday . . . 2017-11-23 New York 120000 47 47 Thanksgiving </code></pre> <p>Generally you would have more visitors to the city on Thanksgiving day and Cyber Monday. But my forecast is not reflecting that. Now I would like a quick fix with some thing like this:</p> <pre><code>df1: Date City Visitors WKN WKN_2015 Holiday New_Visitors 2016-11-06 New York 40000 45 46 No_Holiday 40000 2016-11-13 New York 50000 46 47 No_Holiday 50000 2016-11-20 New York 50000 47 48 Thanksgiving 100000 2016-11-27 New York 100000 48 49 Cyber_Monday 100000 2016-12-04 New York 100000 49 50 No_Holiday 70000 2016-12-11 New York 70000 50 51 No_Holiday 70000 . . . 2017-11-23 New York 120000 47 47 Thanksgiving 120000 </code></pre> <p>If you see the above data The new volume only changed for Thanksgiving, Cyber Monday and a week after Cyber Monday. Is there any way to automate this because the data continues for 2017 and so on. </p> <p>I was thinking of a quick fix until I develop a forecast to suit the moving holidays. Can anyone point me in the right direction?</p> <p>I have tried something like this but this doesn't work because I need lag/lead for only those 3 Weeks:</p> <pre><code>df1 &lt;- df1 %&gt;% mutate(New_Visitors = ifelse(Holiday == "Thanksgiving", lag(Visitors, (WKN - WKN_2015), Visitors) </code></pre> <p>Logic: Look up for thanksgiving each year and see if the WKN's match. If don't then adjust Visitors for next 3 Weeks starting from thanksgiving based on difference between WKN's. If WKN-WKN_2015 == -1 then lead Visitors by 1 for next 3 rows and if WKN-WKN_2015 == 1 then lag Visitors by 1 for next 3 rows</p> data <pre><code>df1 &lt;- structure(list(Date = c("2016-11-06", "2016-11-13", "2016-11-20", "2016-11-27", "2016-12-04", "2016-12-11", "2017-11-23"), City = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "New York", class = "factor"), Visitors = c(40000L, 50000L, 50000L, 100000L, 100000L, 70000L, 120000L), WKN = c(45L, 46L, 47L, 48L, 49L, 50L, 47L), WKN_2015 = c(46L, 47L, 48L, 49L, 50L, 51L, 47L), Holiday = structure(c(2L, 2L, 3L, 1L, 2L, 2L, 3L), .Label = c("Cyber_Monday", "No_Holiday", "Thanksgiving"), class = "factor")), .Names = c("Date", "City", "Visitors", "WKN", "WKN_2015", "Holiday"), row.names = c(NA, 7L), class = "data.frame") </code></pre>
<p>You are interest in only three weeks per year and you can calculate the lag value in the "Thanksgiving" row. I don't think <code>dplyr</code> is needed to do it.</p> <pre><code>df1$New_Visitors &lt;- df1$Visitors # copy Visitors ind &lt;- which(df1$Holiday == "Thanksgiving") # get number of "Thanksgiving" rows invisible(sapply(ind, function(x) { lag &lt;- df1[x, "WKN_2015"] - df1[x, "WKN"] # calculate the lag df1[x:(x+2), "New_Visitors"] &lt;&lt;- df1[(x+lag):(x+lag+2), "Visitors"] # rewrite })) </code></pre> <pre><code>&gt; df1 # this method treats the three weeks as a unit, so made two NA rows in the example data) Date City Visitors WKN WKN_2015 Holiday New_Visitors 1 2016-11-06 New York 40000 45 46 No_Holiday 40000 2 2016-11-13 New York 50000 46 47 No_Holiday 50000 3 2016-11-20 New York 50000 47 48 Thanksgiving 100000 4 2016-11-27 New York 100000 48 49 Cyber_Monday 100000 5 2016-12-04 New York 100000 49 50 No_Holiday 70000 6 2016-12-11 New York 70000 50 51 No_Holiday 70000 7 2017-11-23 New York 120000 47 47 Thanksgiving 120000 8 &lt;NA&gt; &lt;NA&gt; NA NA NA &lt;NA&gt; NA 9 &lt;NA&gt; &lt;NA&gt; NA NA NA &lt;NA&gt; NA </code></pre>
Can't set CALayer's border color <p>I'm trying to customize the appearance of a UIButton, like this: </p> <pre><code>@IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() button.layer.cornerRadius = button.frame.size.width / 2 button.layer.borderColor = UIColor.cyan.cgColor button.layer.borderWidth = 1 } </code></pre> <p>However when I run it, it displays nothing but the text of the button, what could cause the problem? </p>
<p>The problem is that you are running this code too soon (in <code>viewDidLoad</code>). Your <code>cornerRadius</code> calculation depends upon <code>calculateButton.frame</code>, but its value is not known at this time. Move your code into <code>viewDidLayoutSubviews</code> and I think you will find that it works as you expect.</p>
How to make crosstab in PostgreSQL? <p>CREATE TEMPORARY TABLE</p> <pre><code>CREATE TEMP TABLE pivot( gid SERIAL, zoom smallint NOT NULL, day timestamp with time zone NOT NULL, point integer NOT NULL ); </code></pre> <p>INSERT DATA</p> <pre><code>INSERT INTO pivot(zoom, day, point) VALUES(6,'2015-10-01',21); INSERT INTO pivot(zoom, day, point) VALUES(7,'2015-10-01',43); INSERT INTO pivot(zoom, day, point) VALUES(8,'2015-10-01',18); INSERT INTO pivot(zoom, day, point) VALUES(9,'2015-10-01',14); INSERT INTO pivot(zoom, day, point) VALUES(10,'2015-10-01',23); INSERT INTO pivot(zoom, day, point) VALUES(11,'2015-10-01',54); INSERT INTO pivot(zoom, day, point) VALUES(6,'2015-10-02',657); INSERT INTO pivot(zoom, day, point) VALUES(7,'2015-10-02',432); INSERT INTO pivot(zoom, day, point) VALUES(8,'2015-10-02',421); INSERT INTO pivot(zoom, day, point) VALUES(9,'2015-10-02',432); INSERT INTO pivot(zoom, day, point) VALUES(10,'2015-10-02',454); INSERT INTO pivot(zoom, day, point) VALUES(11,'2015-10-02',654); </code></pre> <p>Lets see if everything works until now:</p> <pre><code>SELECT zoom, day, point FROM pivot ORDER BY 1,2; </code></pre> <p>Result:</p> <pre><code> zoom | day | point ------+------------------------+------- 6 | 2015-10-01 00:00:00+02 | 21 6 | 2015-10-02 00:00:00+02 | 657 7 | 2015-10-01 00:00:00+02 | 43 7 | 2015-10-02 00:00:00+02 | 432 8 | 2015-10-01 00:00:00+02 | 18 8 | 2015-10-02 00:00:00+02 | 421 9 | 2015-10-01 00:00:00+02 | 14 9 | 2015-10-02 00:00:00+02 | 432 10 | 2015-10-01 00:00:00+02 | 23 10 | 2015-10-02 00:00:00+02 | 454 11 | 2015-10-01 00:00:00+02 | 54 11 | 2015-10-02 00:00:00+02 | 654 (12 rows) </code></pre> <p>CREATE EXTENSION:</p> <pre><code>CREATE EXTENSION tablefunc; </code></pre> <p>CROSSTAB QUERY</p> <pre><code>SELECT * FROM crosstab( 'SELECT zoom, day, point FROM pivot ORDER BY 1,2' ,$$VALUES ('2015-10-01'::timestamp), ('2015-10-02')$$) AS ct ("zoom" smallint, "2015-10-01" integer, "2015-10-02" integer); </code></pre> <p>Result:</p> <pre><code> zoom | 2015-10-01 | 2015-10-02 ------+------------+------------ 6 | | 7 | | 8 | | 9 | | 10 | | 11 | | (6 rows) </code></pre> <p>I cannot return values of the points, the query itself gives me an empty spots. What am I doing wrong?</p> <p><strong>Edit</strong></p> <p>I tried to do it the other way, but I am still searching for the answer to the question above.</p> <pre><code>SELECT * from crosstab ( 'select zoom, day, point from pivot order by 1,2', 'select distinct day from pivot order by 1') AS ct(zoom smallint, "2015-10-01" integer, "2015-10-02" integer); </code></pre> <p>Result:</p> <pre><code> zoom | 2015-10-01 | 2015-10-02 ------+------------+------------ 6 | 21 | 657 7 | 43 | 432 8 | 18 | 421 9 | 14 | 432 10 | 23 | 454 11 | 54 | 654 (6 rows) </code></pre>
<p>Thanks to @Abelisto suggestion about <code>timestamptz</code>, this works:</p> <pre><code>SELECT * FROM crosstab( 'SELECT zoom, day, point FROM pivot ORDER BY 1,2' ,$$VALUES ('2015-10-01'::timestamptz), ('2015-10-02')$$) AS ct ("zoom" smallint, "2015-10-01" integer, "2015-10-02" integer); </code></pre>
Deprecation warning in moment js <p>I need help I'm getting a warning on my code that has a value provided is not in a recognized ISO format. and I change my variable today with moment function and still it doesn't work.</p> <p>Here's the warning error </p> <blockquote> <p>Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to <a href="http://momentjs.com/guides/#/warnings/js-date/" rel="nofollow">http://momentjs.com/guides/#/warnings/js-date/</a> for more info. Arguments: [0] _isAMomentObject: true, _isUTC: true, _useUTC: true, _l: undefined, _i: 2016-9-26 19:30, _f: undefined, _strict: undefined, _locale: [object Object]</p> </blockquote> <pre><code> var entryDate = new Date(); var currentDate = entryDate.getDate(); function between(x,min,max) { return x.valueOf() &gt;= min.valueOf() &amp;&amp; x &lt; max.valueOf(); }; $("#custom1").change(function(){ if ($("#custom1 :selected").val() == "AU" ) { var keyword = ""; var aus1_s = moment.tz('2016-9-26 19:30', 'Australia/Sydney'); var aus2_s = moment.tz('2016-10-2 19:30', 'Australia/Sydney'); var aus3_s = moment.tz('2016-10-9 19:30', 'Australia/Sydney'); var aus4_s = moment.tz('2016-10-16 19:30', 'Australia/Sydney'); var aus5_s = moment.tz('2016-10-23 19:30', 'Australia/Sydney'); var aus6_s = moment.tz('2016-10-30 19:30', 'Australia/Sydney'); var aus6_e = moment.tz('2016-11-5 19:30', 'Australia/Sydney'); } else if ($("#custom1 :selected").val() == "NZ" ) { var aus1_s = moment.tz('2016-9-28 20:30', 'Pacific/Auckland'); var aus2_s = moment.tz('2016-10-4 20:30', 'Pacific/Auckland'); var aus3_s = moment.tz('2016-10-11 20:30', 'Pacific/Auckland'); var aus4_s = moment.tz('2016-10-18 20:30', 'Pacific/Auckland'); var aus5_s = moment.tz('2016-10-25 20:30', 'Pacific/Auckland'); var aus6_s = moment.tz('2016-11-2 20:30', 'Pacific/Auckland'); var aus6_e = moment.tz('2016-11-9 20:30', 'Pacific/Auckland'); } else { $("#entryEquals").val(""); return false; } var today = moment(); switch (true) { case between (today, aus1_s, aus2_s): keyword = "RElYT04="; break; case between (today, aus2_s, aus3_s): keyword = "QlJJREU="; break; case between (today, aus3_s, aus4_s): keyword = "U1lETkVZ"; break; case between (today, aus4_s, aus5_s): keyword = "R1JPT00="; break; case between (today, aus5_s, aus6_s): keyword = "V0VERElORw=="; break; case between (today, aus6_s, aus6_e): keyword = "VExD"; break; default: $("#entryEquals").val(""); break; } $("#entryEquals").val(keyword); }); </code></pre>
<p>Check out all their awesome documentation!</p> <p>Here is where they discuss the <a href="http://momentjs.com/docs/#/parsing/string/" rel="nofollow">Warning Message</a>.</p> <h2>String + Format</h2> <blockquote> <p>Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.</p> <p>For consistent results parsing anything other than ISO 8601 strings, you should use <a href="http://momentjs.com/docs/#/parsing/string-format/" rel="nofollow">String + Format</a>.</p> </blockquote> <pre><code>moment("12-25-1995", "MM-DD-YYYY"); </code></pre> <h2>String + Formats (multiple formats)</h2> <p>If you have more than one format, check out their <a href="http://momentjs.com/docs/#/parsing/string-formats/" rel="nofollow">String + Formats</a> (with an 's').</p> <blockquote> <p>If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.</p> </blockquote> <pre><code>moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]); </code></pre> <p>Please checkout the documentation for anything more specific.</p> <h2>Timezone</h2> <p>Checkout <a href="http://momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone/" rel="nofollow">Parsing in Zone</a>, the equivalent documentation for timezones.</p> <blockquote> <p>The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.</p> </blockquote> <pre><code>var b = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", "America/Toronto"); </code></pre> <p><strong>EDIT</strong></p> <pre><code>//... if ($("#custom1 :selected").val() == "AU" ) { var keyword = ""; var dateFormat = "YYYY-M-D H:m"; var aus1_s = moment.tz('2016-9-26 19:30', dateFormat, 'Australia/Sydney'); var aus2_s = moment.tz('2016-10-2 19:30', dateFormat, 'Australia/Sydney'); var aus3_s = moment.tz('2016-10-9 19:30', dateFormat, 'Australia/Sydney'); var aus4_s = moment.tz('2016-10-16 19:30', dateFormat, 'Australia/Sydney'); var aus5_s = moment.tz('2016-10-23 19:30', dateFormat, 'Australia/Sydney'); var aus6_s = moment.tz('2016-10-30 19:30', dateFormat, 'Australia/Sydney'); var aus6_e = moment.tz('2016-11-5 19:30', dateFormat, 'Australia/Sydney'); } else if ($("#custom1 :selected").val() == "NZ" ) { var aus1_s = moment.tz('2016-9-28 20:30', dateFormat, 'Pacific/Auckland'); var aus2_s = moment.tz('2016-10-4 20:30', dateFormat, 'Pacific/Auckland'); var aus3_s = moment.tz('2016-10-11 20:30', dateFormat, 'Pacific/Auckland'); var aus4_s = moment.tz('2016-10-18 20:30', dateFormat, 'Pacific/Auckland'); var aus5_s = moment.tz('2016-10-25 20:30', dateFormat, 'Pacific/Auckland'); var aus6_s = moment.tz('2016-11-2 20:30', dateFormat, 'Pacific/Auckland'); var aus6_e = moment.tz('2016-11-9 20:30', dateFormat, 'Pacific/Auckland'); } //... </code></pre>
Which is the intended bit (not byte) order in internet RFC packet diagrams <p>I am parsing ICMPv6 datagrams on my home wired network, and can't find an explicit mention of the bit-ordering convention in the specific RFC. </p> <p>Multi-byte fields are network order, but what about bits within a byte?</p> <p>Machines are byte-addressible, but network hardware serializes bits. On diagrams, a bit to the "left" of a 8-bit field ends up in which bit of an unsigned byte (most significant, or least)? Is this per-RFC, or is it everywhere the same for all internet RFCs?</p> <h3>Example Reading a multi-byte field (Prf field)</h3> <p>Assume I have the packet data stored in a variable called <code>data</code>:</p> <pre><code>data, remote_peer = sock.recvfrom(1024) #pseudocode </code></pre> <p>And that I find the particular <em>byte</em> (not bit) of interest containing the flags:</p> <pre><code>flag_byte = data[some_offset] #pseudocode </code></pre> <p>Trying to parse this message, <a href="https://tools.ietf.org/html/rfc4191#section-2.3" rel="nofollow">RFC4161 section 2.3</a>, specifies that the the Route information option has a 2-bit flag called <code>Prf</code>. </p> <pre><code> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | Prefix Length |Resvd|Prf|Resvd| +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Route Lifetime | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Prefix (Variable Length) | . . . . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ... Prf (Route Preference) 2-bit signed integer. The Route Preference indicates whether to prefer the router associated with this prefix over others, when multiple identical prefixes (for different routers) have been received. If the Reserved (10) value is received, the Route Information Option MUST be ignored. </code></pre> <p>To phrase my question in terms of this example, <code>(flag_byte &amp; 0x18) &gt;&gt; 3</code> will get me the two bits. Will <code>b &amp; 0x10</code> be the sign bit? I'm also interested in figuring out the standard that specifies that this is the way it should be.</p> <p><em>edit</em> Removed superfluous example. Edited question to get to the point. </p>
<p>As pointed out in a previous comment (thanks ron-maupin), <a href="https://tools.ietf.org/html/rfc1700" rel="nofollow">RFC1700</a> tells one that the messages (covering internet protocols) are depicted with most significant bits on the left.</p> <pre><code>Whenever an octet represents a numeric quantity the left most bit in the diagram is the high order or most significant bit. That is, the bit labeled 0 is the most significant bit. For example, the following diagram represents the value 170 (decimal). 0 1 2 3 4 5 6 7 +-+-+-+-+-+-+-+-+ |1 0 1 0 1 0 1 0| +-+-+-+-+-+-+-+-+ Significance of Bits Similarly, whenever a multi-octet field represents a numeric quantity the left most bit of the whole field is the most significant bit. </code></pre> <p>RFC1700 was superseded by <a href="https://tools.ietf.org/html/rfc3232" rel="nofollow">RFC3232</a>, which puts the up-to-date protocol definitions online at <a href="http://www.iana.org/protocols" rel="nofollow">iana.org/protocols</a>. They seem to have kept that notation (e.g. <a href="http://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xhtml#icmpv6-parameters-11" rel="nofollow">RouterAdvertisementFlags</a>).</p> <p>I assume this convention on significance applies to n-bit bit fields too (1 &lt; n &lt; 8), and therefore the leftmost bit in a 2-bit field (such as <code>Prf</code>) would be the sign bit.</p> <p>It should be up to the hardware to de-serialize bits on the physical medium and place them at their right location within a byte on the byte-addressible computer. Different physical layers (physical ethernet, wifi, coax, infiniband, fibre channel) might serialize bits in different orders on the "wire", but the respective positions in bytes at the packet-level would be the same regardless.</p>
My program doesn't seem to follow through my If statements <pre><code> //Declarations double height; double weight; double BMI; int Const; //Reading User Input //HEIGHT Console.WriteLine("Please enter the person's height in inches: "); height = Convert.ToDouble(Console.ReadLine()); if (height &lt; 5 &amp;&amp; height &gt; 120) { Console.WriteLine("The height entered must be between 5” and 120” inclusive."); } //MASS Console.WriteLine("Please enter the person's weight in lbs: "); weight = Convert.ToDouble(Console.ReadLine()); if (weight &lt; 0.5 &amp;&amp; weight &gt; 999) { Console.WriteLine("The weight entered must be between 0.5 lb. and 999 lb. inclusive."); } //BMI Calculations Const = 703; BMI = (weight / (height * height)) * Const; //Category Assignments if (BMI &lt;= 16) { Console.WriteLine("The BMI for a " + height + "tall person who weighs " + weight + " lb. is 26.7, which is categorized as 'serverly underwieght'."); } else if (BMI &gt; 16 &amp;&amp; BMI &lt;= 18.5) { Console.WriteLine("The BMI for a " + height + "tall person who weighs " + weight + " lb. is 26.7, which is categorized as 'underwieght'."); } else if (BMI &gt; 18.5 &amp;&amp; BMI &lt;= 25) { Console.WriteLine("The BMI for a " + height + "tall person who weighs " + weight + " lb. is 26.7, which is categorized as 'healthy'."); } else if (BMI &gt; 25 &amp;&amp; BMI &lt; -30) { Console.WriteLine("The BMI for a " + height + "tall person who weighs " + weight + " lb. is 26.7, which is categorized as 'Overweight'."); } else if (BMI &gt; 30) { Console.WriteLine("The BMI for a " + height + "tall person who weighs " + weight + " lb. is 26.7, which is categorized as 'Obese'."); } } } } </code></pre> <p>First question on here, so sorry about not making proper format. Anyways, my program just closes after I enter in the weight, like instantly. Its a console application btw.</p> <p>Also, if I enter a weight or height that is below or above the requirements, it doesn't display the error message, just goes on then closes.</p>
<p>If you are checking between a range 5 and 120 it should be as follows, because <code>height &lt; 5 &amp;&amp; height &gt; 120</code> will return false.</p> <pre><code>if (height &gt; 5 &amp;&amp; height &lt; 120) { Console.WriteLine("The height entered must be between 5” and 120” inclusive."); } </code></pre> <p>Similarly for weight,</p> <pre><code>if (weight &gt; 0.5 &amp;&amp; weight &lt; 999) { Console.WriteLine("The weight entered must be between 0.5 lb. and 999 lb. inclusive."); } </code></pre> <p>if you want to see the output in console, Add this at the end of the program</p> <pre><code>Console.ReadLine() </code></pre> <p>which will wait until the user press some key</p>
variable in bat file not being read <p>I have a .bat file which contains the following command:</p> <pre><code>set /p Param=&lt;foo.ext START "test" /wait "C:\Program Files\blabla\bla.exe" -flag1 -flag2 %Param% </code></pre> <p>Param is the file to be opened by bla.exe. When I run the .bat, bla.exe opens, but it doesn't open %Param%. It looks like CMD only passes the string "%Param%" to bla.exe. Can I force it to pass the variable somehow?</p>
<p>get rid of the &lt; in the first line.</p> <p>P.S: I am a bot for J03L's chat rooms, i just need 20 rep to be able to be given the permissions.</p>
How would improve this O(n^2 ) string manipulation solution? <p>Write a function that takes in an input of a string and returns the count of tuples. Tuples in the form (x,y) where x = index of 'a', y = index of 'b' and x &lt; y.</p> <p>Examples: For “aab” the answer is two For "ababab" the answer is six</p> <p>It can be done in O(n^2) by simply looking for the number of b's after each 'a' but I am not sure how to do it in O(n). I've tried traversing the string with 2 pointers but I keep missing some tuples. I am not sure if this can be done in O(n) time.</p>
<p>The idea is to store the amount of 'a's that we have behind the <strong>ith</strong> position in the string.</p> <pre><code>int main() { string ss; ss = "ababab"; int NumberOfAs = 0; //The amount of A that we have encountered int Answer = 0; //The sum of the possible tuples int StringLen = ss.length(); //We store the length of the string to avoid //checking it in O(n) time each iteration of the for for (int i=0; i &lt; StringLen; i++){ if (ss[i] == 'a') //If it's an 'a' we increase the counter NumberOfAs++; if (ss[i] == 'b') //If it's a 'b' we sum the possible tuples Answer += NumberOfAs; } printf("%d\n", Answer); //cout from c. return 0; } </code></pre> <p>We can store the amount of 'a's in the <strong>ith</strong> positino using one extra variable that doesnt affect our space complexity.<br> The result will be O(N) in time, where N is in terms of the length of the string. And the space complexity is O(1)</p>
Best path to have a masters degree in computer science? (Canada, Quebec) <p>I was wondering what could be the best path to be a have a computer science master's degree as I want to be a game developer, I'm currently in grade 10 and I'm taking advanced math and science, getting fairly good grades but I dont know what I should do in CGEP and University, thanks in advance!</p>
<p>I think a degree in Computer Science is very valuable, but because it is in such high demand right now, it may be a better option to do a few internships while in college and get hired by a company right after you get your BS. A masters would be useful, however, if you plan on getting a job as a "senior software engineer" or possibly in a teaching position. From my experience, companies hire programmers based on their abilities, not necessarily just your level of education. It would be a good idea to build a portfolio of projects you've worked on, or in your case games that you have worked on. </p>
AngularJS - Passing variable to controller <p>I need to send a parameter to the controller</p> <pre><code>function config($routeProvider, $locationProvider) { $routeProvider .when('/url-1', { parameter: 1 }) .when('/url-2', { parameter: 2 }) .otherwise({ redirectTo: '/url-1' }); $locationProvider.html5Mode({ enabled: true, requireBase: true }); } </code></pre> <p>this is my controller</p> <pre><code>function MyController(parameter) { console.log(parameter); } </code></pre> <p>and in the view I only have two links</p> <pre><code>&lt;a ng-href="/url-1"&gt;url-1&lt;/a&gt; &lt;a ng-href="/url-2"&gt;url-1&lt;/a&gt; </code></pre> <p>Do I need to specify the controller in the $routeProvider? I only have one controller. I´m not loading views dinamically I just need to do a console.log(parameter) based on the parameter sent by $routeProvider</p> <p>thank you!</p>
<p>This would be good way to define route, suppose if you have 100 routes then the rout definition would get increased to that number. Rather that multiple routes have single generic route.</p> <p>And assign a controller to the route where you can access $routeParams API to get parameters available in route.</p> <p>Config</p> <pre><code>function config($routeProvider, $locationProvider) { $routeProvider .when('/url/:id', { controller: MyController }) .otherwise({ redirectTo: '/url/1' }); $locationProvider.html5Mode({ enabled: true, requireBase: true }); } </code></pre> <p>Controller</p> <pre><code>function MyController($routeParams) { console.log($routeParams); } </code></pre> <hr> <p>If you don't want to place another controller's for each route then you can keep track of route changes by placing hook on <code>routeChangeSuccess</code> event inside run block of your application like below</p> <pre><code>app.run(function($rootScope, $routeParams ) { $rootScope.$on('routeChangeSuccess', function() { console.log($routeParams); } }); </code></pre> <p>OR you can have that event inside page controller which has been placed on body.</p> <pre><code>function MyController($scope, $routeParams) { console.log("Parameters on page load "+ $routeParams); $scope.$on('$routeChangeSuccess', function(event, next, current) { console.log($routeParams); } } </code></pre>
Scrapy Xpath with text() contains <p>I'm using scrapy, and I'm trying to look for a span that contains a specific text. I have:</p> <pre><code>response.selector.xpath('//*[@class="ParamText"]/span/node()') </code></pre> <p>which returns:</p> <pre><code>&lt;Selector xpath='//*[@class="ParamText"]/span/text()' data=u' MILES STODOLINK'&gt;, &lt;Selector xpath='//*[@class="ParamText"]/span/text()' data=u'C'&gt;, &lt;Selector xpath='//*[@class="ParamText"]/span/text()' data=u' MILES STODOLINK'&gt;] </code></pre> <p>However when I run:</p> <pre><code>&gt;&gt;&gt; response.selector.xpath('//*[@class="ParamText"]/span[contains(text(),"STODOLINK")]') Out[11]: [] </code></pre> <p>Why does the contains function not work?</p>
<p><code>contains()</code> can not evaluate multiple nodes at once :</p> <pre><code>/span[contains(text(),"STODOLINK")] </code></pre> <p>So, in case there are multiple text nodes within the <code>span</code>, and <code>"STODOLINK"</code> isn't located in <em>the first text node child of the <code>span</code></em>, then <code>contains()</code> in the above expression won't work. You should try to apply <code>contains()</code> check on individual text nodes as follow :</p> <pre><code>//*[@class="ParamText"]/span[text()[contains(.,"STODOLINK")]] </code></pre> <p>Or if <code>"STODOLINK"</code> isn't necessarily located directly within <code>span</code> (can be nested within other element in the <code>span</code>), then you can simply use <code>.</code> instead of <code>text()</code> :</p> <pre><code>//*[@class="ParamText"]/span[contains(.,"STODOLINK")] </code></pre>
POST method does not display but GET method does <p>My <code>POST</code> method does not display on the webpage, but my <code>GET</code> method does even though I haven't create a method with it in my global.js. Does the <code>GET</code> method come with <code>POST</code>? I want my <code>POST</code> to display not <code>GET</code>. How do I do that? I know that my <code>POST</code> work i think because in network (that is in the browser with console), the <code>POST</code> method is there, and the preview prints out the <code>$_POST</code> and <code>$_SESSION</code>. How do I make <code>POST</code> to display on the page instead of <code>GET</code>.</p> <p><strong><em>Button.php</em></strong></p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt; &lt;/script&gt; &lt;script src ="global.js"&gt;&lt;/script&gt; &lt;title&gt;Button POST&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;button id ="postbutton" onclick="location.href='storage.php'"&gt;GO&lt;/button&gt;&lt;br&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong><em>storage.php</em></strong></p> <pre><code>&lt;?php print_r($_POST); if(isset($_POST['json'])){ $_SESSION['object'] = $_POST["json"]; print_r($_SESSION); echo 'True'; }else { echo 'False'; } </code></pre> <p><strong><em>global.js</em></strong></p> <pre><code>var oject = [{name:'John', age:17},{name:'James', age:22}]; var json = JSON.stringify(oject); $(document).ready(function(){ $('#postbutton').click(function(){ $('#output').html('sending..'); var jobject = JSON.stringify(oject); console.log(jobject); $.ajax({ method:'post', url:'storage.php', data:{json:oject}, }) .done(function(data){ console.log(data); }); }); }); </code></pre>
<p>Your GET method is work because you used onclick with <code>location.href</code> method .That will always redirected with GET method so it can display your output ! But to work with <code>POST method in ajax</code> you need to remove onclick method and append return data to body element . </p> <p><strong>Button.php</strong></p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt; &lt;/script&gt; &lt;script src ="global.js"&gt;&lt;/script&gt; &lt;title&gt;Button POST&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;button id ="postbutton"&gt;GO&lt;/button&gt;&lt;br&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>global.js</strong></p> <pre><code>var oject = [{name:'John', age:17},{name:'James', age:22}]; var json = JSON.stringify(oject); $(document).ready(function(){ $('#postbutton').click(function(){ $('#output').html('sending..'); var jobject = JSON.stringify(oject); console.log(jobject); $.ajax({ method:'post', url:'storage.php', data:{json:oject}, }) .done(function(data){ $("body").append(data); }); }); }); </code></pre>
Add values in Array based on other multiple values then regroup <p>I have this data:</p> <pre><code>var data = [ [1, "San Miguel National Central High School", "School", 1], [1, "San Miguel Central Elementary School", "School", 2], [2, "Medrano's Rice Mill and Warehouse", "Warehouse", 3], [1, "Unknown", "Residential", 341], [2, "Unknown", "Residential", 532], [3, "Unknown", "Residential", 257], [2, "Unknown", "Gas Station", 1] ]; </code></pre> <p>And the intended ouput should be like this:</p> <pre><code>var data = [ ["School", 3,0,0], ["Warehouse", 0,3,0], ["Residential", 341, 532, 257], ["Gas Station", 0,1,0] ]; </code></pre> <p>For its representation,</p> <ul> <li>data[i][0] --> Level </li> <li>data[i][1] --> Building Name</li> <li>data[i][2] --> Building Type</li> <li>data[i][3] --> Count</li> </ul> <p>The result should have this sequence:</p> <blockquote> <p>Building Type, Level 1 Count, Level 2 Count, Level 3 Count</p> </blockquote> <p>If the array has the same level and same building type the count value should be added.</p> <p>How to achieve this using JavaScript or JQuery?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var input = [ [1, "San Miguel National Central High School", "School", 1], [1, "San Miguel Central Elementary School", "School", 2], [2, "Medrano's Rice Mill and Warehouse", "Warehouse", 3], [1, "Unknown", "Residential", 341], [2, "Unknown", "Residential", 532], [3, "Unknown", "Residential", 257], [2, "Unknown", "Gas Station", 1] ]; var output = []; function init() { var index = {}; for (let building of input) { if (!index.hasOwnProperty(building[2])) { index[building[2]] = output.length; output.push([ building[2], 0, 0, 0 ]); } output[index[building[2]]][building[0]] += building[3]; } console.log(output); } document.addEventListener( "DOMContentLoaded", init, false );</code></pre> </div> </div> </p>
IFS and INDEX/ MATCH EXCEL COUNTERPART IN SQL QUERY <p>My table looks like this</p> <pre><code>NAME BRAND REFERENCE COMMENTS &lt;-Expected output ------------------------------------------------- Gu Skirt 101128 Pants Cci Pants 101127 Pants Cha Skirt paired paired Gu Pants 101128 Skirts Nel Skirt nonpaired UNIQUE Gir Pants 101188 Skirt Baud Skirt dropped DROPPED Le Pants paired PAIRED Gir Skirt 101188 101178 Vis Socks blanks Cci Skirts 101127 Skirts </code></pre> <p>I wonder what code to use to get the <code>Comments</code> result.</p> <p>First reference in <code>NUMBERS</code> should be paired. If reference numbers match, return value should be the <code>Brand</code> counterpart. </p> <p>If reference is in <code>Character</code>, they have to fall under if statements: IF character is Nonpaired return value should be unique, dropped for dropped and so on. If the reference is blanks no change.</p> <p>Is this possible?</p> <p>Thank you so much.</p>
<p>You can use common table expressions to break down the problem which can help with maintaining the code.</p> <p>I didn't use lag/lead because you only have two rows in the pair, so numbering the rows and joining the table to itself felt quicker and easier to follow.</p> <p>Here's the code I've used to answer and test your question;</p> <pre><code>create table #source ( [NAME] varchar(200), [BRAND] varchar(200), [REFERENCE] varchar(200) ); insert into #source values ('Gu','Skirt','101128'), ('Cci','Pants','101127'), ('Cha','Skirt','paired'), ('Gu','Pants','101128'), ('Nel','Skirt','nonpaired'), ('Gir','Pants','101188'), ('Baud','Skirt','dropped'), ('Le','Pants','paired'), ('Gir','Skirt','101188'), ('Vis','Socks',''), ('Cci','Skirts','101127'), ('Le','Socks','101188'), ('Uno','Socks','101101'); select * from #source; with cteNumericRef as ( select [NAME],[BRAND],[REFERENCE] from #source where ISNUMERIC([REFERENCE]) = 1 ) , cteCheckRow as ( select [REFERENCE], 'CHECK' as [COMMENT] from cteNumericRef group by [REFERENCE] having count(*) &lt;&gt; 2 ) , ctePairedRow as ( select num_ref.[NAME] , num_ref.[BRAND] , num_ref.[REFERENCE] , row_number() over (partition by num_ref.[REFERENCE] order by num_ref.[NAME]) as [Pair_Num] from cteNumericRef num_ref left join cteCheckRow check_row on check_row.[REFERENCE] = num_ref.[REFERENCE] where check_row.[REFERENCE] is null ) , cteTextRow as ( select [NAME],[BRAND],[REFERENCE], case [REFERENCE] when 'paired' then 'PAIRED' when 'nonpaired' then 'UNIQUE' when 'dropped' then 'DROPPED' when '' then '' else 'CHECK' end as [COMMENT] from #source where ISNUMERIC([REFERENCE]) &lt;&gt; 1 ) select left_row.[NAME] , left_row.[BRAND] , left_row.[REFERENCE] , right_row.[BRAND] as [COMMENTS] from ctePairedRow left_row inner join ctePairedRow right_row on left_row.[REFERENCE] = right_row.[REFERENCE] and left_row.[Pair_Num] &lt;&gt; right_row.[Pair_Num] union all select num_ref.[NAME] , num_ref.[BRAND] , num_ref.[REFERENCE] , check_row.[COMMENT] from cteNumericRef num_ref inner join cteCheckRow check_row on check_row.[REFERENCE] = num_ref.[REFERENCE] union all select [NAME] , [BRAND] , [REFERENCE] , [COMMENT] from cteTextRow; drop table #source </code></pre>
Python - KeyboardInterrupt or RuntimeError implementation <p>New to python and programming. I have a program consist of several classes, module and functions. the program runs from a main class which calls several modules and function</p> <p>My question is how to implement keyboardinterrupt if the user wants to terminate a running program at any point. Do I need to implement 'try/except' method in all the functions? or this can be implementable in the main function? </p> <p>To catch interrupt at any moment do I need to use try/except in all the calling functions?</p> <pre><code>def KEYBOARD_INTERRUPT(): while True: yesnoinput=raw_input('Do you want to exit from software [Y/N]:') if yesnoinput=='y' or yesnoinput.upper()=='Y': sys.exit() elif yesnoinput=='n' or yesnoinput.upper()=='N': break else: continue def A(): while True: try: userInput=raw_input("Please enter A") if userInput=='A': break else: continue except KeyboardInterrupt: KEYBOARD_INTERRUPT() def B(): userInput=raw_input("Please enter B") if userInput=='B': break else: continue def main(): try: A() B() except: KEYBOARD_INTERRUPT() </code></pre> <p>when main program is calling function B, at this moment if the user presses keyboardInterrupt the program will quit with error messgage, I am worried if I want to handle interrupt like KEYBOARD_INTERRUPT function I need to implement this in very function such as function A?</p> <p>Did I understand wrong? </p>
<p>You could do something like :</p> <pre><code>try: ... except KeyboardInterrupt: Do something </code></pre>
Check if the first letter of each element of an array is capital using filter method. But I keep getting the whole array <pre><code>// JavaScript Document "use strict"; var testArray =["beau","Diane","morgan","Brittany"]; function checkCapital(value,index,array) { if(value!==value.charAt(0).toLowerCase()) return value; } var capital =testArray.filter(checkCapital); console.log(capital); </code></pre> <p>I need to check if the first letter of every value of the array is a capital using filter method. But I keep getting the whole array returned on my function.</p>
<p>The <code>filter()</code> method depends on the <code>return</code> statement of the callback, which if returns <code>true</code> then <code>filter()</code> will include the current value to the array it will return. Just remove your <code>if</code> statement and put the condition on the <code>return</code> statement:</p> <pre><code>function checkCapital(value,index,array) { return value !== value.charAt(0).toLowerCase(); } </code></pre> <p>Because your original callback returns <code>true</code> always, it would include all elements of the original array to be returned by the <code>filter()</code> method.</p>
In Handsontable How do you save records with specific ids each row? <p>I have this set of records object-array like for example.. </p> <p><code>[{firstname:'John',lastname:'Smith'},{firstname:'Jimmy',lastname:'Morre'}]</code></p> <p>What I want to do is to enable Saving feature of Handsontable. My problem is I can't update it where column name is "firstname" or "lastname" .. or at least row id (where can I put rowID by the way?) because the getData() function returns only values of the cell not the with the properties of the original data-set such as like 'firstname ' and 'lastname'.</p> <p>Anyone from here who are more familiar with Handsontable? thank you..</p>
<p>I am not sure to understand what you want.</p> <p>But in this <a href="http://jsfiddle.net/am5dmmbt/" rel="nofollow">JSFiddle</a> you can see how to get the property of your data ;)</p> <pre><code>var datas = hot.getData() $.each(datas, function(rowIndex, row) { console.log('The row id is ' + rowIndex); $.each(row, function(colIndex, value) { console.log('The column id is ' + colIndex + ' and the property is ' + Object.keys(hot.getSchema())[colIndex]); console.log(value); }); console.log("----------------------------"); }); </code></pre> <p>I hope it helps you.</p>
php url string converts "&section=" to "§ion", which does not yield cURL response <p>I save a php string as $url = "<a href="http://example.com/index.php?q=board/ajax_" rel="nofollow">http://example.com/index.php?q=board/ajax_</a><strong>call&amp;section</strong>=get_messages";</p> <p>The url when printed to screen displays as "<a href="http://example.com/index.php?q=board/ajax_" rel="nofollow">http://example.com/index.php?q=board/ajax_</a><strong>call§ion</strong>=get_messages" as "&amp;sect" gets auto converted to special char "§".</p> <p>How can I prevent this so that I can call the correct URL using cURL .</p>
<h1>Your Problem</h1> <p>The problem is that <code>&amp;sect</code> is interpreted by the browser as the <a href="https://dev.w3.org/html5/html-author/charref" rel="nofollow">HTML entity</a> for <code>§</code>.<sup>*</sup> So, <code>&amp;section</code> displays as <code>§ion</code>.</p> <h1>The Solution</h1> <p>If you're going to print the URL itself, you need to escape the <code>&amp;</code> and turn it into <code>&amp;amp;</code>. You can do this automatically using <a href="http://php.net/manual/en/function.htmlentities.php" rel="nofollow"><code>htmlentities()</code></a>. Sample code:</p> <pre><code>&lt;?php $url = "http://example.com/index.php?q=board/ajax_call&amp;section=get_messages"; echo "Without htmlentities(): " . $url . "\n"; // output: http://example.com/index.php?q=board/ajax_call&amp;section=get_messages echo "With htmlentities(): " . htmlentities($url) . "\n"; // output: http://example.com/index.php?q=board/ajax_call&amp;amp;section=get_messages </code></pre> <p>Here's a <a href="https://3v4l.org/k0Abt" rel="nofollow">demo</a>.</p> <h1>A Note About Security</h1> <p>Note that using <code>htmlentities()</code> here is a good idea for lots of other reasons. What if somebody used this URL?</p> <pre><code>http://example.com/index.php?q=board/ajax_call&amp;section=get_messages&lt;script src="http://evilsite/evil.js&gt;&lt;/script&gt; </code></pre> <p>If you just dumped it out onto the screen, you have just included an evil JavaScript. Congratulations! You just hacked your user and, probably, got your own site hacked. This is a real problem called <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)" rel="nofollow">XSS (Cross-Site Scripting)</a>. But if you call <code>htmlentities()</code> first, you get:</p> <pre><code>http://example.com/index.php?q=board/ajax_call&amp;amp;section=get_messages&amp;lt;script src=&amp;quot;http://evilsite/evil.js&amp;gt;&amp;lt;/script&amp;gt; </code></pre> <p>That's safe and won't actually run the evil script.</p> <hr> <p><sup>* Technically, the HTML entity is <code>&amp;sect;</code>, with the semicolon, but nearly all browsers with treat it as an HTML entity with or without the semicolon. See <a href="http://stackoverflow.com/a/15532395/2057919">this answer</a> for a good explanation.</sup></p>
Best Way to Implement an Intro Sequence? Swift <p>I'm trying to add an intro sequence to my code so that if it's the first time the app is opened, the user can enter some basic information (which I can then store in UserDefaults).</p> <p>The way that I was thinking of doing this is by having a variable called <code>isFirstTime</code> which is initially set to <code>true</code>. Every time the app is opened, it'll check if there is a value for <code>isFirstTime</code> in UserDefaults. If it isn't there, it'll trigger the View Controller that has my intro sequence to appear. Once the intro sequence is finished, <code>isFirstTime</code> will be set to <code>false</code> and then stored in UserDefaults.</p> <p>Is this a correct implementation, or is there a more efficient way?</p> <p><strong>EDIT:</strong> If anyone is interested, this is the code I used to implement my intro sequence. I first assign a boolean variable outside of my View Controller that keeps track of whether it's the first time opening the app or not.</p> <pre><code>var isFirstTime = true </code></pre> <p>Then, in my <code>ViewDidAppear</code> (it does not work in the <code>ViewDidLoad</code> method), I added this code which checks whether or not I already have a <code>UserDefault</code> for my <code>isFirstTime</code> variable. If yes, I then execute the rest of my program, but if not, I start up my intro sequence's View Controller.</p> <pre><code>if UserDefaults.standard.object(forKey: "isFirstTime") != nil{ // Not the first time app is opened isFirstTime = false // I use isFirstTime elsewhere in my code too. } else { let introVC = self.storyboard?.instantiateViewController(withIdentifier: "intro") self.present(introVC!, animated: false, completion: nil) } </code></pre> <p>In my intro sequence View Controller, when I am done with my gathering the user's basic information, I do two things: the first is changing the value of <code>isFirstTime</code> and setting it as a UserDefault, and the second is dismissing the View Controller.</p> <pre><code>isFirstTime = false UserDefaults.standard.set(isFirstTime, forKey: "isFirstTime") dismiss(animated: false, completion: nil) </code></pre>
<p>You can achieve it easily. This is code which I have used for it.</p> <p><strong>Step 1</strong> First create a file called UserDefaultManager.swift</p> <pre><code>import UIKit // User Defaults Manager Constants let kIsFirstTimeLaunch = "IsFirstTimeLaunch" class UserDefaultsManager: NSObject { // MARK: Setter Methods class func setIsFirstTimeLaunch(flag: Bool) { NSUserDefaults.standardUserDefaults().setBool(flag, forKey:kIsFirstTimeLaunch) NSUserDefaults.standardUserDefaults().synchronize() } // MARK: Getter Methods class func isFirstTimeLaunch() -&gt; Bool { return NSUserDefaults.standardUserDefaults().boolForKey(kIsFirstTimeLaunch) } // MARK: Reset Methods class func resetIsFirstTimeLaunch() { NSUserDefaults.standardUserDefaults().removeObjectForKey(kIsFirstTimeLaunch) NSUserDefaults.standardUserDefaults().synchronize() } } </code></pre> <p>Step 2: In your Implementation file check it like below : </p> <pre><code> if(!UserDefaultsManager.isFirstTimeLaunch()) { // Your code here. let introVC = self.storyboard?.instantiateViewController(withIdentifier: "intro") self.present(introVC!, animated: false, completion: nil) // Update value in user defaults UserDefaultsManager.setIsFirstTimeLaunch(true) } </code></pre>
Getting SignalR IConnectionManager GetHubContext working in Startup.cs in aspnet core <p>I can't seem to the following code working. All I'm doing is in <code>ConfigureServies</code> calling <code>_serviceProvider.GetService&lt;IConnectionManager&gt;();</code> and saving it in a static field and trying to use it later to get access to a <code>IConnectionManager</code> and subsequently call <code>GetHubContext&lt;MyHub&gt;</code> so I can broadcast messages to all connected clients.</p> <pre><code>_connectionManager.GetHubContext&lt;MyHub&gt;().Clients.All.doSomethingOnClients(); </code></pre> <p>Just as a test, the same line of code inside a webapi controller action method works fine! (with IConnectionManager injected via constructor). That makes me believe my signalr set up is just fine, just how I got things in the startup class is wrong somewhere. <code>GetHashCode</code> on the <code>IConnectionManager</code> in startup and my controller gives different hash codes. I just need to hook things up on the ApplicationLifetime OnStartUp ...</p> <p>Can you help me understand where things are going wrong please?</p> <pre><code>public class Startup { public static IServiceProvider _serviceProvider; public static IConnectionManager _connectionManager; private readonly IHostingEnvironment _hostingEnv; public IConfigurationRoot Configuration { get; } public Startup (IHostingEnvironment env) { // ... } public void ConfigureServices (IServiceCollection services) { // .... services.AddSignalR(options =&gt; { options.Hubs.EnableDetailedErrors = true; }); services.AddMvc(); // ... _serviceProvider = services.BuildServiceProvider(); _connectionManager = _serviceProvider.GetService&lt;IConnectionManager&gt;(); } public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime) { // ... applicationLifetime.ApplicationStarted.Register(OnStartUp); // ... app.UseMvc(routes =&gt; { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); app.UseSignalR(); // ... } public void OnStartUp () { var x = _serviceProvider.GetService&lt;MySingletonObject&gt;(); // MySingletonObject has a VersionUpdated event handler x.VersionUpdated += OnUpdate; } private void OnUpdate (object sender, EventArgs e) { // I get here everytime my singleton gets updated fine! // but the following does not work _connectionManager.GetHubContext&lt;MyHub&gt;().Clients.All.doSomethingOnClients(); } } </code></pre> <p>I am using "Microsoft.AspNetCore.SignalR.Server/0.2.0-alpha1-22362".</p>
<p>1st thing is to realize this version of SignalR isn't shipping, it's just alpha. The problem you're having is because you're building 2 service providers and they're not talking to each other. You call <code>BuildServiceProvider()</code> instead of injecting the <code>IConnectionManager</code> into your Configure method. You can also clean up a lot of the service locator pattern by injecting dependencies directly into configure and then using them in the callbacks.</p> <pre><code>public class Startup { public IConfigurationRoot Configuration { get; } public Startup (IHostingEnvironment env) { // ... } public void ConfigureServices (IServiceCollection services) { // .... services.AddSignalR(options =&gt; { options.Hubs.EnableDetailedErrors = true; }); services.AddMvc(); // ... } public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime, MySingletonObject obj, IHubContext&lt;MyHub&gt; context) { // ... applicationLifetime.ApplicationStarted.Register(() =&gt; OnStartUp(obj, context)); // ... app.UseMvc(routes =&gt; { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); app.UseSignalR(); // ... } public void OnStartUp(MySingletonObject obj, IHubContext&lt;MyHub&gt; context) { // MySingletonObject has a VersionUpdated event handler obj.VersionUpdated += (sender, e) =&gt; { context.Clients.All.doSomethingOnClients(); }; } } </code></pre> <p>Even cleaner would be a another service that would compose everything so you don't end up with so many arguments in your startup method.</p>
How to load the embeded video only after some click-event was triggered. jQuery <p>What I have now satisfies me in terms of an overall effect: Click on "show me", it displays an YT Video, when clicked once again - vid will hide etc. BUT even when site is loaded in the first place (and YT video is hidden) - all of its (Mb) size is counted as it was displayed causing the website to load slowly. My question is how to load the embeded video (with its size) only after I clicked on "Show me" element.</p> <p>This is what I have:</p> <p><br>HTML:</p> <pre><code>&lt;div class="#"&gt; &lt;span class="#" id="show_me"&gt;&lt;i class="icon fa-angle-down"&gt;&lt;/i&gt;Show Me&lt;/span&gt; &lt;span class="#" id="shown"&gt; &lt;iframe width="100%" height="315" src="https://www.youtube.com/embed/#" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;/span&gt; &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code>$(document).ready(function(){ $("#show_me").click(function(){ $("#shown").toggle(); }); }); </code></pre> <p>CSS:</p> <pre><code>#shown { display: none; } </code></pre>
<p>Try something like this:</p> <p>HTML:</p> <pre><code>&lt;div class="#"&gt; &lt;a href="#" id="show_me"&gt;&lt;i class="icon fa-angle-down"&gt;&lt;/i&gt;Show Me&lt;/a&gt; &lt;div id="i_frame"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code>$(document).ready(function(){ $("#show_me").click(function(e){ e.preventDefault(); if ($(this).is(".opened") ) { $(this).removeClass("opened"); $(this).find(".icon").removeClass("fa-angle-up").addClass("fa-angle-down"); $("#i_frame").hide().html(""); } else { $(this).addClass("opened"); $(this).find(".icon").removeClass("fa-angle-down").addClass("fa-angle-up"); $("#i_frame").show().html("&lt;iframe width='100%' height='315' src='https://www.youtube.com/embed/#' frameborder='0' allowfullscreen&gt;&lt;/iframe&gt;"); } }); }); </code></pre> <p>CSS:</p> <pre><code>#i_frame { display: none; } </code></pre> <p><a href="https://jsfiddle.net/jeremykenedy/fkcnncjm/" rel="nofollow">https://jsfiddle.net/jeremykenedy/fkcnncjm/</a></p>
How to resolve scala.MatchError when creating a Data Frame <p>I have text file which has complex structured row. I am using customer converter which converts the given string(line) to Pojo class(countryInfo). After converting, I am building DF. The POJO class has a field which is a List of Custome Type(GlobalizedPlayTimeWindows). I created a Struct which matches this GlobalizedPlayTimeWindows and trying to convert the existing Custom Type to the Struct but keep getting error. </p> <p>StructType I created :</p> <pre><code>import org.apache.spark.sql.types._ val PlayTimeWindow = StructType( StructField("startTime", DateType, true) :: StructField("endTime", DateType, true) :: Nil) val globalizedPlayTimeWindows = StructType( StructField( "countries", ArrayType(StringType, true), true ) :: StructField( "purchase", ArrayType(PlayTimeWindow, true), true ) :: StructField( "rental", ArrayType(PlayTimeWindow, true), true ) :: StructField( "free", ArrayType(PlayTimeWindow, true), true ) :: StructField( "download", ArrayType(PlayTimeWindow, true), true ) :: StructField( "advertisement", ArrayType(PlayTimeWindow, true), true ) :: StructField( "playTypeIds", ArrayType(PlayTimeWindow, true), true ) :: StructField( "benefitIds", MapType(StringType, ArrayType(PlayTimeWindow, true), true), true) :: Nil) val schema = StructType( StructField("id", StringType, true) :: StructField("jazzCount", IntegerType, true) :: StructField("rockCount", IntegerType, true) :: StructField("classicCount", IntegerType, true) :: StructField("nonclassicCount", IntegerType, true) :: StructField("musicType", StringType, true) :: StructField( "playType", ArrayType(globalizedPlayTimeWindows, true), true) :: Nil) </code></pre> <p>Data frame creation :</p> <pre><code>val mappingFile = sc.textFile("s3://input.....") val inputData = mappingFile.map(x=&gt; { val countryInfo = MappingUtils.getCountryInfo(x) val id = countryInfo.getId val musicType = if(countryInfo.getmusicType != null &amp;&amp; StringUtils.isNotBlank(countryInfo.getmusicType)) countryInfo.getmusicType else "UNKOWN_TYPE" val classicWestern = if (countryInfo.getClassic() != null &amp;&amp; countryInfo.getClassic.size() &gt; 0) true else false var nonclassicCount : Int = 0 var classicCount : Int = 0 if (classicWestern) { classicCount = 1 } else { nonclassicCount = 1 } val jazzrock = if (countryInfo.getmusicType() != null &amp;&amp; countryInfo.getmusicType != "JAZZ") true else false var jazzCount : Int = 0 var rockCount : Int = 0 if (jazzrock) { jazzCount = 1 } else { rockCount = 1 } val playType = if(countryInfo.getPlayTimeWindows != null &amp;&amp; countryInfo.getPlayTimeWindows.size &gt; 0 ) { countryInfo.getPlayTimeWindows.asScala.toList } else null (id, jazzCount, rockCount, classicCount, nonclassicCount, musicType ,playType) }).map{case (id, jazzCount, rockCount, classicCount, nonclassicCount, musicType,playType) =&gt; Row(id, jazzCount, rockCount, classicCount, nonclassicCount, musicType,playType) }.persist(DISK_ONLY) val inputDataDF = sqlContext.createDataFrame(inputData, schema) </code></pre> <p>inputDataDF.printSchema :</p> <pre><code>root |-- id: string (nullable = true) |-- jazzCount: integer (nullable = true) |-- rockCount: integer (nullable = true) |-- classicCount: integer (nullable = true) |-- nonclassicCount: integer (nullable = true) |-- musicType: string (nullable = true) |-- playType: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- countries: array (nullable = true) | | | |-- element: string (containsNull = true) | | |-- purchase: array (nullable = true) | | | |-- element: struct (containsNull = true) | | | | |-- startTime: date (nullable = true) | | | | |-- endTime: date (nullable = true) | | |-- rental: array (nullable = true) | | | |-- element: struct (containsNull = true) | | | | |-- startTime: date (nullable = true) | | | | |-- endTime: date (nullable = true) | | |-- free: array (nullable = true) | | | |-- element: struct (containsNull = true) | | | | |-- startTime: date (nullable = true) | | | | |-- endTime: date (nullable = true) | | |-- download: array (nullable = true) | | | |-- element: struct (containsNull = true) | | | | |-- startTime: date (nullable = true) | | | | |-- endTime: date (nullable = true) | | |-- advertisement: array (nullable = true) | | | |-- element: struct (containsNull = true) | | | | |-- startTime: date (nullable = true) | | | | |-- endTime: date (nullable = true) | | |-- playTypeIds: array (nullable = true) | | | |-- element: struct (containsNull = true) | | | | |-- startTime: date (nullable = true) | | | | |-- endTime: date (nullable = true) | | |-- benefitIds: map (nullable = true) | | | |-- key: string | | | |-- value: array (valueContainsNull = true) | | | | |-- element: struct (containsNull = true) | | | | | |-- startTime: date (nullable = true) | | | | | |-- endTime: date (nullable = true) </code></pre> <p>Struct's equivalent POJO :</p> <pre><code>@Data public GlobalizedPlayTimeWindows( private final List&lt;String&gt; countries; private final List&lt;PlayTimeWindow&gt; purchase; private final List&lt;PlayTimeWindow&gt; rental; private final List&lt;PlayTimeWindow&gt; free; private final List&lt;PlayTimeWindow&gt; download; private final List&lt;PlayTimeWindow&gt; advertisement; private final List&lt;PlayTimeWindow&gt; preorderExclusive; private final Map&lt;String, List&lt;PlayTimeWindow&gt;&gt; playTypeIds; } @Data public class PlayTimeWindow { private final Date startTime; private final Date endTime; } </code></pre> <p>The error I am getting :</p> <pre><code>org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 12.0 failed 4 times, most recent failure: Lost task 0.3 in stage 12.0 (TID 393, ip-172-31-14-43.ec2.internal): scala.MatchError: GlobalizedPlayTimeWindows(countries=[US], purchase=null, rental=null, free=null, download=null, advertisement=null, preorderExclusive=null, playTypeIds=null) (of class com.model.global.GlobalizedPlayTimeWindows) at org.apache.spark.sql.catalyst.CatalystTypeConverters$StructConverter.toCatalystImpl(CatalystTypeConverters.scala:255) at org.apache.spark.sql.catalyst.CatalystTypeConverters$StructConverter.toCatalystImpl(CatalystTypeConverters.scala:250) at org.apache.spark.sql.catalyst.CatalystTypeConverters$CatalystTypeConverter.toCatalyst(CatalystTypeConverters.scala:102) at org.apache.spark.sql.catalyst.CatalystTypeConverters$ArrayConverter$$anonfun$toCatalystImpl$2.apply(CatalystTypeConverters.scala:163) at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) at scala.collection.immutable.List.foreach(List.scala:318) at scala.collection.TraversableLike$class.map(TraversableLike.scala:244) at scala.collection.AbstractTraversable.map(Traversable.scala:105) at org.apache.spark.sql.catalyst.CatalystTypeConverters$ArrayConverter.toCatalystImpl(CatalystTypeConverters.scala:163) at org.apache.spark.sql.catalyst.CatalystTypeConverters$ArrayConverter.toCatalystImpl(CatalystTypeConverters.scala:153) at org.apache.spark.sql.catalyst.CatalystTypeConverters$CatalystTypeConverter.toCatalyst(CatalystTypeConverters.scala:102) at org.apache.spark.sql.catalyst.CatalystTypeConverters$StructConverter.toCatalystImpl(CatalystTypeConverters.scala:260) at org.apache.spark.sql.catalyst.CatalystTypeConverters$StructConverter.toCatalystImpl(CatalystTypeConverters.scala:250) at org.apache.spark.sql.catalyst.CatalystTypeConverters$CatalystTypeConverter.toCatalyst(CatalystTypeConverters.scala:102) at org.apache.spark.sql.catalyst.CatalystTypeConverters$$anonfun$createToCatalystConverter$2.apply(CatalystTypeConverters.scala:401) at org.apache.spark.sql.SQLContext$$anonfun$6.apply(SQLContext.scala:492) at org.apache.spark.sql.SQLContext$$anonfun$6.apply(SQLContext.scala:492) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$$anon$10.next(Iterator.scala:312) at scala.collection.Iterator$class.foreach(Iterator.scala:727) at scala.collection.AbstractIterator.foreach(Iterator.scala:1157) at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103) at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47) at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273) at scala.collection.AbstractIterator.to(Iterator.scala:1157) at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265) at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1157) at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252) at scala.collection.AbstractIterator.toArray(Iterator.scala:1157) at org.apache.spark.sql.execution.SparkPlan$$anonfun$5.apply(SparkPlan.scala:212) at org.apache.spark.sql.execution.SparkPlan$$anonfun$5.apply(SparkPlan.scala:212) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858) at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66) at org.apache.spark.scheduler.Task.run(Task.scala:89) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:213) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Driver stacktrace: at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1431) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1419) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1418) at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59) at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47) at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1418) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799) at scala.Option.foreach(Option.scala:236) at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:799) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1640) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1599) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1588) at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48) at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:620) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1832) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1845) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1858) at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:212) at org.apache.spark.sql.execution.Limit.executeCollect(basicOperators.scala:165) at org.apache.spark.sql.execution.SparkPlan.executeCollectPublic(SparkPlan.scala:174) at org.apache.spark.sql.DataFrame$$anonfun$org$apache$spark$sql$DataFrame$$execute$1$1.apply(DataFrame.scala:1538) at org.apache.spark.sql.DataFrame$$anonfun$org$apache$spark$sql$DataFrame$$execute$1$1.apply(DataFrame.scala:1538) at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:56) at org.apache.spark.sql.DataFrame.withNewExecutionId(DataFrame.scala:2125) at org.apache.spark.sql.DataFrame.org$apache$spark$sql$DataFrame$$execute$1(DataFrame.scala:1537) at org.apache.spark.sql.DataFrame.org$apache$spark$sql$DataFrame$$collect(DataFrame.scala:1544) at org.apache.spark.sql.DataFrame$$anonfun$head$1.apply(DataFrame.scala:1414) at org.apache.spark.sql.DataFrame$$anonfun$head$1.apply(DataFrame.scala:1413) at org.apache.spark.sql.DataFrame.withCallback(DataFrame.scala:2138) at org.apache.spark.sql.DataFrame.head(DataFrame.scala:1413) at org.apache.spark.sql.DataFrame.take(DataFrame.scala:1495) at org.apache.spark.sql.DataFrame.showString(DataFrame.scala:171) at org.apache.spark.sql.DataFrame.show(DataFrame.scala:394) at org.apache.spark.sql.DataFrame.show(DataFrame.scala:355) at org.apache.spark.sql.DataFrame.show(DataFrame.scala:363) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$$$$$c57ec8bf9b0d5f6161b97741d596ff0$$$$wC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:163) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$$$$$c57ec8bf9b0d5f6161b97741d596ff0$$$$wC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:168) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$$$$$c57ec8bf9b0d5f6161b97741d596ff0$$$$wC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:170) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$$$$$c57ec8bf9b0d5f6161b97741d596ff0$$$$wC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:172) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$$$$$c57ec8bf9b0d5f6161b97741d596ff0$$$$wC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:174) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$$$$$c57ec8bf9b0d5f6161b97741d596ff0$$$$wC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:176) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$$$$$c57ec8bf9b0d5f6161b97741d596ff0$$$$wC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:178) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:180) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:182) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:184) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:186) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:188) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:190) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:192) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:194) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:196) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:198) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:200) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:202) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:204) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:206) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:208) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:210) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:212) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:214) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:216) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:218) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:220) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:222) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:224) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:226) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:228) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:230) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:232) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:234) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:236) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:238) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:240) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:242) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:244) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:246) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:248) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:250) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:252) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:254) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:256) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:258) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:260) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:262) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:264) at $iwC$$iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:266) at $iwC$$iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:268) at $iwC$$iwC$$iwC.&lt;init&gt;(&lt;console&gt;:270) at $iwC$$iwC.&lt;init&gt;(&lt;console&gt;:272) at $iwC.&lt;init&gt;(&lt;console&gt;:274) at &lt;init&gt;(&lt;console&gt;:276) at .&lt;init&gt;(&lt;console&gt;:280) at .&lt;clinit&gt;(&lt;console&gt;) at .&lt;init&gt;(&lt;console&gt;:7) at .&lt;clinit&gt;(&lt;console&gt;) at $print(&lt;console&gt;) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065) at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1346) at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:840) at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:871) at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:819) at org.apache.zeppelin.spark.SparkInterpreter.interpretInput(SparkInterpreter.java:664) at org.apache.zeppelin.spark.SparkInterpreter.interpret(SparkInterpreter.java:629) at org.apache.zeppelin.spark.SparkInterpreter.interpret(SparkInterpreter.java:622) at org.apache.zeppelin.interpreter.ClassloaderInterpreter.interpret(ClassloaderInterpreter.java:57) at org.apache.zeppelin.interpreter.LazyOpenInterpreter.interpret(LazyOpenInterpreter.java:93) at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:276) at org.apache.zeppelin.scheduler.Job.run(Job.java:170) at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:118) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) </code></pre> <p>Also tried to do implicit toDF from inputData :</p> <p>inputData.toDF.printSchema but getting error :</p> <pre><code>java.lang.UnsupportedOperationException: Schema for type com.model.global.GlobalizedPlayTimeWindows is not supported at org.apache.spark.sql.catalyst.ScalaReflection$class.schemaFor(ScalaReflection.scala:718) at org.apache.spark.sql.catalyst.ScalaReflection$.schemaFor(ScalaReflection.scala:30) at org.apache.spark.sql.catalyst.ScalaReflection$class.schemaFor(ScalaReflection.scala:667) at org.apache.spark.sql.catalyst.ScalaReflection$.schemaFor(ScalaReflection.scala:30) at org.apache.spark.sql.catalyst.ScalaReflection$$anonfun$schemaFor$1.apply(ScalaReflection.scala:693) at org.apache.spark.sql.catalyst.ScalaReflection$$anonfun$schemaFor$1.apply(ScalaReflection.scala:691) at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) at </code></pre>
<p>OK - to cut the long discussion short, here's a working solution. Basically you had two separate issues here:</p> <ol> <li><p>You expected Spark to be able to parse an arbitrary Java class into a DataFrame - that is not the case, Spark can only parse specific types, which are generally: Scala collections; Primitives; <code>java.sql.Date</code>; and any subclass of <code>scala.Product</code> - all case classes and tuples, for instance. So - as discussed in comments, the first thing to do is to convert your existing structure into such types.</p></li> <li><p>Your <code>schema</code> didn't match your Java class either - there were a few differences:</p> <ul> <li>Schema's <code>playType</code> was an <em>Array</em> of <code>GlobalizedPlayTimeWindows</code>, while your code created a <em>single</em> item and not an array </li> <li><code>globalizedPlayTimeWindows</code> schema contained <code>benefitIds</code> which doesn't exist in the Java class</li> <li><code>playTypeIds</code> schema was an <em>Array</em>, while the field with the same name in the Java class was a <code>Map</code></li> </ul></li> </ol> <p>So - I corrected all these (changed the schema to match the data, you can choose to fix these differently as long as they <em>match</em>) and completed the conversion of the Java classes into case classes:</p> <pre><code>// corrected schemas: val PlayTimeWindow = StructType( StructField("startTime", DateType, true) :: StructField("endTime", DateType, true) :: Nil) val globalizedPlayTimeWindows = StructType( StructField( "countries", ArrayType(StringType, true), true ) :: StructField( "purchase", ArrayType(PlayTimeWindow, true), true ) :: StructField( "rental", ArrayType(PlayTimeWindow, true), true ) :: StructField( "free", ArrayType(PlayTimeWindow, true), true ) :: StructField( "download", ArrayType(PlayTimeWindow, true), true ) :: StructField( "advertisement", ArrayType(PlayTimeWindow, true), true ) :: StructField( "preorderExclusive", ArrayType(PlayTimeWindow, true), true ) :: StructField( "playTypeIds", MapType(StringType, ArrayType(PlayTimeWindow, true), true), true ) :: Nil) val schema = StructType( StructField("id", StringType, true) :: StructField("jazzCount", IntegerType, true) :: StructField("rockCount", IntegerType, true) :: StructField("classicCount", IntegerType, true) :: StructField("nonclassicCount", IntegerType, true) :: StructField("musicType", StringType, true) :: StructField( "playType", globalizedPlayTimeWindows, true) :: Nil) // note the use of java.sql.Date, java.util.Date not supported case class PlayTimeWindowScala(startTime: java.sql.Date, endTime: java.sql.Date) case class GlobalizedPlayTimeWindowsScala (countries: List[String], purchase: List[PlayTimeWindowScala], rental: List[PlayTimeWindowScala], free: List[PlayTimeWindowScala], download: List[PlayTimeWindowScala], advertisement: List[PlayTimeWindowScala], preorderExclusive: List[PlayTimeWindowScala], playTypeIds: Map[String, List[PlayTimeWindowScala]]) // some conversion methods: def toSqlDate(jDate: java.util.Date): java.sql.Date = new java.sql.Date(jDate.getTime) import scala.collection.JavaConverters._ def toScalaWindowList(l: java.util.List[PlayTimeWindow]): List[PlayTimeWindowScala] = { l.asScala.map(javaWindow =&gt; PlayTimeWindowScala(toSqlDate(javaWindow.startTime), toSqlDate(javaWindow.endTime))).toList } def toScalaGlobalizedWindows(javaObj: GlobalizedPlayTimeWindows): GlobalizedPlayTimeWindowsScala = { GlobalizedPlayTimeWindowsScala( javaObj.countries.asScala.toList, toScalaWindowList(javaObj.purchase), toScalaWindowList(javaObj.rental), toScalaWindowList(javaObj.free), toScalaWindowList(javaObj.download), toScalaWindowList(javaObj.advertisement), toScalaWindowList(javaObj.preorderExclusive), javaObj.playTypeIds.asScala.mapValues(toScalaWindowList).toMap ) } val parsedJavaData: RDD[(String, Int, Int, Int, Int, String, GlobalizedPlayTimeWindows)] = mappingFile.map(x =&gt; { // your code producing the tuple }) // convert to Scala objects and into a Row: val inputData = parsedJavaData.map{ case (id, jazzCount, rockCount, classicCount, nonclassicCount, musicType, javaPlayType) =&gt; val scalaPlayType = toScalaGlobalizedWindows(javaPlayType) Row(id, jazzCount, rockCount, classicCount, nonclassicCount, musicType, scalaPlayType) } // now - this works val inputDataDF = sqlContext.createDataFrame(inputData, schema) </code></pre>
Using loops within CSV export - Ruby <p>I'm trying to DRY up my code and wondering if many people have experience with CSV's and ruby.</p> <p>My code is below. It works just... Its awful. </p> <p>I'm wondering if anyone has any ideas on how I could do the following:</p> <p>1 - How could I use a loop rather than explicit 1..10 that I've done. I did try a few ways but couldn't get them to work with CSV. 2 - Is there a nicer way to do headers in CSV? 3 - Any other ideas on how to make CSV code nicer?</p> <p>I initially went with this</p> <pre><code>(1..10).each do |number| end </code></pre> <p>However the csv system didn't like that one! It was thinking my end statements were incorrect however, I don't think this was the case. </p> <p>Here's my code. If you have any bright ideas you're awesome! Yes I know it's awful, just wondering how I could do it better! </p> <pre><code>require 'csv' class CampagignsCsv class &lt;&lt; self HEADERS = [ 'Job Title', 'Business Name', 'Business Contact Name', 'Location', 'Job Status', 'Created date', 'Last Modified date', '# Positions', 'Description', 'Std/Prem', 'Referral code (To discuss)', 'Coupon code (To discuss)', 'Question1', 'Knockout?1', 'Correct Answer1', 'Question2', 'Knockout?2', 'Correct Answer2', 'Question3', 'Knockout?3', 'Correct Answer3', 'Question4', 'Knockout?4', 'Correct Answer4', 'Question5', 'Knockout?5', 'Correct Answer5', 'Question6', 'Knockout?6', 'Correct Answer6', 'Question7', 'Knockout?7', 'Correct Answer7', 'Question8', 'Knockout?8', 'Correct Answer8', 'Question9', 'Knockout?9', 'Correct Answer9', 'Question10', 'Knockout?10', 'Correct Answer10' ].freeze def report puts 'campaigns_report.csv created in reporting_output folder' CSV.open("reporting_output/campagins_report.csv", "wb") do |csv| csv &lt;&lt; HEADERS Paddl::Models::Job.all.each do |job| csv &lt;&lt; [ job.title, job.employer.business_name, job.employer.profile.full_name, job.address, job.status, job.created_at, job.updated_at, job.num_of_positions, job.description, job.employer.account_type, 'null', 'null', job.job_questions.map { |item| item[:question] }[1], job.job_questions.map { |item| item[:knockout] }[1], job.job_questions.map { |item| item[:correct_answer] }[1], job.job_questions.map { |item| item[:question] }[2], job.job_questions.map { |item| item[:knockout] }[2], job.job_questions.map { |item| item[:correct_answer] }[2], job.job_questions.map { |item| item[:question] }[3], job.job_questions.map { |item| item[:knockout] }[3], job.job_questions.map { |item| item[:correct_answer] }[3], job.job_questions.map { |item| item[:question] }[4], job.job_questions.map { |item| item[:knockout] }[4], job.job_questions.map { |item| item[:correct_answer] }[4], job.job_questions.map { |item| item[:question] }[5], job.job_questions.map { |item| item[:knockout] }[5], job.job_questions.map { |item| item[:correct_answer] }[5], job.job_questions.map { |item| item[:question] }[6], job.job_questions.map { |item| item[:knockout] }[6], job.job_questions.map { |item| item[:correct_answer] }[6], job.job_questions.map { |item| item[:question] }[7], job.job_questions.map { |item| item[:knockout] }[7], job.job_questions.map { |item| item[:correct_answer] }[7], job.job_questions.map { |item| item[:question] }[8], job.job_questions.map { |item| item[:knockout] }[8], job.job_questions.map { |item| item[:correct_answer] }[8], job.job_questions.map { |item| item[:question] }[9], job.job_questions.map { |item| item[:knockout] }[9], job.job_questions.map { |item| item[:correct_answer] }[9], job.job_questions.map { |item| item[:question] }[10], job.job_questions.map { |item| item[:knockout] }[10], job.job_questions.map { |item| item[:correct_answer] }[10] ] end end end end end </code></pre>
<p>How's this?</p> <pre><code>... job.employer.account_type, 'null', 'null', *1.upto(10).flat_map {|i| jq = job.job_questions[i] [jq[:question], jq[:knockout], jq[:correct_answer]] } ... </code></pre>
c++ parsing data from file I/O <p>I am writing code to 1. read in from a file via command line argument, 2. parse through each line of data (string) and 3. split the data into 4 substrings.</p> <p>say I have game.txt</p> <pre><code>3 overwatch|hanzo|junkrat|reinhart league of legends|vayne|ezreal|master yi starcraft|marine|zergling|zealot </code></pre> <p>the output that I want is each to have each line of data be splited into 4 substrings and I want to save each respective column to some sort of container. Possibly linkedlist of Strings, or array of strings. So, </p> <pre><code>overwatch hanzo junkrat reinhart league of legend vayne ezreal ... String nameOfGame = overwatch; String leastFav = hanzo; String fav = junkrat; String bestCharacter = reinhart; </code></pre> <p>I've tried several ways to go about this problem, but I cannot see the logic to have string read in and parsed at the same time. The concept is still new to me, and I need some advice on where to start and how to approach the problem.</p> <p>What could I do here?</p>
<p>You can use <a href="http://www.cplusplus.com/reference/fstream/ifstream/" rel="nofollow">ifstream</a> to read first number and <a href="http://en.cppreference.com/w/cpp/io/basic_istream/getline" rel="nofollow">lines</a> from file. For getting data from the any line, you can use <a href="http://www.cplusplus.com/reference/sstream/istringstream/?kw=istringstream" rel="nofollow">istringstream</a>. You can create the istringstream object with the line string. After that you can read components from the line by using method <a href="http://en.cppreference.com/w/cpp/io/basic_istream/getline" rel="nofollow">getline</a> with delim = '|'.</p> <p>After that you can print lines as you want</p> <pre><code>using String = std::string; int main(int argc, const char * argv[]) { // insert code here... std::ifstream inputFileStream("Input.txt"); int count; inputFileStream&gt;&gt;count; inputFileStream.ignore(1, '\n'); for(int i = 0; i &lt; count; i++) { String line; std::getline(inputFileStream, line); std::istringstream lineStream(line); String nameOfGame; String leastFav; String fav; String bestCharacter; std::getline(lineStream, leastFav, '|'); std::getline(lineStream, nameOfGame, '|'); std::getline(lineStream, fav, '|'); std::getline(lineStream, bestCharacter, '|'); std::cout&lt;&lt; leastFav &lt;&lt;"\n"&lt;&lt;nameOfGame&lt;&lt;"\n"&lt;&lt;fav&lt;&lt;"\n"&lt;&lt;bestCharacter&lt;&lt;"\n\n"; } return 0; } </code></pre>
STM32 SPI hardware and strict aliasing warnings <p>I've seen that the subject has been discussed in many other questions, but I can't quite find the answer for my particular case.</p> <p>I am working with a STM32F0 microcontroller. The top of the SPI reception/transmit FIFO are accessible by a memory access. This particular microcontroller allows me to read/write 8bits or 16bits from the top of the FIFO. More precisely, when a LDRB/STRB instruction is executed, 8bits are popped/pushed from/to the FIFO and when a LDRH/STRH instruction is executed, 16 bits are popped/pushed from/to the FIFO. </p> <p>The Hardware Abstraction Layer provided by STMicroelectronic proposes this syntax to read the SPI FIFO.</p> <pre><code>return *(volatile uint8_t*)&amp;_handle-&gt;Instance-&gt;DR; // Pop 1 byte return *(volatile uint16_t*)&amp;_handle-&gt;Instance-&gt;DR; // Pop 2 byte *(volatile uint8_t*)&amp;_handle-&gt;Instance-&gt;DR = val; // Push 1 byte *(volatile uint16_t*)&amp;_handle-&gt;Instance-&gt;DR = val; // Push 2 bytes </code></pre> <p>Where <code>DR</code> is a <code>uint32_t*</code> pointing on the top of the SPI FIFO</p> <p>I've built my software using this syntax and it does work fine. The only problem, is that g++ throws a lot of warning about type punning. More precisely:</p> <blockquote> <p>Inc/drivers/SPI.h:70:50: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] <code>return *(volatile uint16_t*)&amp;_handle-&gt;Instance-&gt;DR;</code></p> </blockquote> <p>After some readings it looks like using union is not a good idea in C++. I did try it anyway but got some problems. Actually accessing the memory through a pointer in a union makes my microcontroller crashes just like an unaligned memory access. </p> <p>static_cast and reinterpret_cast throws the sames warning as the C-style cast</p> <p>I cannot use <code>memcpy</code> with <code>void*</code> since my final goal is to make the compiler uses a LDRB/STRB and LDRH/STRH instruction.</p> <p>Others proposed solutions that I found on Stack Overflow were dependent on the use-case.</p> <p>Any suggestion?</p>
<p>I would suggest creating two specific pointers for the job. You can create them during initialisation or statically so you don't have to create them each time.</p> <pre><code>static uint8_t * const DR_Byte = (uint8_t * const)&amp;_handle-&gt;Instance-&gt;DR; static uint16_t * const DR_Word = (uint16_t * const)&amp;_handle-&gt;Instance-&gt;DR; </code></pre> <p>then simply read by:</p> <pre><code>uint8_t read_byte = *DR_Byte; uint16_t read_word = *DR_Word; </code></pre> <p>and write by:</p> <pre><code>*DR_Byte = byte_to_write; *DR_Word = word_to_write; </code></pre> <p>or something similar.</p>
When I click Element A, I want to change text of Element B <p>The idea is that when I click on h1.question, the string in h1.answer will change to the string in h1.question's data-text-swap. For example, if I click "What is wrong with you?", I should see the answer "Nothing" at h1.answer.</p> <p>I've tried using .text() but I think it isn't the right answer because I plan to put 10 questions and writing .text() 10 times is a bit ridiculous.</p> <p>Help! </p> <p>Update: Wow! Thanks so much for the answers! All the answers here have been really swift and easy to understand. I'm going to look at them again tonight. Thanks so much!!</p> <pre><code>&lt;h1 class="answer"&gt;Answer here&lt;/h1&gt;&lt;/div&gt; &lt;h1 class="question" data-text-swap="Nothing"&gt;What is wrong with you?&lt;/h1&gt; &lt;h1 class="question" data-text-swap="Good!"&gt;How is the weather today?&lt;/h1&gt; &lt;h1 class="question" data-text-swap="Everything"&gt;What is wrong with him?&lt;/h1&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $("h1.question").click(ontop); function ontop() { $("h1.answer").text(("h1.question").data("text-swap")); } &lt;/script&gt; </code></pre>
<p>you are binding the click handler on all h1 with class 'question', so if you just reference the clicked element dynamically, you end up with a (almost) one-liner:</p> <pre><code>$('h1.question').on('click', function() { $('h1.answer').text($(this).attr('data-text-swap')); }); </code></pre> <p>no need to write text() 10 times...</p> <p>this assumes that you always have exactly one 'answer' element. if you have an 'answer' element per question, you should traverse to it from the $(this) obj.</p>
Updating List<> used in xaml and reload frame <p>So i have an XML file that i load data into a List&lt;> from. That means that i have a main list that contains all the data i need.</p> <p>From that list i the create variable "sub" lists that i then will use to present data, as needed.</p> <p>My main window (as for now) contains a frame that i use to load in pages.</p> <p>My problem is, that i can't figure out how you change the data to be shown on a page, reload it and keep it from showing the standard data.</p> <p>So i think there a two ways of attacking this, but i need advise on what is the right(working) way.</p> <p>So on my page1 (loaded into the frame) i have the following code:</p> <pre><code>public sealed partial class Page1 : Page { public List&lt;Book&gt; Books; public List&lt;Book&gt; ts1; public Page1() { this.InitializeComponent(); Books = BookManager.GetBooks(); ts1 = Books.Where(p =&gt; p.bogNa == "Robert").ToList(); } private void Update_Click(object sender, RoutedEventArgs e) { ts1 = Books.Where(p =&gt; p.bogNa != "Robert").ToList(); } } </code></pre> <p>So i can with my button update the list, but obviously when i then reload the frame, we are just back to square one. Can i do it different from the page?</p> <p>In my page1 xaml i have this code:</p> <pre><code>&lt;GridView ItemsSource="{x:Bind ts1}" IsItemClickEnabled="True" SelectionMode="Multiple"&gt; &lt;GridView.ItemTemplate&gt; &lt;DataTemplate x:DataType="data:Book"&gt; &lt;StackPanel&gt; &lt;Grid Height="200"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="3*" /&gt; &lt;RowDefinition Height="1*" /&gt; &lt;RowDefinition Height="1*" /&gt; &lt;RowDefinition Height="1*" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Image Grid.Row="0" Name="pic" Width="150" Source="{x:Bind bogCo }"/&gt; &lt;TextBlock Grid.Row="1" FontSize ="20" Text="{x:Bind bogNa}" /&gt; &lt;TextBlock Grid.Row="2" FontSize ="16" Text="{x:Bind bogRe}"/&gt; &lt;Button Grid.Row="3" Content="More Info" FontSize="16"&gt; &lt;Button.Flyout&gt; &lt;Flyout x:Name="FlyoutTest"&gt; &lt;TextBlock Text="{x:Bind bogAr}"&gt; &lt;/TextBlock&gt; &lt;/Flyout&gt; &lt;/Button.Flyout&gt; &lt;/Button&gt; &lt;/Grid&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/GridView.ItemTemplate&gt; &lt;/GridView&gt; </code></pre> <p>Is there a way to change </p> <pre><code>&lt;GridView ItemSource="{x:bind ts1}" ... </code></pre> <p>To a different page than page1, like the MainPage?</p> <p>Iv'e looked into making a <strong>data template</strong> but i don't know is that is the way to go? because i don't want to spend my time on that, for now, if it leads to the same problems.</p>
<p>One simple way to solve this problem would be to enable the <code>NavigationCacheMode</code> for Page1.</p> <p>This caches the state of page1 and shows the old state when reopening the page. Just remember that you cannot empty the cache once the page is initialized. Also the <code>NavigationCacheMode</code> must be set in the constructor of the page.</p> <pre><code>public Page1() { this.InitializeComponent(); NavigationCacheMode = NavigationCacheMode.Enabled; // or NavigationCacheMode.Required if you want to ignore caching limits. Books = BookManager.GetBooks(); ts1 = Books.Where(p =&gt; p.bogNa == "Robert").ToList(); } </code></pre> <p>But like Inbar Barkai said, a cleaner solution would be to keep the ViewModel of page1.</p>
How do I make powershell stop showing this message whenever I push <p>How do I make powershell stop showing the below message:</p> <blockquote> <p>github --credentials get: github: command not found</p> </blockquote> <p>This occurs whenever I try to <code>ssh</code> for <code>git push</code> or <code>git pull</code>.</p>
<p>Check you git remote -v: it you see https, it is not an ssh url.<br> Make sure push or pull are using an ssh url with:</p> <pre><code>git remote set-url origin git@github.com:username/repo.git </code></pre> <p>If you are using https, Git will try and use a credential helper: see if <code>git config -l | grep cred</code> returns anything. That would explain the <code>github: command not found</code> part.</p> <p>If you have, go to your repo and type:</p> <pre><code>cd /path/to/my/repo git config credential.helper "" </code></pre> <p>If your git is recent enough (<a href="http://stackoverflow.com/a/36435803/6309">Git 2.9+</a>), that will prevent any credential helper to be active in your repo.</p>
why does the c value gets repeated in the given code? <p>1.This is my code to convert binary to decimal but its not working.The c value gets repeated for some reasons.</p> <pre><code>/** * Created by Ranjan Yadav on 11.10.2016. */ public class BinaryToDecimal { public static void main(String[] args) { java.util.Scanner read = new java.util.Scanner(System.in); System.out.println("Enter a binary number: "); int binary = read.nextInt(); int total = 0; int n = 1; int c = 0; int number = 0; while (binary != 0) { c = binary % ((int) Math.pow(10, n)); binary = binary / 10; number = c * (int)(Math.pow(2, (n - 1))); total += number; ++n; } System.out.printf("The decimal of the binary is %d", total); } } </code></pre>
<p>You were <strong>increasing n by 1</strong> and <strong>dividing binary by 10 raised to n</strong> at same time. Due to this, you were not able to fetch the unit's digit of binary number after 1st iteration. To solve this issue, you need to get binary modulo 10 (not 10 raised to n) in each iteration and also keep the statement of binary divided by 10. </p> <p>I have simplified and also made some small changes to your code to increase readability. Here is the corrected main method : </p> <pre><code>public static void main (String[] args){ java.util.Scanner read = new java.util.Scanner(System.in); System.out.println("Enter a binary number: "); int binary = read.nextInt(); int total = 0; int n = 0; int c = 0; int number = 0; while (binary != 0) { c = binary % 10; binary = binary / 10; number = c * (int)(Math.pow(2, n)); total += number; ++n; } System.out.println("The decimal of the binary is " + total); } </code></pre> <p>The code is working and producing desired results. Let me know in case you have any further doubts.</p>
Is there a simple method to get properties for all keys in javascript object? <p>So I've created this JS code to get a map where every word in a string is the key and the amount of times that word appears is the value.</p> <pre><code>var txtArray = txtVar.split(" "); var txtMap = {}; for (var i = 0; i&lt;txtArray.length;i++){ if(txtArray[i] in txtMap) txtMap[txtArray[i]] += 1; else txtMap[txtArray[i]] = 1; } </code></pre> <p>Now i need to sort them so that I can somehow rank them by the 10 longest words and 10 most used words and so on and I guess I could find a way to do it by making a for loop where i stored them in arrays and then pushed the oldest "top" word up or down the list when a new one comes along, but I think there must be a less awkward way to do this task?</p>
<p>It's probably an adequate approach to do as you're currently doing, then sorting/slicing those results when you're done:</p> <pre><code>var allWords = Object.keys(txtMap); var tenMostFrequent = allWords .sort((a, b) =&gt; txtMap[b] - txtMap[a]) .slice(0, 10); var longestWords = allWords .sort((a, b) =&gt; b.length - a.length) .slice(0, 10); </code></pre>
Ruby 100 doors returning 100 nil <p>I'm solving the <a href="https://www.rosettacode.org/wiki/100_doors" rel="nofollow">'100 doors' problem from Rosetta Code</a> in Ruby. Briefly,</p> <ul> <li>there are 100 doors, all closed, designated 1 to 100</li> <li>100 passes are made, designated 1 to 100</li> <li>on the ith pass, every ith door is "toggled": opened if it's closed, closed if it's open</li> <li>determine the state of each door after 100 passes have been completed.</li> </ul> <p>Therefore, on the first pass all doors are opened. On the second pass even numbered doors are closed. On the third pass doors <code>i</code> for which <code>i%3 == 0</code> are toggled, and so on.</p> <p>Here is my attempt at solving the problem.</p> <pre><code>visit_number = 0 door_array = [] door_array = 100.times.map {"closed"} until visit_number == 100 do door_array = door_array.map.with_index { |door_status, door_index| if (door_index + 1) % (visit_number + 1) == 0 if door_status == "closed" door_status = "open" elsif door_status == "open" door_status = "closed" end end } visit_number += 1 end print door_array </code></pre> <p>But it keeps printing me an array of 100 nil when I run it: <a href="http://i.stack.imgur.com/BfoNH.jpg" rel="nofollow">Look at all this nil !</a></p> <p>What am I doing wrong?</p>
<p>That's what your <code>if</code> clauses return. Just add a return value explicitly.</p> <pre><code>until visit_number == 100 do door_array = door_array.map.with_index { |door_status, door_index| if (door_index + 1) % (visit_number + 1) == 0 if door_status == "closed" door_status = "open" elsif door_status == "open" door_status = "closed" end end door_status } visit_number += 1 end </code></pre> <p>OR:</p> <pre><code>1.upto(10) {|i| door_array[i*i-1] = 'open'} </code></pre>
User input within functions, can I make it 'global'? <p>The best way I can phrase this question = <em>'Can I use a 'programmer' defined function to grab user input, and then use that input within another user defined function?'</em></p> <p>Background info:</p> <pre><code> 1. Python 3.x please 2. I understand function statements are usually local, not global, but I am unsure if that is 100% the case 3. I usually grab user input during the main function, and then call a function to act on that input, so even though it is 'local' the called function is using that data </code></pre> <p>- I want to know if there is a way to create a function that will be able to grab user input, and then use the information gathered within that function within any other user defined function.</p> <p>I would like to create a function that will gather user input, instead of grabbing in the main function using statements, if possible. So that way I can grab a list from the user using that function, instead of using my global statement of L</p> <p>Here is my current example:</p> <pre><code>#Creating global list to be called on by the functions L = [1,2,3,4,5,6,7,8,9] #total is 45 # Sum a list using 'For Loop' def sumF(n): total = 0 for i in L: total += i return total # Sum a list using 'While Loop' def sumW(x): count = 0 total = 0 while count &lt; len(L): total += L[count] count += 1 return total # Sum a list using Recursion def sumR(g,h): if h == 0: return 0 else: return g[h-1] + sumR(g,h-1) def combine(a,b): L3 = [] a = a.split() b = b.split() # Currently only works when lists have same length? for i in range(len(a)): L3.append(a[i]) L3.append(b[i]) print('The combination of the lists = %s' %L3) #main funtion to call all the other functions def main(): print('The number %d was calculated using the for-loop function.' %(sumF(L))) print('The number %d was calculated using the while-loop function.' %(sumW(L))) print('The number %d was calculated using a recursive function.' %(sumR(L,len(L)))) user = input('Enter a list of elements, with each being seperated by one space: ') user2 = input('Enter a second list of elements, with each being seperated by one space: ') combine(user,user2) #selection control statement to initiate the main function before all others main() </code></pre>
<p>Declare the variable <code>global</code> inside the function</p> <pre><code>&gt;&gt;&gt; def func(max_input): global list1 list1=[] for i in range(max_input): list1.append(input('enter item and press enter')) return list1 #Optional </code></pre> <p><strong>Output</strong></p> <pre><code>&gt;&gt;&gt; &gt;&gt;&gt; func(5) enter list item and enter1 enter list item and enter2 enter list item and enter3 enter list item and enter4 enter list item and enter5 &gt;&gt;&gt; list1 ['1', '2', '3', '4', '5'] &gt;&gt;&gt; </code></pre> <p>If you are refering the variable from function which is inside another function then refer it as <code>nonlocal</code></p> <pre><code>&gt;&gt;&gt;def func2(): var1=[] #local to func2 def func3(): nonlocal var1 #refers to var1 in func2 function </code></pre>
Why are constants not defined when using p5.js in instance mode? <p>I'm probably missing something very obvious here. I can use p5.js in global mode and use constants for textAlign with no problem, e.g. CENTER.</p> <p>Here is global mode code where it works fine:</p> <pre><code>function setup() { var canvas = createCanvas(720, 400); canvas.parent('main_canvas'); }; function draw() { textSize(32); textAlign(CENTER); text("word", 50, 50); }; </code></pre> <p>However when I try using CENTER in instance mode I get:</p> <pre><code>Uncaught ReferenceError: CENTER is not defined: </code></pre> <p>Here is instance mode code where it fails:</p> <pre><code>var s = function (p) { p.setup = function() { p.createCanvas(720, 400); }; p.draw = function() { p.textSize(32); p.textAlign(CENTER); p.text("word", 50, 50); }; }; var myp5 = new p5(s,'main_canvas'); </code></pre> <p>Any ideas on what I am missing here? </p>
<p>In global mode, all the P5.js functions <strong>and variables</strong> are added to the global namespace. In instance mode, all the P5.js functions <strong>and variables</strong> are added to the variable passed into the sketch function (in your case, your <code>p</code> variable).</p> <p>To use the <code>CENTER</code> variable, you have to get at it through the <code>p</code> variable.</p> <p>In other words, you need to do this:</p> <pre><code>p.textAlign(p.CENTER); </code></pre> <p>You'll also have to do this with other variables, like <code>mouseX</code> and <code>mouseY</code>.</p>
AngularJS cannot insert data to phpMyadmin (mySql) <p>I'm new for AngularJS but it seems like I can't insert any data to my database. I have followed few instructions but seem likes it doesn't work. When I click on submit button, nothing happen and no data has inserted to my database. Please help.</p> <p>Thanks a lot guys.</p> <p>view2.html</p> <pre><code> &lt;div ng-app="register" &gt; &lt;form name="form1" ng-controller="registerInsert" align="center"&gt; &lt;ul&gt; &lt;li class="err" ng-repeat="error in errors"&gt; {{ error}} &lt;/li&gt; &lt;/ul&gt; &lt;ul&gt; &lt;li class="info" ng-repeat="msg in msgs"&gt; {{ msg}} &lt;/li&gt; &lt;/ul&gt; &lt;div class="form-group col-md-6 col-xs-12 col-md-offset-3" &gt; &lt;label for="InputName" &gt;&lt;h1&gt;Please fill your informations&lt;/h1&gt;&lt;/label&gt; &lt;input type="text" class="form-control" ng-model="fName" placeholder="Firstname" &gt; &lt;/div&gt; &lt;div class="form-group col-md-6 col-xs-12 col-md-offset-3"&gt; &lt;input type="text" class="form-control" ng-model="lName" placeholder="Lastname" &gt; &lt;/div&gt; &lt;div class="form-group col-md-6 col-xs-12 col-md-offset-3"&gt; &lt;input type="text" class="form-control" ng-model="eMail" placeholder="E-Mail" &gt; &lt;/div&gt; &lt;div class="form-group col-md-6 col-xs-12 col-md-offset-3"&gt; &lt;input type="text" class="form-control" ng-model="userName" placeholder="Username" &gt; &lt;/div&gt;&lt;div class="form-group col-md-6 col-xs-12 col-md-offset-3"&gt; &lt;input type="password" class="form-control" ng-model="passWord" placeholder="Password" &gt; &lt;/div&gt; &lt;div class="form-group col-md-6 col-xs-12 col-md-offset-3"&gt; &lt;input type="text" class="form-control" ng-model="tel" placeholder="Telephone Number" &gt; &lt;/div&gt; &lt;div class="form-group col-md-6 col-xs-12 col-md-offset-3"&gt; &lt;button ng-click='SignUp();' class="btn btn-default" &gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; function registerInsert($scope, $http) { $scope.errors = []; $scope.msgs = []; $scope.SignUp = function() { $scope.errors.splice(0, $scope.errors.length); // remove all error messages $scope.msgs.splice(0, $scope.msgs.length); $http.post('save_register.php', {'fName':$scope.fName,'lName':$scope.lName,'eMail':$scope.eMail, 'userName':$scope.userName,'passWord':$scope.passWord,'tel':$scope.tel} ).success(function(data, status, headers, config) { if (data.msg != '') { $scope.msgs.push(data.msg); } else { $scope.errors.push(data.error); } }).error(function(data, status) { // called asynchronously if an error occurs // or server returns response with an error status. $scope.errors.push(status); }); } } &lt;/script&gt; save_register.php &lt;?php $data = json_decode(file_get_contents("php://input")); $userName = mysqli_real_escape_string($con,$data-&gt;userName); $passWord = mysqli_real_escape_string($con,$data-&gt;passWord); $fName = mysqli_real_escape_string($con,$data-&gt;fName); $lName = mysqli_real_escape_string($con,$data-&gt;lName); $eMail = mysqli_real_escape_string($con,$data-&gt;eMail); $tel = mysqli_real_escape_string($con,$data-&gt;tel); $accountStat = mysqli_real_escape_string($con,$data-&gt;accountStat); $verifyCode = mysqli_real_escape_string($con,$data-&gt;verifyCode ); $verifyStat = mysqli_real_escape_string($con,$data-&gt;verifyStat); $con = mysql_connect('localhost', 'root', ''); mysql_select_db('MiddleWork', $con); $qry_em = 'select count(*) as cnt from UserTest where Username ="' . $userName . '"'; $qry_res = mysql_query($qry_em); $res = mysql_fetch_assoc($qry_res); if ($res['cnt'] == 0) { $qry = 'INSERT INTO UserTest (Username,Password,Firstname,Lastname,Email,Tel) values ("' . $userName . '","' . $passWord . '","' . $fName . '""' . $lName . '","' . $eMail . '","' . $tel . '")'; $qry_res = mysql_query($qry); if ($qry_res) { $arr = array('msg' =&gt; "User Created Successfully!!!", 'error' =&gt; ''); $jsn = json_encode($arr); print_r($jsn); } else { $arr = array('msg' =&gt; "", 'error' =&gt; 'Error In inserting record'); $jsn = json_encode($arr); print_r($jsn); } } else { $arr = array('msg' =&gt; "", 'error' =&gt; 'User Already exists with same email'); $jsn = json_encode($arr); print_r($jsn); } </code></pre>
<p>Turn on error reporting or take a look at server log. You are obviously missing a comma in <code>INSERT</code> statement between <code>fName</code> and <code>lName</code>.</p>
SQLite: How to combine SQL of order limit with left join queries <p>I have a record of A, B, C and D.</p> <p>My SQL1 <code>SELECT * FROM main_table order by main_table.date desc limit 2</code> returns A and B.</p> <p>My SQL2 <code>SELECT * FROM main_table left join sub_table using (key) where sub_table._id is not null</code> returns B and C.</p> <p>I want to have a single SQL Statement that returns A, B and C. Basically, I want to join SQL1 or SQL2</p> <p>How could I combine this two SQLs (in SQLite) optimally?</p> <p>My data is as below</p> <pre><code> main_table _id date key 1 2016-08-04 D 2 2016-10-06 A 3 2016-09-04 B 4 2016-07-05 C sub_table _id age key 1 8 B 2 9 C </code></pre> <p>Desire Output</p> <pre><code>m._id m.date m.key s._id s.age s.key 2 2016-10-06 A 3 2016-09-04 B 1 8 B 4 2016-07-05 C 2 9 C </code></pre> <p>My logic of selection... I want to pick the top two latest data, and also data that has an age. The others I don't care (i.e. the D is not in top 2, and doesn't have an age).</p>
<p>If I read correctly, then a <code>UNION</code> might be what you have in mind:</p> <pre><code>SELECT * FROM (SELECT * FROM main_table LEFT JOIN sub_table USING (key) ORDER BY date DESC LIMIT 2) UNION SELECT * FROM main_table LEFT JOIN sub_table USING (key) WHERE sub_table._id IS NOT NULL </code></pre>
Type of expression is ambiguous without more context in Swift 3 <p>I am trying to learn Swift and am going through a tutorial on push notifications.</p> <pre><code>let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge , .Sound], categories: nil) </code></pre> <p>Is giving me the error</p> <blockquote> <p>"Type of expression is ambiguous without more context".</p> </blockquote> <p>I copy/pasted this line directly from a tutorial and have found this same line used on StackOverFlow.<br><br>What am I doing wrong?<br>I am using Xcode 8.</p>
<p>Look at the documentation for <code>UIUserNotificationSettings</code>. Its signature has changed in Swift 3 as has the values for the types.</p> <p>You need:</p> <pre><code>let settings = UIUserNotificationSettings(types: [.alert, .badge , .sound], categories: nil) </code></pre> <p>Of course if you are only supporting iOS 10 and later, then you shouldn't use <code>UIUserNotificationSettings</code> at all since it is now deprecated. Use <code>UNNotificationSettings</code> instead. But if you are still supporting iOS 9 or earlier, then using <code>UIUserNotificationSettings</code> is fine as long as you change to the updated syntax.</p>
:hover not working on div, working on other parts of page <p>My hover class is not working on my button div however it is working on other parts of my webpage including ones using the absolute position. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.desbutton { margin-left: 25px; margin-bottom: 25px; height: 36px; width: 113px; background-color: #4A6D81; border-radius: 2px; position: absolute; bottom: 0; } .desbutton:hover { background-color: #80999E; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="desbutton"&gt; &lt;p class="butText"&gt;READ MORE&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="https://jsfiddle.net/96kp9gcj/" rel="nofollow">Jsfiddle with full src</a></p>
<p>Please check : why do you have in your <code>.designCard</code> attr <code>z-index: -1</code>. This causes that your body element is <code>higher</code> then your card and because of this your hover is never "called"</p>
How to extract digits from a sentence in java? <pre><code>[{"id":1475280000,"high":0.01384629,"low":0.01155011,"area":13251.43990321,"quoteVolume":1073925.2309893,"averagevolume":0.01233925},{"id":1475366400,"high":0.0139987,"low":0.0119,"area":7535.00823446,"quoteVolume":573093.11152305,"averagevolume":0.01314796}] </code></pre> <p>Above is the data from which i want to extract digits. I want to extract id, area and average volume from above data and print the result in the form:</p> <pre><code>id1:1475280000 area1:13251.43990321 averagevolume1:0.01233925 id2:1475366400 area2:7535.00823446 averagevolume3:0.01314796 </code></pre>
<p>You can deserialize the json object wrapping the values in a Java object using jackson fasterxml and ObjectMapper:</p> <pre class="lang-java prettyprint-override"><code>class Values{ //With getters and setters int id; double area; double averageVolume; //Rest of the values in the json string } </code></pre> <p>Then your deserializer might look like: </p> <pre><code>public class Deserialize { private final ObjectMapper mapper; public DeserializeCollectionMessage() { mapper = new ObjectMapper(); } public Values deSerializeCollectionMessage(String jsonString) { Values val = new Values(); return mapper.readValue(jsonString, Values.class); } </code></pre> <p>Then you can extract the values from the Values object</p>
Unexpected value when counting the number of words in a textbox <pre><code>$scope.cal = function (){ var totalItems = stringSplit($scope.eatables); $scope.value = totalItems; if(totalItems == 0){ $scope.message = "Please enter something"; }else if(totalItems &lt;= 3){ $scope.message = "Enjoy!"; }else{ $scope.message = "TOO MUCH!"; } }; function stringSplit(string){ var array = string.split(" "); var x = array.length; return x; }; </code></pre> <p>I'm calling this function on <code>ng-click</code>, but when the input box is empty it is still giving a value of 1. Why is that?</p>
<p>How about this?</p> <pre><code>function stringSplit(string){ var array = string.split(" "); var x = array.length; return (array[i] === "" || array[i] === null || array[i] === undefined) ? 0 : x; //Check whether first element is empty }; </code></pre>
Fetch words in a sentence <p>I have string - <code>My name is "foo bar" I live in New York</code></p> <p>Now I want to split it to an array but words in double quotes should be considered as one.</p> <p>I have tried <code>input.split(' ')</code> but need some help how to handle strings inside double quotes.</p> <p>I want output as <code>['My', 'name', 'is', '"foo bar"', 'I', 'live', 'in', 'New', 'York']</code></p>
<p>Something along the lines of</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var str = 'My name is "foo bar" I live in New York'; console.log(str.split(/ |(".*?")/).filter(v=&gt;v));</code></pre> </div> </div> </p> <p>should do the trick</p>
Make an object that behaves like a slice <p>How can we make a class represent itself as a slice when appropriate?</p> <p>This didn't work:</p> <pre><code>class MyThing(object): def __init__(self, start, stop, otherstuff): self.start = start self.stop = stop self.otherstuff = otherstuff def __index__(self): return slice(self.start, self.stop) </code></pre> <p>Expected output:</p> <pre><code>&gt;&gt;&gt; thing = MyThing(1, 3, 'potato') &gt;&gt;&gt; 'hello world'[thing] 'el' </code></pre> <p>Actual output:</p> <pre><code>TypeError: __index__ returned non-(int,long) (type slice) </code></pre> <p>Inheriting from <code>slice</code> doesn't work either. </p>
<p>TLDR: It's impossible to make custom classes replace <code>slice</code> for builtins types such as <code>list</code> and <code>tuple</code>.</p> <hr> <p>The <code>__index__</code> method exists purely to provide an <em>index</em>, which is by definition an integer in python (see <a href="https://docs.python.org/3.5/reference/datamodel.html#object.__index__" rel="nofollow">the Data Model</a>). You cannot use it for resolving an object to a <code>slice</code>.</p> <p>I'm afraid that <code>slice</code> seems to be handled specially by python. The interface requires an actual slice; providing its signature (which also includes the <code>indices</code> method) is not sufficient. As you've found out, you cannot inherit from it, so you cannot create new types of <code>slice</code>s. Even Cython will not allow you to inherit from it.</p> <hr> <p>So why is <code>slice</code> special? Glad you asked. Welcome to the innards of CPython. Please wash your hands after reading this.</p> <p>So slice objects are described in <a href="https://raw.githubusercontent.com/python/cpython/c30098c8c6014f3340a369a31df9c74bdbacc269/Doc/c-api/slice.rst" rel="nofollow"><code>slice.rst</code></a>. Note these two guys:</p> <blockquote> <p>.. c:var:: PyTypeObject PySlice_Type</p> <p>The type object for slice objects. This is the same as :class:<code>slice</code> in the Python layer.</p> <p>.. c:function:: int PySlice_Check(PyObject *ob) Return true if <em>ob</em> is a slice object; <em>ob</em> must not be <em>NULL</em>.</p> </blockquote> <p>Now, this is actually implemented in <a href="https://github.com/python/cpython/blob/c30098c8c6014f3340a369a31df9c74bdbacc269/Include/sliceobject.h" rel="nofollow"><code>sliceobject.h</code></a> as :</p> <pre><code>#define PySlice_Check(op) (Py_TYPE(op) == &amp;PySlice_Type) </code></pre> <p>So <em>only</em> the <code>slice</code> type is allowed here. This check is actually used in <a href="https://github.com/python/cpython/blob/c30098c8c6014f3340a369a31df9c74bdbacc269/Objects/listobject.c#L2406" rel="nofollow"><code>list_subscript</code></a> (and <code>tuple subscript</code>, ...) <em>after</em> attempting to use the index protocol (so having <code>__index__</code> on a slice is a bad idea). A custom container class is free to overwrite <code>__getitem__</code> and use its own rules, but that's how <code>list</code> (and <code>tuple</code>, ...) does it.</p> <p>Now, why is it not possible to subclass <code>slice</code>? Well, <code>type</code> actually has a flag indicating whether something can be subclassed. It is checked <a href="https://github.com/python/cpython/blob/222b935769b07b8e68ec5b0494c39518d90112d1/Objects/typeobject.c#L1971" rel="nofollow">here</a> and generates the error you have seen:</p> <pre><code> if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) { PyErr_Format(PyExc_TypeError, "type '%.100s' is not an acceptable base type", base_i-&gt;tp_name); return NULL; } </code></pre> <p>I haven't been able to track down how <code>slice</code> (un)sets this value, but the fact that one gets this error means it does. This means you cannot subclass it.</p> <hr> <p>Closing remarks: After remembering some long-forgotten C-(non)-skills, I'm fairly sure this is not about optimization in the strict sense. All existing checks and tricks would still work (at least those I've found).</p> <p>After washing my hands and digging around in the internet, I've found a few references to similar "issues". <a href="http://grokbase.com/t/python/python-list/033r5nks47/type-function-does-not-subtype#20030324rcnwbkfedhzbaf3vmiuer3z4xq" rel="nofollow">Tim Peters has said all there is to say:</a></p> <blockquote> <p>Nothing implemented in C is subclassable unless somebody volunteers the work to make it subclassable; nobody volunteered the work to make the <em>[insert name here]</em> type subclassable. It sure wasn't at the top of my list <em>wink</em>.</p> </blockquote> <p>Also see <a href="http://stackoverflow.com/a/10114382/5349916">this thread</a> for a short discussion on non-subclass'able types.</p> <p>Practically all alternative interpreters replicate the behavior to various degrees: <a href="https://github.com/nakagami/jython3/blob/master/src/org/python/core/PyType.java#L65" rel="nofollow">Jython</a>, <a href="https://github.com/dropbox/pyston/issues/596" rel="nofollow">Pyston</a>, <a href="https://github.com/IronLanguages/main/blob/eedca3ee3c8260ef205a53c5ee11340b092a250a/Languages/IronPython/IronPython/Runtime/Types/NewTypeInfo.cs#L72" rel="nofollow">IronPython</a> and PyPy (didn't find out how they do it, but they do).</p>
After uprading to SupportMapFragment do you need a new google api map key? <p>My release build doesn't recognize my v2 google map api key. It works fine with a debug package name and corresponding debug key. I know the key and package name have to match. Is a new key required when upgrading to SupportMapFragment ?</p>
<p>There no relation between key and SupportMapFragment. Generate SHA for release key store and generate new API key from that. Then use that new API key within the app.</p>
any logs/steps to debug azure stream analytics job available? <p>Referring to the below link <a href="https://blogs.msdn.microsoft.com/streamanalytics/2016/04/18/troubleshooting-azure-stream-analytics-jobs-on-new-portal-2/" rel="nofollow">https://blogs.msdn.microsoft.com/streamanalytics/2016/04/18/troubleshooting-azure-stream-analytics-jobs-on-new-portal-2/</a> there is no such thing called "Audit logs" in stream analytics job !</p> <p>The issue is - My Eventhub has 'outgoing messages' but "No available data" in stream analytics job</p> <p>I raised support ticket. But minimum it will take 2 days to resolve in that way.</p>
<p>When using the classic portal, go to the Stream Analytics Job , tabpage "Dashboard" and look for the link to "Operation Logs" near the bottom right.</p> <p>In the new portal, go to the Stream Analytics Job and open the Activity log (second item of the menu, just below "Overview")</p>
Access Storyboard from embedded project <p>I have got two projects <strong>ProjectA</strong> and <strong>ProjectB</strong>, where <strong>ProjectA</strong> is the main project and <strong>ProjectB</strong> is embedded into <strong>ProjectA</strong>.</p> <p>When I try to access the storyboard of <strong>ProjectB</strong> from <strong>ProjectA</strong>, I get error the storyboard doesn't exist, understandably the storyboard from <strong>ProjectB</strong> is not added into the target of <strong>ProjectA</strong>.</p> <p>How would I reference the storyboard of the embedded project?</p> <p><a href="http://i.stack.imgur.com/og25x.png" rel="nofollow"><img src="http://i.stack.imgur.com/og25x.png" alt="enter image description here"></a></p>
<p>Try to save "Storyboard B" into Project A. Simply drag the storyboard into the Projact A's folder. Make sure to set in the App's overview the right storyboard as main.</p> <hr> <p>If this don't work, try to save the storyboard within the Finder, copy the storyboard from Project B and paste it into Project A>base.lproj</p>
Calling an instance method using autowired bean <p>I have three classes (Class <strong>A</strong>, Class <strong>B</strong>, Class <strong>C</strong>) in my application. </p> <p>I'm a spring beginner. Trying to inject a bean of Class <strong>B</strong> to use in Class <strong>A</strong> using <code>@Autowired</code> annotation. I want to make use of the Singleton behaviour of spring beans so that there will be only instance of Class <strong>B</strong> no matter how many times it is invoked from Class <strong>A</strong>. </p> <p>There's a method in Class <strong>B</strong> which I want to call from Class <strong>A</strong> using this bean of Class <strong>B</strong>. How can I do that? </p> <p>I know how to implement a singleton class in Java and then get the one and only instance to call it's methods but not sure how to do that using spring singleton beans. </p>
<p>Spring singleton is defined as "per container per bean"</p> <p>If you want singleton per spring container below is what needs to be done in your bean definition</p> <pre><code>&lt;bean id="myBean" class="MyBean"/&gt; </code></pre> <p>If you want the singleton per entire application and not per container, then I believe the only way you can do that is implement a Singleton pattern have a private constructor, access/retrieve it from its static method like getInstance. What you can do is allow spring to call a method that can in turn return an object</p> <pre><code>&lt;bean id="myBean" class="MyBean" factory-method="getInstance"&gt;&lt;/bean&gt; </code></pre>
Why does $(this) work differently depending on how callback is created? <p>I'm trying to display a table and cause certain actions to take place if the user clicks on a cell in the table. My Javascript (using jquery-3.1.1.min) looks like this:</p> <pre><code> $(function() { function tdHeader(key) { return '&lt;td class="mytable-cell" data-key="' + key + '"&gt;'; } function clickHandler() { alert("Key: " + $(this).data("key")); } function displayTable() { var tabHTML = '&lt;table class="mmmtab"&gt;'; tabHTML += '&lt;tr&gt;&lt;th&gt;Data1&lt;/th&gt;&lt;th&gt;Data2&lt;/th&gt;&lt;th&gt;Data3&lt;/th&gt;&lt;/tr&gt;'; for (var i = 0; i &lt; 3; i++) { tabHTML += '&lt;tr&gt;'; for (var j = 0; j &lt; 3; j++) { key = i + "-" + j; tabHTML += tdHeader(key) + ((i + 1) * (j + 1)) + '&lt;/td&gt;'; } tabHTML += '&lt;/tr&gt;'; } tabHTML += '&lt;/table&gt;'; $("#mytable").html(tabHTML); $(".mytable-cell").click(clickHandler); // Version 1 // $(".mytable-cell").click(function() {clickHandler();}); // Version 2 } displayTable(); }); </code></pre> <p>What I'm finding is that if I use Version 1 to set up the callback, then if I click on a cell, the alert box displays the correct key. However, if I use Version 2, the alert box says "Key: undefined".</p> <p>What's going on, and why does it make a difference which callback I use?</p> <p>[Assuming I need the Version 2 because I want to pass some local data to the handler, I can solve my problem by passing <code>$(this).data("key")</code> as a parameter to the handler. But I'd still like to know why it's doing this.]</p>
<p>jQuery calls the callback you pass to <code>click</code> in the context of the element the event belongs to. So for <code>$(".mytable-cell").click(clickHandler);</code> the <code>clickHandler</code> is called in the context of the given DOM element.</p> <p>For <code>$(".mytable-cell").click(function() {clickHandler();});</code> the anonymous function is called in the context of the DOM element and inside of this you call <code>clickHandler</code> in the context of <code>undefined</code> or the global object.</p> <p>You would need to write <code>$(".mytable-cell").click(function() { return clickHandler.apply(this, arguments); } );</code> if you want that the behavior is the same.</p>
Login into laravel 5.2 from other domain <p>I have a project with <strong>laravel 5.2</strong>. There is <strong>another system in .net</strong>. What I want is to get <strong>login into laravel 5.2 from .net system</strong>. For that, I'm <strong>making ajax call</strong> from .net app to laravel app. But laravel app is throwing <code>TokenMismatchException</code>. I know I have to send csrf token in request. But <strong>how to send csrf token from .net app</strong>. If anyone knows the answer, it will be appreciated.</p> <p>Here is my code.</p> <p><strong>.net app</strong></p> <pre><code>$.ajax({ type: 'POST', url: 'http://192.168.1.78/laravel-project/login', data: { email: 'xyz@xyz.com', password: 'pass' } }).success(function (response) { response = $.parseJSON(response); }).error(function () { alert('error'); }); </code></pre>
<p>If you need to send more information with javascript try this</p> <pre><code> jQuery.support.cors = true; $.ajax({ url: 'http://192.168.1.78/myproject/login', type: 'POST', dataType: dataType, data: data, crossDomain: true, cotentType: YOUR_CONTENT_TYPE, success: successCallback, error: errorCallback, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', SOMETHING.val()); } }); </code></pre> <p>To make this script right for your needs, you should read about <strong>CORS</strong>, <strong>crossDomain</strong> and <strong>xhr.setRequestHeader</strong> </p> <p>You can also use Postman (Chrome extension)</p> <p><a href="https://msdn.microsoft.com/fr-fr/library/ms536752(v=vs.85).aspx" rel="nofollow">xhr.setRequestHeader</a></p> <p><a href="http://www.java-success.com/chrome-postman-to-test-and-debug-restful-web-services/" rel="nofollow">Postman sample</a></p> <p><strong><em>EDIT</em></strong>: Did you read this? <a href="http://stackoverflow.com/questions/22066241/token-mismatch-exception-on-login-laravel">Token Mismatch Exception on Login (Laravel)</a></p> <p>Regards,</p>
Recycle-view inflating different row :- Getting exception while binding the data <p><br> I am working on the <code>Recyceview</code> with different item inflation. When i am <strong>NOT</strong> binding the data on <code>onBindViewHolder</code> method of <code>RecycleView</code> than it Does not crash..<br> But when i am binding the data inside the <code>onBindViewHolder</code> than i am getting the <code>Exception</code>, Please check my code and let me know where am i doing wrong.</p> <pre><code>package com.tv.practise.adapter; /** Created by Ravindra Kushwaha on 10/10/16. */ public class RecycleDataAdapter extends RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt; { private Context mContext; private ArrayList&lt;RecycleBen&gt; data; public static class SimpleText extends RecyclerView.ViewHolder { TextView first_data_tv; public SimpleText(View v) { super(v); this.first_data_tv = (TextView) v.findViewById(R.id.first_data_tv); } } public class SimpleImage extends RecyclerView.ViewHolder { ImageView second_data_iv; public SimpleImage(View v) { super(v); this.second_data_iv = (ImageView) v.findViewById(R.id.second_data_iv); } } public class SimpleImageWithText extends RecyclerView.ViewHolder { TextView third_data_tv; ImageView third_iv; public SimpleImageWithText(View v) { super(v); this.third_data_tv = (TextView) v.findViewById(R.id.third_data_tv); this.third_iv = (ImageView) v.findViewById(R.id.third_iv); } } public RecycleDataAdapter(Context mContext, ArrayList&lt;RecycleBen&gt; data) { this.mContext = mContext; this.data = data; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { int listViewItemType = getItemViewType(viewType); View itemView; if(listViewItemType==1) { itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.recycle_first_item, parent, false); return new SimpleText(itemView ); } else if(listViewItemType==2) { itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.recycle_fsecond_item, parent, false); return new SimpleImage(itemView); } else { itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.recycle_third_item, parent, false); return new SimpleImageWithText(itemView); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { RecycleBen bean = data.get(position); if(holder.getItemViewType()==1) { /////HERE I AM GETTING THE EXCEPTION WHILE BINDIND DATA ((SimpleText)holder).first_data_tv.setText(bean.getName()); } else if(holder.getItemViewType()==2) { } else { /////HERE I AM GETTING THE EXCEPTION WHILE BINDIND DATA((SimpleImageWithText)holder).third_data_tv.setText(bean.getName()); } } @Override public int getItemViewType(int position) { return Integer.parseInt(data.get(position).getType_row()); } @Override public int getItemCount() { return data.size(); } } </code></pre> <p><strong>Exception</strong> while i am binding the data are as follow:-<br></p> <pre><code>3758-3758/com.tv.practise E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.tv.practise, PID: 3758 java.lang.ClassCastException: com.tv.practise.adapter.RecycleDataAdapter$SimpleImageWithText cannot be cast to com.tv.practise.adapter.RecycleDataAdapter$SimpleText at com.tv.practise.adapter.RecycleDataAdapter.onBindViewHolder(RecycleDataAdapter.java:101) at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5471) at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5504) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4741) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617) at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1994) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1390) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028) at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2625) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) at android.view.View.measure(View.java:18804) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643) at android.view.View.measure(View.java:18804) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2112) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1228) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1464) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6060) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858) at android.view.Choreographer.doCallbacks(Choreographer.java:670) at android.view.Choreographer.doFrame(Choreographer.java:606) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844) at android.os.Handler.handleCallback(Handler.java:746) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5443) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) </code></pre>
<p>The reason is<code>onCreateViewHolder(ViewGroup parent, int viewType)</code>. The parameter is view type but not position. Using <code>int listViewItemType = getItemViewType(viewType)</code> is incorrect because <code>position</code> should be passed to <code>getItemViewType</code>.</p> <p>In short, you should use <code>viewType</code> directly and remove <code>listViewItemType</code> in <code>onCreateViewHolder</code>.</p>
Querying with joins & filters in Mongoose <p>I'm new to Mongodb &amp; using it in web application that I'm building using MEAN stack. My goal is to query two tables by joining them and applying a filter condition on them. For eg: I have two tables - Bike-BikeID,Registration No.,Make,Model &amp; Appointment - Appointment Date,Status,Bike(ref Bike object) and I want to show only those bikes who do not have an appointment with status='Booked'. I want to accomplish the following SQL in Mongoose.</p> <pre><code>Select bike.* from Bike inner join Appointment on Bike.BikeID = Appointment.BikeID and Appointment.Status != 'Booked' </code></pre> <p>I'm using the following code, but I'm not getting the desired results. Can someone help me with this query. </p> <pre><code>app.get('/api/getbikeappo*',function(req,res){ var msg=""; //.find({cust:req.query._id}) //.populate('cust','email') ubBike.aggregate([ { $match: { cust : req.query._id } }, { $lookup: { from: "appos", localField: "_id", foreignField: "bike", as : "appointments" } }, { $match: { "appointments" : {$eq : []} } } ]) .exec(function(err,bikes){ res.send(bikes); if(err) throw err; }); }); </code></pre> <hr> <pre><code>bikes - collection { "_id": { "$oid": "57fb600fdd9070681de19c18" }, "brand": "Splendor", "model": "Splendor", "year": "2002", "kms": 0, "regno": "TN02M8937", "cust": { "$oid": "57f8c44466cab97c1355a09a" }, "__v": 0 } { "_id": { "$oid": "57fb6025dd9070681de19c19" }, "brand": "Activa", "model": "Activa", "year": "2016", "kms": 0, "regno": "TN14M3844", "cust": { "$oid": "57f8c44466cab97c1355a09a" }, "__v": 0 } appointment collection ---------------------- { "_id": { "$oid": "57fb6040dd9070681de19c1a" }, "appoidt": { "$date": "2016-10-15T18:30:00.000Z" }, "reqdt": { "$date": "2016-10-10T09:32:48.694Z" }, "status": "Booked", "bike": { "$oid": "57fb600fdd9070681de19c18" }, "cust": { "$oid": "57f8c44466cab97c1355a09a" }, "__v": 0 } ----------------- Expected output is { "_id": { "$oid": "57fb6025dd9070681de19c19" }, "brand": "Activa", "model": "Activa", "year": "2016", "kms": 0, "regno": "TN14M3844", "cust": { "$oid": "57f8c44466cab97c1355a09a" }, "__v": 0 } </code></pre>
<p>You were almost there, you just needed the right <strong><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/match/" rel="nofollow"><code>$match</code></a></strong> query which follows:</p> <pre><code>ubBike.aggregate([ { "$match": { "cust": req.query._id } }, { "$lookup": { "from": "appos", "localField": "_id", "foreignField": "bike", "as": "appointments" } }, { "$match": { "appointments.status": { "$ne": "Booked" } } } ]).exec(function(err, bikes){ if(err) throw err; res.send(bikes); }); </code></pre>
Order by same as where in condtion <p>How can i order records same as <code>where I.ItemCode in ()</code> sequence</p> <p><strong>(sort by order of values in a select statement in clause)</strong></p> <p><strong>Query</strong> </p> <pre><code>SELECT I.ItemCode,I.ItemName,UM.Name As Unit, SUM(CASE WHEN Rs.RestaurantID=1 THEN RD.Quantity ELSE Null END) [res1], SUM(CASE WHEN Rs.RestaurantID=2 THEN RD.Quantity ELSE Null END) [res2], SUM(RD.Quantity)TOTAL_QTY FROM DBO.ITEMS I LEFT JOIN UnitMeasure UM ON I.UnitMeasureID=UM.UnitMeasureID LEFT OUTER JOIN DBO.RequisitionDetails RD ON I.ItemID=RD.ItemID LEFT JOIN Requisitions R ON RD.RequisitionID=R.RequisitionID LEFT JOIN Restaurants Rs ON R.RestaurantID=Rs.RestaurantID where I.ItemCode in (355,365,360,275,335,350,395,320,310,340,345,305,325,315,388,300,383,385,250,245,453,326,366,368,375) and r.RequisitionDate='2016-09-23' GROUP BY I.ItemCode,I.ItemName,UM.Name </code></pre>
<p>You need to explicitly hard code the ordering in <code>Order by</code> no other way </p> <pre><code>Order by Case ItemCode when 355 then 0 when 365 then 1 when 360 then 2 when 275 then 3 .. when 368 then 24 when 375 then 25 end asc </code></pre> <p>Each time you may have to build the <code>Order by</code> based on <code>IN</code> clause</p>
Changing Scale of Sprite with SKAction.scale <p>Trying to have the scale of the sprite 'PlayButton' continue to scale up and down to hint to the user to touch it. Can't seem to get it working. </p> <p>This is the Menu Class:</p> <pre><code>import SpriteKit class MenuScene: SKScene { let ScalePBup = SKAction.scaleX(to: 300, y: 300, duration: 10) let ScalePBdown = SKAction.scaleX(to: -300, y: -300, duration: 10) //MARK: - Private Instance Variables private let logo = GameLogo() private let title = GameTitle() private let playButton = PlayButton() private let background = Background() private let foreground = Foreground() private let background2 = Background2() //MARK: - Init required init ?(coder aDecoder: NSCoder){ super.init(coder:aDecoder) } override init(size: CGSize){ super.init(size: size) } override func didMove(to view: SKView){ self.setup() } //MARK: - Setup private func setup() { self.backgroundColor = Colors.colorFromRGB(rgbvalue: Colors.background) self.addChild(logo) self.addChild(title) self.addChild(playButton) self.addChild(background) self.addChild(foreground) self.addChild(background2) } // MARK: - Update override func update(_ currentTime: TimeInterval) {} // MARK: - Touch Handling override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { let touch:UITouch = touches.first! as UITouch let touchLocation = touch.location(in: self) if playButton.contains(touchLocation){ loadScene() } } // MARK: - Load Scene private func loadScene() { let scene = GameScene(size: kViewSize) let transition = SKTransition.fade(with: SKColor.black, duration: 0.5) self.view?.presentScene(scene, transition: transition) run(SKAction.repeatForever(SKAction.sequence([ SKAction.run(ScalePBup, onChildWithName: "playButton"), SKAction.run(ScalePBdown, onChildWithName: "playButton") ]) )) } } </code></pre> <p>Here is the sprite </p> <pre><code>import SpriteKit class PlayButton: SKSpriteNode { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) } convenience init() { let texture = GameTextures.sharedInstance.texture(name: SpriteName.playButton) self.init(texture: texture, color: SKColor.white, size: texture.size()) setup() } private func setup() { self.position = CGPoint(x: kViewSize.width / 2, y: kViewSize.height * 0.2) } } </code></pre> <p>Please let me know if you have any suggestions! Thanks!</p>
<p>In <strong>MenuScene</strong> remove the code:</p> <pre><code>run(SKAction.repeatForever(SKAction.sequence([ SKAction.run(ScalePBup, onChildWithName: "playButton"), SKAction.run(ScalePBdown, onChildWithName: "playButton") ]) )) </code></pre> <p>in <strong>class PlayButton</strong> add:</p> <pre><code>let ScalePBup = SKAction.scaleX(to: 300, y: 300, duration: 10) let ScalePBdown = SKAction.scaleX(to: -300, y: -300, duration: 10) func startPulse() { run(SKAction.repeatForever(SKAction.sequence([ScalePBup,ScalePBdown]))) } func removePulse () { removeAllAction() } </code></pre> <p>in <strong>MenuScene</strong></p> <pre><code>override func didMove(to view: SKView){ self.setup() playButton.startPulse() } </code></pre>
Source of event (SCREEN_ON) <p>I have such problem: My application subscribed on the Intent.SCREEN_ON event, but in some cases it make wrong effect. How I can detect - SCREEN_ON has been caused by button (user has pressed the power button), or any other (alarm, incoming call, notification from whatsapp)? Is it possible?</p>
<p>No. It's not possible.</p> <p>At the heart of every broadcasts is an <code>Intent</code>. If such feat is possible then we should see the required information somewhere within them.</p> <p>But if you take a look at <code>Intent</code>'s soucre, these are the only fields defined:</p> <pre><code> private String mAction; private Uri mData; private String mType; private String mPackage; private ComponentName mComponent; private int mFlags; private HashSet&lt;String&gt; mCategories; private Bundle mExtras; </code></pre> <p>You see, among those fields there's not really one that could tell us anything about the sender.</p>
error when implementing eccjs library <p>I am trying to implement this <code>ecc</code> library of NodeJS, <a href="https://github.com/jpillora/eccjs" rel="nofollow">https://github.com/jpillora/eccjs</a>.</p> <p>The file that I am trying to run is,</p> <pre><code>https://github.com/jpillora/eccjs/blob/gh-pages/examples/simple.js </code></pre> <p>The problem is, when I try to run the file using <code>node simple.js</code> command, I get the following error,</p> <pre><code>eccjs-gh-pages/examples/simple.js:31 var keys = ecc.generate(ecc.ENC_DEC); ^ TypeError: Object function ecc() { return new ECC(); } has no method 'generate' at Object.&lt;anonymous&gt; (/home/pi/Project/eccjs-gh-pages/examples/simple.js:31:16) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:906:3 </code></pre> <p>However, when I run the same file using an html file (<a href="https://github.com/jpillora/eccjs/blob/gh-pages/index.html" rel="nofollow">https://github.com/jpillora/eccjs/blob/gh-pages/index.html</a>) as follows,</p> <pre><code> &lt;script src="examples/simple.js"&gt;&lt;/script&gt; </code></pre> <p>I can see the output of in my Chrome console.</p> <p>Can someone please tell me why the file is not working using command line but working fine when executed through the browser ? and is there anyway to do so ?</p> <p><strong>Edit:</strong> I have already commented out the following line,</p> <pre><code>var ecc = require('../dist/0.1/ecc'); </code></pre> <p>in example.js before running it in command line.</p>
<p>You need to import the <code>generate</code> method from where its coming from in the js file. </p> <p>Add an import statement to the to of the file pointing to the module supporting this generate method. </p> <p>Looking at the file, this is currently commented out: </p> <pre><code>// var ecc = require('../dist/0.1/ecc'); </code></pre> <p>Try un-commenting it. </p> <p>Note, this has to be commented when used in HTML as a JS file.</p> <p><strong>Edit</strong> Just saw your changes. Maybe you're using an outdated ecc module. As the error states there is no <code>generate</code> method in the ecc file. </p> <p>Alternatively, install the latest ecc via npm using <code>npm install eccjs</code> and replacement <code>var ecc = require('../dist/0.1/ecc');</code> with <code>var ecc = require('eccjs');</code></p>
Convert if else structure into switch case in swift <p>I am pretty new in programming, I am trying to convert this if else structure into Switch cases in Swift language, i appreciate your help, thanks.</p> <p>here is my code</p> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "ShowDefinition") { if let destinationViewController = segue.destinationViewController as? EnglishViewController { if let definition = sender as? String { if definition == "Abstraction" { destinationViewController.titleMsg = "Abstraction" destinationViewController.definitionMsg = "definition 1" } else if definition == "Binary System" { destinationViewController.titleMsg = "Binary System" destinationViewController.definitionMsg = "definition 2" } else if definition == "Computer" { destinationViewController.titleMsg = "Computer" destinationViewController.definitionMsg = "definition 3" } else if definition == "Internet" { destinationViewController.titleMsg = "Internet" destinationViewController.definitionMsg = "definition 4" } else if definition == "Virtual Reality" { destinationViewController.titleMsg = "Virtual Reality" destinationViewController.definitionMsg = "definition 5" } } } } } </code></pre>
<p>Something like this:</p> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "ShowDefinition") { if let destinationViewController = segue.destinationViewController as? EnglishViewController { if let definition = sender as? String { switch definition { case "Abstraction": destinationViewController.titleMsg = "Abstraction" destinationViewController.definitionMsg = "definition 1" case "Binary System": destinationViewController.titleMsg = "Binary System" destinationViewController.definitionMsg = "definition 2" case "Computer": destinationViewController.titleMsg = "Computer" destinationViewController.definitionMsg = "definition 3" case "Internet": destinationViewController.titleMsg = "Internet" destinationViewController.definitionMsg = "definition 4" destinationViewController.titleMsg = "Abstraction" destinationViewController.definitionMsg = "definition 1" case "Virtual Reality": destinationViewController.titleMsg = "Virtual Reality" destinationViewController.definitionMsg = "definition 5" default: destinationViewController.titleMsg = "" destinationViewController.definitionMsg = "" } } } } } </code></pre> <p>Check what you want to do with the <code>default</code> value, that will be hit if none of the <code>case</code> matches.</p>
Convert LINQ with Model To Array <p>I'm trying to create a LINQ to get the records in Personnel table that exist in Users table. Here's the tutorial I'm currently following: <a href="http://docs.telerik.com/data-access/feature-reference/api/linq-guide/data-access-tasks-querying-model-convert-result-to-array" rel="nofollow">Convert the Results of a LINQ Query to an Array</a>.</p> <p>However, when I try to implement it in my codes I'm having an error: <code>'UserModel[]' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains&lt;string&gt;(IQueryable&lt;string&gt;, string)' requires a receiver of type 'IQueryable&lt;string&gt;'</code></p> <pre><code>var users = from u in db.USR_MSTR select new UserModel { emp_id = u.EMP_ID }; UserModel[] userList = users.ToArray(); var matches = from p in db.PERSONNEL_MSTR where userList.Contains(p.EMP_ID) //userList is generating the error above select p; </code></pre>
<p>Contains is awaiting for UserModel instance to be passed, that's why you get error. Just use .Any() instead:</p> <pre><code>var matches = from p in db.PERSONNEL_MSTR where userList.Any(u=&gt; u.ID == p.EMP_ID) select p; </code></pre> <p>What it does here is: If p.EMP_ID is found inside userList, than it is selected.</p>
npm ionic install error in node.js <p>I'm quite upset by the day. Give me best solution.</p> <p>Your environment has been set up for using Node.js 0.10.38 (x64) and npm.</p> <pre><code>C:\Users\ASAR-KSS&gt;npm install -g ionic npm ERR! network getaddrinfo ENOTFOUND npm ERR! network This is most likely not a problem with npm itself npm ERR! network and is related to network connectivity. npm ERR! network In most cases you are behind a proxy or have bad network settings. npm ERR! network npm ERR! network If you are behind a proxy, please make sure that the npm ERR! network 'proxy' config is set properly. See: 'npm help config' npm ERR! System Windows_NT 6.1.7600 npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "ionic" npm ERR! cwd C:\Users\ASAR-KSS npm ERR! node -v v0.10.38 npm ERR! npm -v 1.4.28 npm ERR! syscall getaddrinfo npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! npm ERR! Additional logging details can be found in: npm ERR! C:\Users\ASAR-KSS\npm-debug.log npm ERR! not ok code 0 C:\Users\ASAR-KSS&gt; </code></pre>
<p>Update npm to the <a href="https://docs.npmjs.com/getting-started/installing-node" rel="nofollow">latest version</a>. Try again. Seems that it can't find the package, or you're using an outdated npm version. </p> <p>If that doesn't work, check whether you're sitting behind a proxy or make sure you've not configured a proxy in the <code>~/.npmrc</code> file. </p> <p>The error <code>network getaddrinfo ENOTFOUND</code> suggests that the http address for the package cannot be found or is being altered because you're sitting behind a proxy. </p>
How to minimize the Size of Xamarin android app <p>How to i minimize the size of a Xamarin android app.Unlike the android studio version,Xamarin apps tend to take more space. I would be glad for the help. thanks</p>
<p>Xamarin apps take more space only in Debug mode, if you try build your application in Release mode then linker deletes all unnecessary libraries from build.</p>
Best way to make fixed div to bottom or top depending on the position? Example inside <p>I'm in trouble. What a best way to make left block fixed like that <a href="http://gph.is/2e2oh46" rel="nofollow">http://gph.is/2e2oh46</a></p> <p>My current code</p> <pre><code>var lastSt = 0; var windowHeight = $(window).height(); $(window).scroll(function(event){ var st = $(this).scrollTop(); var sb = st + windowHeight; $.each(portlets, function(i, portlet) { if (st + padding &lt; $(portlet).data('init-top')) { $(portlet).css('position', '').css('top', ''); } else { // Otherwise fix to top or bottom depending on the position if (st &gt; lastSt) { // Downscroll if (sb + padding &gt; $(portlet).position().top + $(portlet).height() + 45) { $(portlet).css('position', 'fixed').css('bottom', padding); } } else { // Upscroll if (st + padding &lt; $(portlet).position().top) { $(portlet).css('position', 'fixed').css('top', padding); } } } }); lastSt = st; }); </code></pre> <p>Sorry for my bad English =(</p>
<p>There are a lot of examples arround the WWW.</p> <p>Please visit this page <a href="https://css-tricks.com/scrollfollow-sidebar/" rel="nofollow">https://css-tricks.com/scrollfollow-sidebar/</a></p>
generate document and then zip with php <p>I have an issue. I have an index.php with several checkboxes. Every checkbox represents a piece of code. I am trying to create some generating tool. For example: if I select four checkboxes, I want that four specific parts of code to generate in one php file, then zip it and download on my computer.</p> <p><a href="http://i.stack.imgur.com/NKJGC.png" rel="nofollow"><img src="http://i.stack.imgur.com/NKJGC.png" alt="enter image description here"></a></p> <p>I know I can do it something like this:</p> <pre><code>$files = array('list.php', 'one-image.php', 'gallery.php', 'pdf.php'); $zipname = 'file.zip'; $zip = new ZipArchive; $zip-&gt;open($zipname, ZipArchive::CREATE); foreach ($files as $file) { $zip-&gt;addFile($file); } $zip-&gt;close(); header('Content-Type: application/zip'); header('Content-disposition: attachment; filename='.$zipname); header('Content-Length: ' . filesize($zipname)); readfile($zipname); </code></pre> <p>but, at the moment i am pretty lost. Thanks in advance.</p>
<p>Copied from comments:</p> <p>Read the files yourself using <code>file_get_contents</code>, concatenate using <code>+</code>, write to zip with <code>ZipArchive::addFromString</code>.</p>
Laravel not sending from address <p>I want to send Email to my Email when a user views a page.<br> I done it successfully.</p> <p>My code looks like this:</p> <pre><code>Route::any('contact_us/send', function() { return Mail::send('contactus.send', ['name' =&gt; 'Advaith'], function($message) { $name = $_POST['name']; $from = $_POST['email']; $message-&gt;to('itsme@gmail.com')-&gt;from($from, $name)-&gt;subject('Feed Back'); //itsme@gmail.com is used in this question only }); }); </code></pre> <p>This code send Email to my account.</p> <p>But it is not sending the senders name and email (<code>$name</code> and <code>$from</code>) <br>I Even tried to change the variables and give a example email to it.</p> <p>My <code>.env</code> file looks like this:</p> <pre><code>MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=itsme@gmail.com MAIL_PASSWORD=********** MAIL_ENCRYPTION=tls </code></pre> <p>My <code>config/mail.php</code> file looks like this:</p> <pre><code>'driver' =&gt; env('MAIL_DRIVER', 'smtp'), 'host' =&gt; env('MAIL_HOST', 'smtp.gmail.com'), 'port' =&gt; env('MAIL_PORT', 587), 'from' =&gt; [ 'address' =&gt; 'hello@example.com', 'name' =&gt; 'Example', ], 'encryption' =&gt; env('MAIL_ENCRYPTION', 'tls'), 'username' =&gt; env('MAIL_USERNAME'), 'password' =&gt; env('MAIL_PASSWORD'), 'sendmail' =&gt; '/usr/sbin/sendmail -bs', 'pretend' =&gt; false, </code></pre> <p>My form which sends the data is like this:</p> <pre><code>&lt;form class="ad-form col-md-12" method="POST" action="/contact_us/send"&gt; {{ csrf_field() }} &lt;input placeholder="Name...*" type="text" name="name" required="required"&gt; &lt;br&gt; &lt;input placeholder="Email...*" type="email" name="email" required="required"&gt; &lt;br&gt; &lt;textarea required="required" placeholder="Your valuable feedback...*" name="comment" rows="5" cols="40"&gt;&lt;/textarea&gt; &lt;br&gt; &lt;input type="submit" name="submit" value="Send"&gt; &lt;/form&gt; </code></pre> <p>And my <code>contactus/send.blade.php</code> file looks like this:</p> <pre><code>&lt;div style="border: 2px solid orange; padding: 30px;"&gt; &lt;div&gt;From: &lt;b&gt;{{ $_POST['name'] }}&lt;/b&gt;&lt;/div&gt; &lt;div&gt;From-Email: &lt;b&gt;{{ $_POST['email'] }}&lt;/b&gt;&lt;hr&gt;&lt;/div&gt;&lt;br&gt; &lt;div style="text-align: justify;"&gt;&lt;strong&gt;{{ $_POST['comment'] }}&lt;/strong&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Please tell me why it is not sending the from address.</p> <p>And please also tell me how to go to another page after the email is send. </p>
<p>This problem is not a Laravel issue. You said in a comment, that it is written that you sent the email to yourself. This is due to the fact that gmail does not allow to use random from addresses, to prevent spamming. </p> <p>You have to register alternate addresses before you can use them as your "from address" , or gmail will change it back to default. </p> <p>For references see <a href="https://productforums.google.com/forum/#!topic/gmail/0_6Np9yAZ5M" rel="nofollow">here</a> or <a href="https://support.google.com/mail/answer/22370?hl=en" rel="nofollow">here</a></p> <p>There are also some SO ressources that deal with the problem: </p> <p><a href="http://stackoverflow.com/q/1332510/3927116">How to change from-address when using gmail smtp server</a>, </p> <p><a href="http://stackoverflow.com/questions/5431631/when-using-gmail-for-smtp-can-you-set-a-different-from-address">When using Gmail for SMTP, can you set a different “from” address?</a></p> <p><a href="http://stackoverflow.com/questions/3871577/change-sender-address-when-sending-mail-through-gmail-in-c-sharp">change sender address when sending mail through gmail in c#</a></p>
White border on both sides of the image <p><p>I'm trying to load my my image to a custom view but after loading im getting withite border on both sides.</p><a href="http://i.stack.imgur.com/1NWXs.png" rel="nofollow"><img src="http://i.stack.imgur.com/1NWXs.png" alt="enter image description here"></a></p> <p>My custom imageView <h3>MyCanvas</h3></p> <pre><code>public class MyCanvas extends ImageView { private Paint mPaint; private Path mPath; private Map&lt;Path, Integer&gt; mPaths; private PathsChangedListener mListener; private int mColor; private float mCurX; private float mCurY; private float mStartX; private float mStartY; private boolean mPaintIsOn; private Activity mScaleDetector; private float mLastTouchX; private float mLastTouchY; private int mActivePointerId = INVALID_POINTER_ID; private float mPosX; private float mPosY; public void setmPaintIsOn(boolean mPaintIsOn) { this.mPaintIsOn = mPaintIsOn; } public MyCanvas(Context context, AttributeSet attrs) { super(context, attrs); mPath = new Path(); mPaint = new Paint(); mPaint.setColor(Color.BLACK); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(5f); mPaint.setAntiAlias(true); mPaths = new LinkedHashMap&lt;&gt;(); mPaths.put(mPath, mPaint.getColor()); pathsUpdated(); } public void setListener(PathsChangedListener listener) { this.mListener = listener; } public void undo() { if (mPaths.size() &lt;= 0) return; Path lastKey = null; for (Path key : mPaths.keySet()) { lastKey = key; } mPaths.remove(lastKey); pathsUpdated(); invalidate(); } public void setColor(int newColor) { mColor = newColor; } public Bitmap getBitmap() { final Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(bitmap); canvas.drawColor(Color.WHITE); draw(canvas); return bitmap; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mPaintIsOn) { for (Map.Entry&lt;Path, Integer&gt; entry : mPaths.entrySet()) { mPaint.setColor(entry.getValue()); canvas.drawPath(entry.getKey(), mPaint); } mPaint.setColor(mColor); canvas.drawPath(mPath, mPaint); } } public void clearCanvas(){ mPath.reset(); mPaths.clear(); pathsUpdated(); invalidate(); } private void actionDown(float x, float y) { mPath.reset(); mPath.moveTo(x, y); mCurX = x; mCurY = y; } private void actionMove(float x, float y) { mPath.quadTo(mCurX, mCurY, (x + mCurX) / 2, (y + mCurY) / 2); mCurX = x; mCurY = y; } private void actionUp() { mPath.lineTo(mCurX, mCurY); // draw a dot on click if (mStartX == mCurX &amp;&amp; mStartY == mCurY) { mPath.lineTo(mCurX, mCurY + 2); mPath.lineTo(mCurX + 1, mCurY + 2); mPath.lineTo(mCurX + 1, mCurY); } mPaths.put(mPath, mPaint.getColor()); pathsUpdated(); mPath = new Path(); } private void pathsUpdated() { if (mListener != null &amp;&amp; mPaths != null) { mListener.pathsChanged(mPaths.size()); } } @Override public boolean onTouchEvent(MotionEvent ev) { final MotionEvent event = ev; if (mPaintIsOn) { final float x = ev.getX(); final float y = ev.getY(); switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: mStartX = x; mStartY = y; actionDown(x, y); break; case MotionEvent.ACTION_MOVE: actionMove(x, y); break; case MotionEvent.ACTION_UP: actionUp(); break; default: break; } invalidate(); return true; } return true; } public interface PathsChangedListener { void pathsChanged(int cnt); } </code></pre> <p>Over here im trying to draw on image with different colors.</p> <p>my method which loads image to MyCanvas imageview </p> <pre><code>private void setPreviewImage(final Bitmap bmp) { if (bmp != null) { mCanvas.setImageBitmap(bmp); } } </code></pre> <p>The xml </p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;a9msquare.mustache.Views.MyCanvas android:id="@+id/my_canvas" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;ImageView android:id="@+id/color_picker" android:layout_width="@dimen/icon_size" android:layout_height="@dimen/icon_size" android:layout_alignParentRight="true"/&gt; &lt;ImageView android:id="@+id/undo" android:layout_width="@dimen/icon_size" android:layout_height="@dimen/icon_size" android:layout_alignParentRight="true" android:layout_below="@id/color_picker" android:src="@mipmap/ic_launcher" android:visibility="gone"/&gt; </code></pre> <p></p>
<p>It is not exactly a white border, the image you are setting in your custom view is not of exactly the same size as your <code>MyCanvas</code> view. You will need to scale or crop your image if you want it to take up all the space without leaving any empty spaces around.</p> <p>Try adding <code>android:scaleType="fitXY"</code> to your <code>MyCanvas</code> in your layout.xml. Your <code>MyCanvas</code> would look like:</p> <pre><code>&lt;a9msquare.mustache.Views.MyCanvas android:id="@+id/my_canvas" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitXY" /&gt; </code></pre>
Object oriented jQuery/JavaScript <h3>Description</h3> <p>All of my jQuery code works well on my website and I don't have any issues. However, I think that it would be a good idea to rewrite all the code in a more object oriented manner, so that it's reusable.</p> <p>As I don't have any experience in jQuery/JavaScript OOP, I want to ask you for an advice on how to do this best.</p> <p>It would be great to explain the procedure on the following usecase of my website.</p> <h3>Usecse</h3> <p>Some elements on my website should have a parallax effect. At the moment I'm searching the DOM for these elements and then work with them. My OO idea was to set up kind of an object which includes all the code and later on, assign an element to this object like this: <code>$('.element').parallax(</code><em><code>$direction</code></em><code>)</code></p> <p>Is this a good idea? How should I do this?</p> <p>Thanks in advance for your help.</p>
<p>This question is a bit broad. That said, I'll share the approach I use.</p> <p><strong>Note</strong> I got this from <a href="http://ejohn.org/blog/simple-javascript-inheritance/" rel="nofollow">John Resig's Simple JavaScript Inheritance</a></p> <p>See also <a href="http://blog.buymeasoda.com/understanding-john-resigs-simple-javascript-i/" rel="nofollow">Understanding John Resig's 'Simple JavaScript Inheritance</a></p> <p>First, make a file named <code>ClassDef.js</code> with this content:</p> <pre><code>(function() { var initializing = false, fnTest = /xyz/.test(function() { xyz; }) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function() {}; // Create a new Class that inherits from this class Class.extend = function(prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" &amp;&amp; typeof _super[name] == "function" &amp;&amp; fnTest.test(prop[name]) ? (function(name, fn) { return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if (!initializing &amp;&amp; this.init) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })(); </code></pre> <p><strong>You wont ever need to edit that file again.</strong></p> <hr> <p>Now, when you add a new feature / module, make a new file called <code>SomeFeatureManager.js</code>. </p> <p><code>SomeFeatureManager.js</code></p> <pre><code>var SomeFeatureManager = Class.extend({ init: function(options) { /** * Initialize and set any defaults * @param object options Options set by user, overrides defaults */ var defaults = { someOptionName:'some default value', }; // combine default values with those passed in on init this.options = $.extend(defaults, options); return this; }, makeParalax: function(selector,direction){ /** * Description * @param string selector jQuery selector * @return string direction The direction to parallax */ var $element = $('#'+selector); // .... make element into a parallax.... return this; }, }); </code></pre> <p>This will be your class. All of the functionality and logic for the feature happens here. This is the reusable "module" if you will. Keep the logic here independent of the page you use it on. ie, dont hard code html selectors, pass them to the functions, etc.. </p> <p>Now, when you want to use the feature do this: </p> <pre><code>&lt;script type="text/javascript" src="js/Classes/ClassDef.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/Classes/SomeFeatureManager.js"&gt;&lt;/script&gt; &lt;script&gt; var Feature; $(function(){ var options={ someOptionName:'some user set value', } Feature = new SomeFeatureManger(); Feature.makeParalax('#main-paralax','up'); }); &lt;/script&gt; </code></pre> <h3>Note that this is a simple example, there is a LOT more you can do with the pattern. See the links for more.</h3>
C++ second counter <p>I have created a function which counts seconds, after the choice of a user. It all works, but can it be done smarter and more efficient? Because it seems very heavy and slow. Is there a lib that solves this problem? Or how can we get around it?</p> <p>Here is my code:</p> <pre><code>#include &lt;ctime&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; using namespace std; int main() { double a,c, x,b; int nutid=0; cout&lt;&lt;"Please enter a number: "; cin&gt;&gt;a; x = time(0); c = a-1; while (true) { if (!cin) { cout&lt;&lt;"... Error"; break; } else { b=time(0)-x; if(b&gt;nutid){ cout&lt;&lt;setprecision(11)&lt;&lt;b&lt;&lt;endl; nutid = b+c; } } } return 0; } </code></pre>
<p>You can measure time using the library <code>&lt;chrono&gt;</code> (since <code>c++11</code>) <br></p> <p>Example:</p> <pre><code>#include &lt;iostream&gt; #include &lt;chrono&gt; using namespace std; using namespace chrono; int main() { auto start = high_resolution_clock::now(); // your code here auto end = high_resolution_clock::now(); // you can also use 'chrono::microseconds' etc. cout &lt;&lt; duration_cast&lt;seconds&gt;(end - start).count() &lt;&lt; '\n'; } </code></pre>
angular2 select disable first element <p>I have a select component like this: </p> <pre><code>&lt;select name="typeSelection" materialize="material_select" [(ngModel)]="trainingplan.type" &gt; &lt;option [ngValue] = "null" disabled selected&gt;Please choose a type&lt;/option&gt; &lt;option [ngValue]="type" *ngFor="let type of firebaseService.trainingTypes"&gt; {{type.name}} &lt;/option&gt; &lt;/select&gt; </code></pre> <p>I want the first option to be disabled so that the user sees this hint. But instead of this, the first entry of the "trainingTypes" gets selected. I guess this is because Angular doesn't know which one to select because of the binding maybe and so it takes the first one. What can I do about this?</p>
<p>Your <code>trainingplan.type</code> would need to be set to <code>null</code> but as far as I know <code>[ngValue]</code> with null will only work after the next update.</p> <p>You would need to choose a different value for the first option and set <code>trainingplan.type</code> to this value. You can remove the <code>selected</code> attribute.</p>
My second spinner adapter not updated after my first spinner position has changed <p>I have two spinner, the first spinner is related to the second spinner.</p> <p>I'm using JSON to fill the adapter for both of them.</p> <p>When i start the activity, both of adapter is already filled with a correct data(the first and second adapter is related).</p> <p>But, when i try to change item position of the first spinner, the second spinner's adapter still contain first loaded data.</p> <p>What i want is, the second spinner's adapter can dynamically contain a data that related from first spinner, when an item position from first spinner has changed.</p> <p>I don't know what's the problem, i really need some help.</p> <p>here's my code :</p> <pre><code>spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected (AdapterView &lt; ? &gt; parent, View view,int position, long id){ try { JSONObject json = result.getJSONObject(position); result = json.getJSONArray("all_state"); state.clear(); for (int i = 0; i &lt; result.length(); i++) { try { JSONObject json2 = result.getJSONObject(i); state.add(json2.getString("state")); } catch (JSONException e) { e.printStackTrace(); } } } catch (JSONException e) { e.printStackTrace(); } adapter = new ArrayAdapter&lt;&gt;(ViewState.this, R.layout.spinner_state, state); adapter.notifyDataSetChanged(); spinner2.setAdapter(adapter); } @Override public void onNothingSelected (AdapterView &lt; ? &gt; parent){ } }); </code></pre>
<p>It's solved, the problem is because i put the JSONObject and JSONArray into the same variable "result".</p> <p>So here's the right code :</p> <pre><code>spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected (AdapterView &lt; ? &gt; parent, View view,int position, long id){ try { JSONObject json = result.getJSONObject(position); result2 = json.getJSONArray("all_state"); state.clear(); for (int i = 0; i &lt; result2.length(); i++) { try { JSONObject json2 = result2.getJSONObject(i); state.add(json2.getString("state")); } catch (JSONException e) { e.printStackTrace(); } } } catch (JSONException e) { e.printStackTrace(); } adapter = new ArrayAdapter&lt;&gt;(ViewState.this, R.layout.spinner_state, state); adapter.notifyDataSetChanged(); spinner2.setAdapter(adapter); } @Override public void onNothingSelected (AdapterView &lt; ? &gt; parent){ } }); </code></pre>
Ruby .ceil and .floor <p>I'm new to Ruby and I'm trying to figure out how <code>ceil</code> and <code>floor</code> works as I get different answers when a fraction or a decimal number is used (similar value). Below is what I have tried:</p> <pre><code>puts 8/3.ceil == 2 puts 8/3.floor == 2 puts 2.67.ceil == 2 puts 2.67.floor == 2 </code></pre> <p>Results:</p> <pre><code>true true false true </code></pre> <p>From my understanding, <code>ceil</code> should return a number higher and <code>floor</code> is a number lower. Hope someone can enlighten me on this. Thank you! :)</p>
<p>Everything is returned correctly.</p> <pre><code>puts 8/3.ceil == 2 #=&gt; true, because 8/3 returns an Integer, 2 puts 8/3.floor == 2 #=&gt; true, because 8/3 returns an Integer, 2 puts 2.67.ceil == 2 #=&gt; false, because 2.67.ceil is 3 puts 2.67.floor == 2 #=&gt; true, because true :) </code></pre> <p>To make things of more sense here, you can convert results to Float:</p> <pre><code>(8.to_f / 3).ceil == 2 #=&gt; false (8.to_f / 3).floor == 2 #=&gt; true 2.67.ceil == 2 #=&gt; false 2.67.floor == 2 #=&gt; true </code></pre> <p>Another thing to bear in mind, that having written <code>8/3.ceil</code> is actually <code>8 / (3.ceil)</code>, because the <code>.</code> binds stronger than <code>/</code>. (thx <strong>@tadman</strong>)</p> <p>Yet another thing to mention, is that (thx <strong>@Stefan</strong>):</p> <blockquote> <p>There's also <a href="http://ruby-doc.org/core-2.3.1/Fixnum.html#method-i-fdiv" rel="nofollow"><code>fdiv</code></a> to perform floating point division, i.e. <code>8.fdiv(3).ceil</code>. And Ruby also comes with a nice <a href="https://ruby-doc.org/core-2.3.1/Rational.html" rel="nofollow"><code>Rational</code></a> class: <code>(8/3r).ceil</code>.</p> </blockquote>
AngularJS drop-down with ability to type value <p>We're using AngularJS v1.5.8 in our application. I am looking for a way to display drop down but also allow to type new value. I've checked this <a href="http://stackoverflow.com/questions/4430262/manually-type-in-a-value-in-a-select-drop-down-html-list">Manually type in a value in a &quot;Select&quot; / Drop-down HTML list?</a> and tried datalist (didn't work in Google Chrome) and also looked at the <a href="http://selectize.github.io/selectize.js/" rel="nofollow">http://selectize.github.io/selectize.js/</a> and <a href="http://jsfiddle.net/69wP6/4/" rel="nofollow">http://jsfiddle.net/69wP6/4/</a> I am wondering if something already exists for angularJs so I would not re-invent the wheel.</p> <p>My current code is this</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;input type="text" name="newRowValue" id="newRowValue" class="form-control" list="rowValues" ng-model="newRowValue" placeholder="@Labels.typeOrSelect"/&gt; &lt;datalist id="rowValues" name ="rowValues" class="form-control" ng-model="rowValue"&gt; &lt;option ng-repeat = "possibleValue in metaData.allPossibleValues| filter: {attributeId: currentMatrixTemplate.rowAttributeId}" value="{{possibleValue.attributeId}}" ng-show="possibleValue.hidden==false || showHidden"&gt;{{possibleValue.valueName}} &lt;/option&gt; &lt;/datalist&gt;</code></pre> </div> </div> </p> <p>which doesn't render correctly in Chrome. Any ideas for good and simple implementation of drop down with ability to type new value?</p>
<p>Try this. We use our version of this, but it's very close to <a href="https://github.com/angular-ui/ui-select2" rel="nofollow" title="this solution">this solution.</a></p>
Regex for matching string, contains only number and count must be 2 min values <p>Is there any regex for validating length of a number string for 2 consecutive digits or number </p> <p>Example : </p> <pre><code>"12541256442545245215" = Count (20) "125412564425452452"= Count (18) </code></pre> <p>Need a regex to check a string which contains only number and count must be 18 or 20.</p> <p>I tried using the below regex but it allows length 19 also.</p> <pre><code>^[0-9.]{18,20}$ </code></pre>
<p>You can use this regex:</p> <pre><code>^[0-9.]{18}(?:[0-9.]{2})?$ </code></pre> <p>About this regex:</p> <pre><code>^ # start [0-9.]{18} # match digit or DOT 18 times (?: # start non-capturing group [0-9.]{2} # match digit or DOT 2 times )? # end non-capturing group, ? makes this group *optional* $ # end </code></pre> <p>If you don't want to allow DOT then use:</p> <pre><code>^[0-9]{18}(?:[0-9]{2})?$ </code></pre>
How to auto-increase the height of a FAQ with 2 Main Themes? <p>I have a FAQ in my site with 2 MAIN THEMES..</p> <p>I create a jsfiddle here: <a href="https://jsfiddle.net/kuwr2vhn/" rel="nofollow">https://jsfiddle.net/kuwr2vhn/</a></p> <p>MY ISSUE:</p> <p>FAQ B - is working OK - but FAQ A - isn't.</p> <p>Both FAQ are identicals (I copy and paste) --- but....</p> <p>on FAQ B I made a "TRICK" and I put a lot of "BR" tags at end to increase manually the height of the FAQ.</p> <p>FAQ A doesn't have this trick..</p> <p>But this trick isn't the best way to do this - because the height will change according to the display width too.. If I have a small device - the width will be small - and the height will be different.</p> <p>AND another issue - With this "BR" trick when I click on FAQ A - FAQ B will down a lot.. and for the final user it's hard to understand what happens.</p> <p>I need a solution to auto-control the height. </p> <pre><code>// Question handler $('li.q').on(action, function(){ // gets next element // opens .a of selected question $(this).next().slideToggle(speed) // selects all other answers and slides up any open answer .siblings('li.a').slideUp(); // Grab img from clicked question var i = $(this).children('i'); // remove Rotate class from all images except the active $('i').not(i).removeClass('rotate'); // toggle rotate class i.toggleClass('rotate'); }); $('.faq_question').click(function() { if ($(this).parent().is('.open')){ $(this).closest('.faq').find('.faq_answer_container').animate({'height':'0'},500); $(this).closest('.faq').removeClass('open'); }else{ var newHeight =$(this).closest('.faq').find('.faq_answer').height() +'px'; $(this).closest('.faq').find('.faq_answer_container').animate({'height':newHeight},500); $(this).closest('.faq').addClass('open'); } }); </code></pre>
<p>You are doing it wrong. It won't be dynamic because your answer is also a li and doesn't have its own parent. Here's way of making it dynamic.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var faq_clicker = document.querySelectorAll('.faq--clicker') || document.querySelector('.faq--clicker'), question = document.querySelectorAll('.question') || document.querySelector('.question'); [].forEach.call(faq_clicker, elem =&gt; { elem.onclick = (e) =&gt; { let par = e.target.nextElementSibling; if(par.classList.contains('active')) par.classList.remove('active'); else par.classList.add('active'); } }); [].forEach.call(question, elem =&gt; { elem.onclick = (e) =&gt; { let par = e.target.querySelector('.answer'), afn = document.querySelector('.answer-active'); if(afn) afn.classList.remove('answer-active'); if(par.classList.contains('answer-active')) par.classList.remove('answer-active'); else par.classList.add('answer-active'); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul.parent, ul.answer { max-height: 0; overflow: hidden; transition: max-height 0.2s ease-in-out; } ul li { cursor: pointer; } ul.parent.active, ul.answer.answer-active { max-height: 500px; transition: max-height 0.5s ease-in-out; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="faq-holder"&gt; &lt;a href="#" class="faq--clicker"&gt;FAQ A&lt;/a&gt; &lt;ul class="parent"&gt; &lt;li class="question"&gt; &lt;i class="icon-chevron-right"&gt;&lt;/i&gt; What is my name? &lt;ul class="answer"&gt; &lt;li&gt;I don't know also.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="question"&gt; &lt;i class="icon-chevron-right"&gt;&lt;/i&gt; Who's my girl? &lt;ul class="answer"&gt; &lt;li&gt;Jeamzy Chavez.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="faq-holder"&gt; &lt;a href="#" class="faq--clicker"&gt;FAQ B&lt;/a&gt; &lt;ul class="parent"&gt; &lt;li class="question"&gt;What is your favorite food? &lt;ul class="answer"&gt; &lt;li&gt;Tae.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="question"&gt;What do I want to learn? &lt;ul class="answer"&gt; &lt;li&gt;Create programming language.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Just follow the HTML. And it will work correct. And ofcourse, edit the style. I'm not good in style that's why I just create functionalities for you. </p> <p>Hope it helps. Cheers!</p>
Array of objects and instance of object in each row in C# <p>In an array of objects, why do we have to initialize each object in the array?.... see when an array of a class is made why should i instantiate all the members of the array. is it not kind of pointless or repetetive to again instantiate it again. yes it was meant as question to the developers of vs. you can have nulls but the instantiated object can be nulls</p>
<p>An array is simply a collection of references.</p> <p>For example, the following snippet:</p> <pre><code>Label[] labels = new Label[5]; </code></pre> <p>Declares an array of five <code>Label</code> references. It doesn't actually create the labels themselves. Those five references point to nothing. It's the same as this:</p> <pre><code>Label myLabel; </code></pre> <p>Attempting to access <code>myLabel</code> or any index of <code>labels</code> will result in an object reference error because there is no actual object associated with them. You must initialize them like so:</p> <pre><code>Label myLabel = new Label(...); </code></pre>
Blue "Default" line in a listview - where is it coming from? <p>Can someone please explain to me, what does this line mean, where is it coming from and how do I take it away? Thanks. <a href="http://i.stack.imgur.com/YqoZo.png" rel="nofollow"><img src="http://i.stack.imgur.com/YqoZo.png" alt="enter image description here"></a></p> <p>Here is how I construct my listView: </p> <pre><code> item1 = new ListViewItem(efef.InstFile.File); item1.SubItems.Add(efef.InstFile.DestDir); listViewDerivative1.Items.AddRange(new ListViewItem[] { item1 }); </code></pre>
<p>The item you have added does not belong to a <code>Group</code>, and so is added to the default group.</p> <p>By defining a list of groups for your <code>ListView</code>, you can control what group each item comes under.</p> <p>You can modify these values in the Form Builder or in code. Try setting your <code>ListViewItem</code>'s <code>Group</code> property.</p>
iterating array on refresh <p>How could I go about writing a snippet, that could iterate through array on refresh? Say I have an array with banner links, and I'd like the banner to change to next one when refreshed. There is a lot of solutions to make it random, but I want it to loop through array in order, and go to the first one after last. </p> <pre><code>var banner = new Array(); banner[0] = "http://placehold.it/728x90?text=one"; banner[1] = "http://placehold.it/728x90?text=two"; banner[2] = "http://placehold.it/728x90?text=three"; banner[3] = "http://placehold.it/728x90?text=four"; for(var i=0; i &lt; banner.length; i++){ var img = document.getElementById("imageid"); img.src = banner[i]; } </code></pre> <p>This is the code that I currently have, but it's obviously not working. </p> <p>Thank you in advance</p>
<p>Use <a href="https://developer.mozilla.org/en/docs/Web/API/Window/localStorage" rel="nofollow"><code>localStorage</code></a> like so:</p> <pre><code>var banner = new Array(); banner[0] = "http://placehold.it/728x90?text=one"; banner[1] = "http://placehold.it/728x90?text=two"; banner[2] = "http://placehold.it/728x90?text=three"; banner[3] = "http://placehold.it/728x90?text=four"; if (!localStorage.i || localStorage.i == 3) localStorage.i = 0; else localStorage.i++; var img = document.getElementById("imageid"); img.src = banner[localStorage.i]; </code></pre> <p>Explanation: At first page load, <code>localStorage.i</code> will be <code>0</code>. When you refresh, the value increases by <code>1</code> only until <code>3</code>, then back to <code>0</code> afterwards.</p>
MVC: Serve file with http header <p>I am trying to follow <a href="https://documentation.onesignal.com/docs/web-push-sdk-setup-https#section-can-manifest-json-onesignalsdkworker-js-and-onesignalsdkupdaterworker-js-be-served-from-a-subfolder-of-my-site-" rel="nofollow">this</a> guide and store files in a sub-folder. </p> <p>However, the OneSignal guide asks to serve these files with additional HTTP header <code>Service-Worker-Allowed: /</code>. How do I do that in Asp.Net MVC?</p>
<p>You can use in your controller's action : </p> <pre><code>this.Response.Headers.Add("Service-Worker-Allowed","/"); </code></pre> <p>Hope this help :-)</p> <p>Edit : A better way to do this is to create an action filter to automatically add this header : </p> <pre><code>public class WorkerAllowedAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.HttpContext.Response.Headers.Add("Service-Worker-Allowed", "/"); base.OnActionExecuted(filterContext); } } </code></pre> <p>And you can put it on your action (or your controller) : </p> <pre><code>public partial class HomeController { [WorkerAllowed] public ActionResult Index() { return View(); } } </code></pre>
checking number modulo 1 <p>I saw the following: <code>if (n % 1 || n &lt; 2) ...</code> in some <a href="https://gist.github.com/ehsanamini/d6f3c3709841a2dab94fda4758d07e8f" rel="nofollow" title="github gist">code</a>.</p> <p>The question is what good is the test <code>n % 1</code>? I presume it is (false)0 for all non-zero integers, in which case it would be pointless to disjoin it with anything as it would be equivalent to its disjunct (<code>(false || p) == p</code>, right?). Is it checking if the number is an int? Is it a shortcut for <code>!isNaN(n)</code>?</p>
<p>in javascript all numbers are <code>float</code>s so <code>n%1</code> returns remainder of <code>n/1</code> so it returns the fractional part of <code>n</code> something like <code>n-floor(n)</code> for positive <code>n</code>. So:</p> <pre><code>if (n % 1 || n &lt; 2) </code></pre> <p>should select all fractional numbers and all integers less then 2 (which are not valid inputs for integer IsPrime method).</p>
No benefit of using AsParallel in C#? <p>Here is my sample project:</p> <pre><code> Console.WriteLine("Elapsed time in milliseconds:"); swSingle.Start(); var numbers2 = Enumerable.Range(0, 100000000); var singleResult = numbers2 .Where(i =&gt; i % 2 == 0) .ToArray(); swSingle.Stop(); Console.WriteLine("Without AsParallel: {0}", swSingle.ElapsedMilliseconds); swParallel.Start(); var numbers = Enumerable.Range(0, 100000000); var parallelResult = numbers.AsParallel() .Where(i =&gt; i % 2 == 0) .ToArray(); swParallel.Stop(); Console.WriteLine("Using AsParallel: {0}", swParallel.ElapsedMilliseconds); </code></pre> <p>The output on my (multi-core)system is:</p> <pre><code>Elapsed time in milliseconds: Without AsParallel: 1537 Using AsParallel: 2135 </code></pre> <p>Why don´t I get a time advantage in this sample by using AsParallel? Even worse there seems to be much overhead.</p>
<p>It simply takes more time to make your code run in parallel (create a task, schedule and run it) than the advantage you gain by executing that code in parallel.</p> <p>That said, this makes very clear not every piece of code benefits of running in parallel. You can only use it on substantial code segment with a high CPU load or external I/O (like a HTTP request).</p>