input
stringlengths
51
42.3k
output
stringlengths
18
55k
Stubbing Google Maps/Places iOS SDK calls for unit testing <p>I'm trying to stub my Google Places calls using a local <code>json</code> file. Using Charles proxy, I find that the Google Maps SDK uses the url <code>https://www.googleapis.com</code>. So, I try to stub like:</p> <pre><code>stub(isHost("https://www.googleapis.com")) { request in OHHTTPStubsResponse(fileAtPath: "google_maps.json", statusCode: 200, headers: ["Content-Type":"application/json"]) } </code></pre> <p>But it's not intercepting the google maps SDK calls. Any ideas? Could this be the Google Maps SDK using something other than Cocoa's URL Loading System?</p>
<p>Answer given here: (I was using the incorrect host name, should use simply "www.googleapis.com")</p> <p><a href="https://github.com/AliSoftware/OHHTTPStubs/issues/219" rel="nofollow">https://github.com/AliSoftware/OHHTTPStubs/issues/219</a></p>
Sylius : Catchable Fatal Error: Argument 1 passed to ShopBundle\Controller\HomepageController::__construct() <p>I'm trying to override the <code>HomepageController:indexAction</code> from SyliusShopBundle to pass some data to the <code>index.html.twig</code> but an exception keep appearing:</p> <blockquote> <p>Catchable Fatal Error: Argument 1 passed to AppBundle\Controller\CustomHomepageController::__construct() must be an instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface, none given, called in C:\wamp3\www\acme\app\cache\dev\appDevDebugProjectContainer.php on line 1619 and defined</p> </blockquote> <p><strong>AppBundle/Controller/CustomHomepageController.php:</strong></p> <pre><code>&lt;?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; use Symfony\Component\HttpFoundation\Request; use Sylius\Bundle\ShopBundle\Controller\HomepageController as baseHomepageController; class CustomHomepageController extends baseHomepageController { /** * @var EngineInterface */ private $templatingEngine; /** * @return EngineInterface */ public function getTemplatingEngine() { return $this-&gt;templatingEngine; } /** * @param EngineInterface $templatingEngine */ public function __construct(EngineInterface $templatingEngine) { $this-&gt;templatingEngine = $templatingEngine; } /** * @param Request $request * * @return Response */ public function indexAction(Request $request) { //var_dump($request); $s = "test"; return $this-&gt;templatingEngine-&gt;renderResponse('SyliusShopBundle:Homepage:index.html.twig',array("data"=&gt;$s)); } } </code></pre> <p><strong>AppBundle/Resources/config/services.yml:</strong></p> <pre><code> services: app.custom_homepage_controller: class: AppBundle\Controller\CustomHomepageController arguments: - "@templating" </code></pre> <p><strong>AppBundle/Resources/config/routing.yml:</strong></p> <pre><code>sylius_shop_homepage: path: / defaults: _controller: app.custom_homepage_controller:indexAction </code></pre> <p><strong>AppBundle/Resources/views/Homepage/index.html.twig:</strong></p> <pre><code>{% extends '@SyliusShop/layout.html.twig' %} {% block content %} &lt;h1&gt;{{ data }}&lt;/h1&gt; &lt;h2 class="ui horizontal section divider header"&gt; {{ 'sylius.ui.latest_products'|trans }} &lt;/h2&gt; {% render(url('sylius_shop_partial_product_index_latest', {'count': 4, 'template': '@SyliusShop/Product/_simpleList.html.twig'})) %} {% include '@SyliusShop/Homepage/_promos.html.twig' %} {% include '@SyliusShop/Homepage/_grid.html.twig' %} {% endblock %} </code></pre>
<p>You need to pass the templating engine as an argument in your service definition, something along those lines :</p> <pre><code>services: app.custom_homepage_controller: class: AppBundle\Controller\CustomHomepageController arguments: - "@templating" </code></pre>
Interactions (stats) in matlab <p>I was wondering if there was a function which can give me all interactions given an input of vectors.</p> <p>for example:</p> <p>If I had three vectors a,b,c. Their values are:</p> <pre><code>a = [1,9,3] b = [4,3,2] c = [6,5,7] </code></pre> <p>then I can get back a matrix with:</p> <pre><code>[a.*b, a.*c, b.*c ] </code></pre>
<p>The needed computation doesn't have an inbuilt function but you can always write your own:</p> <pre><code>%% Define the vectors a = [1,9,3]; b = [4,3,2]; c = [6,5,7]; %% test function pairWiseAppend(a,b,c) %% Define the function function customVector = pairWiseAppend(a,b,c) %multiply and generate new vectors vec1 = a.*b; vec2 = a.*c; vec3 = b.*c; %append the vectors customVector = [vec1,vec2,vec3]; end </code></pre> <p>Output:</p> <pre><code>&gt;&gt; stckOvrflow1 ans = 4 27 6 6 45 21 24 15 14 </code></pre> <p>Further, you can always modify the function to suit your needs, for example, this will return a two-dimensional array:</p> <pre><code>%% Define the vectors a = [1,9,3]; b = [4,3,2]; c = [6,5,7]; %% test function customArray = pairWiseAppend(a,b,c) %% Some extra actions on returned array %% Define the function function customArray = pairWiseAppend(a,b,c) %multiply and generate new vectors vec1 = a.*b; vec2 = a.*c; vec3 = b.*c; %append the vectors customArray = [vec1;vec2;vec3]; end </code></pre> <p>Output:</p> <pre><code>&gt;&gt; stckOvrflow1 customArray = 4 27 6 6 45 21 24 15 14 </code></pre> <p>Hope it helps.</p>
Converter Java calendar to Persian calendar <p>I know this question asked by another user and I see all of the posts about this question. I need a library that convert all Java Calendar to Persian calendar like year , month, day and day of week, day of month ... including giving me all the days of one week (Persian week ).</p> <p>Is there any library with this features? </p>
<p>you can see this links...<a href="https://github.com/mohamad-amin/PersianMaterialDateTimePicker" rel="nofollow">PersianMaterialDateTimePicker </a> and <a href="https://github.com/ebraminio/DroidPersianCalendar" rel="nofollow">Android Persian Calendar</a> this are two open source app which i think could help you</p>
Task manager for Android and Profiler for SmartWatches (AndroidWear) <p>Is there any app or way like task manager where I can close individual apps on a smartwatch (Android wear) ? Also if there is any way to measure cpu, memory, and battery consumption of individual apps on Android wear ? </p> <p>For task manager, I have already tried <a href="https://play.google.com/store/apps/details?id=rocketstartups.weartaskmanager&amp;hl=en" rel="nofollow">Task Manager for Android wear</a> But it doesn't work on my LG Watch R. </p>
<p>This question may be more suited in <a href="http://superuser.com/">superuser.com</a> instead of stackoverflow.</p> <p>Anyways, if you're looking for an app, you can try this <a href="https://play.google.com/store/apps/details?id=rocketstartups.weartaskmanager&amp;hl=en" rel="nofollow">Task Manager For Android Wear</a> that is available in the Play Store. It can list all running processes on your watch and it can help you to stop any of the tasks easily and quickly.</p> <p>You can also check this <a href="https://developer.android.com/training/wearables/watch-faces/performance.html" rel="nofollow">documentation</a> for tips for conserving power and improving performance. You need to ensure that your watch face performs computations only when active; use callbacks in <a href="https://developer.android.com/reference/android/support/wearable/watchface/WatchFaceService.Engine.html" rel="nofollow"><code>WatchFaceService.Engine</code></a>. The <a href="https://play.google.com/store/apps/details?id=com.google.android.wearable.app&amp;hl=en" rel="nofollow">Android Wear companion app</a> also enables developers and users to see how much battery is consumed by different processes on the wearable device (under Settings > Watch battery).</p>
regular expression for double consonants <p>I have a problem writing regular expression. I want to write a regular expression that replaces all double consonants with a single consonant. Please help me to write such a rule in only one line. Thanks in advance. </p>
<p>Since you did not specify the language, I'm going to go ahead and assume Javascript.</p> <p>This should get you started:</p> <p><code>console.log('babble bubble http htttp www'.replace(/([^aeiou\.,\/=?:\d&amp;\s!@#$%^*();\\|&lt;&gt;"'_+-])\1{1}/gi, "$1"));</code></p> <p>See more here:</p> <p><a href="http://regexr.com/3ee47" rel="nofollow">http://regexr.com/3ee47</a></p>
Multipart upload initiated with putObject is aborted (AWS Javascript SDK) <p>I'm using the AWS JS Javascript SDK in the browser and trying to upload user selected large files to the user's designated folder on S3.</p> <p>I use the putObject method to upload files to S3. The user is authenticated with a temporary token generated server side, and is allowed to putObject in a specific folder on the bucket.</p> <p>When the file is under 5MB, it works fine. When the file is over 5MB, the AbortMultiupload method is called after the first chunk fails.</p> <p>What causes this?</p>
<p>the problem was "No access to ETag property on response. Check CORS configuration". Solved it with adding "ETag" in bucket CORS configuration.</p>
jQuery prop function is not working <p>HTML code:</p> <pre><code> &lt;ul class="expander-list" id="category"&gt; &lt;li&gt; &lt;div class="radio" style="padding-left:0px"&gt; &lt;label&gt; &lt;input type="checkbox" id="all" name="filter" class="checkbox0" value="all"&gt; all &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="radio" style="padding-left:0px"&gt; &lt;label&gt; &lt;input type="checkbox" name="filter" class="checkbox1" value="electronics"&gt; Electronics &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="radio" style="padding-left:0px"&gt; &lt;label&gt; &lt;input type="checkbox" name="filter" class="checkbox1" value="kitchen"&gt; Kitchen &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="radio" style="padding-left:0px"&gt; &lt;label&gt; &lt;input type="checkbox" name="filter" class="checkbox1" value="decoratives"&gt; Decoratives / Interior &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="radio" style="padding-left:0px"&gt; &lt;label&gt; &lt;input type="checkbox" name="filter" class="checkbox1" value="homedecor"&gt; Home Decor &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="radio" style="padding-left:0px"&gt; &lt;label&gt; &lt;input type="checkbox" name="filter" class="checkbox1" value="furnitures"&gt; Furnitures &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="radio" style="padding-left:0px"&gt; &lt;label&gt; &lt;input type="checkbox" name="filter" class="checkbox1" value="toys"&gt; Toys &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="radio" style="padding-left:0px"&gt; &lt;label&gt; &lt;input type="checkbox" name="filter" class="checkbox1" value="vehicles"&gt; Vehicles &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>jQuery code:</p> <pre><code>$('input[type="checkbox"]').change(function(){ startexecution: alert('checkbox is changed'); var number = []; $('input[type="checkbox"]:checked').each(function(){ number.push($(this).val()); }); if(number.length == 0){ alert('now it zero'); $('.checkbox1').prop('checked', this.checked); $('.checkbox0').prop('checked', this.checked); } }); </code></pre> <p>The following line is not working</p> <pre><code> $('.checkbox1').prop('checked', this.checked); $('.checkbox0').prop('checked', this.checked); </code></pre> <p>if the size of an array number is 0 then it alerting 'now it zero' but the line of prop function is not working right now I am helpless so please help me for resolving this error. </p>
<p>In your code, <code>this.checked</code> refers to the state of the box you've clicked -- the one that fired the <code>change()</code> event. So <code>this.checked</code> will be <code>true</code> if you checked a checkbox and <code>false</code> if you unchecked a checkbox. Here's a demonstration:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('input[type="checkbox"]').change(function() { console.log(this.checked); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;ul class="expander-list" id="category"&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" id="all" name="filter" class="checkbox0" value="all"&gt;all&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="electronics"&gt;Electronics&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="kitchen"&gt;Kitchen&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="decoratives"&gt;Decoratives / Interior&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="homedecor"&gt;Home Decor&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="furnitures"&gt;Furnitures&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="toys"&gt;Toys&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="vehicles"&gt;Vehicles&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p>If you want to check all the checkboxes, set the checked property to <code>true</code> rather than to the state of the changed box. Below, if your click results in zero boxes checked, all boxes will become checked.</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>$('input[type="checkbox"]').change(function() { if ($('input[type="checkbox"]:checked').length == 0) { $('.checkbox1,.checkbox0').prop('checked', true); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;ul class="expander-list" id="category"&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" id="all" name="filter" class="checkbox0" value="all"&gt;all&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="electronics"&gt;Electronics&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="kitchen"&gt;Kitchen&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="decoratives"&gt;Decoratives / Interior&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="homedecor"&gt;Home Decor&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="furnitures"&gt;Furnitures&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="toys"&gt;Toys&lt;/label&gt;&lt;/li&gt; &lt;li&gt;&lt;label&gt;&lt;input type="checkbox" name="filter" class="checkbox1" value="vehicles"&gt;Vehicles&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
Thread 1: signal SIGABRT Login Button Causes App to Crash <p>Currently trying to finish up making the login and registration form for my app. Registration works like how I want it to, but after working on the login screen I get the Thread 1: signal SIGABRT message on my AppDelegate.</p> <p><a href="https://i.stack.imgur.com/HdJri.png" rel="nofollow">AppDelegate File</a></p> <p>So a little more detail about what I'm doing. I'm creating a main ViewController that gives the option to proceed to the login screen or the registration screen. I've set up my registration screen and it works fine, but I can't proceed to my login screen because it crashes when I press the login button on my main ViewController.</p> <p><a href="https://i.stack.imgur.com/0lucY.png" rel="nofollow">main ViewController</a></p> <p>This is my first project and would appreciate any and all help thanks!</p>
<p>Here is the probable reason from the crash log.</p> <ul> <li>Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key emailTxt.' * First throw call stack: ( 0 CoreFoundation 0x000000010c05634b</li> </ul> <p>You might have created an outlet called "emailTxt". You might have then deleted it or changed its name.</p> <p>To solve this, look at the elements you have in your storyboard, my guess is the login button or the email field might have two outlets. Find the one you no longer need and delete it.</p> <p>In case you want to know how to find the outlets that UI element is connect to, just right click on it.</p>
Converting a list of dictionaries to models <p>I have a <code>List</code> containing a <code>Dictionary&lt;string, string&gt;</code> that represents lines from a database from multiple joined tables. I have tried all sorts of LINQ approaches but I always hit a wall where LINQ just doesn't allow certain operations on this data structure. I have tried to simplify the code example as much as I think I can without misrepresenting the core issue so...</p> <p>How can I extract explicit <code>KeyValuePairs</code> from a <code>Dictionary</code> inside of a <code>List</code> and put it into a <code>Model</code>?</p> <p>I need a scale-able solution where the <code>Model</code> could do the same with the subData.</p> <pre><code>public class Program { public static void Main(string[] args) { List&lt;Dictionary&lt;string, string&gt;&gt; data = GetData(); data.Add(new Dictionary&lt;string, string&gt;() { ["modelData"] = "Bob", ["subModelData"] = "Frank" }); data.Add(new Dictionary&lt;string, string&gt;() { ["modelData"] = "Nancy", ["subModelData"] = "Boy" }); List&lt;Model&gt; models = new List&lt;Model&gt;(); //Fails in this linq statement. Anonymous types don't allow key accessors foreach (Dictionary&lt;string, string&gt; distinctModel in data.GroupBy(x =&gt; new { x["dataKey"] })) { List&lt;Dictionary&lt;string, string&gt;&gt; newModelData = data.Where(d =&gt; d["data1Key"] == distinctModel["dataKey"]).ToList(); Model newModel = new Model(newModelData); models.Add(newModel); } } } public class Model { public string modelData; public List&lt;Dictionary&lt;string, string&gt;&gt; subData; public Model(List&lt;Dictionary&lt;string, string&gt;&gt; data) { modelData = data[0]["dataKey"]; data.Remove("dataKey"); subData = data; } } </code></pre>
<p>Anonymous type projection initializer should be a simple name or member access. So you need to add an explicit name like below:</p> <pre><code>data.GroupBy(x =&gt; new {S = x["dataKey"] }) </code></pre>
queryBuilder create sql with innerJoin <p>i can't to do true query from 2 tables.</p> <pre><code> /** * Order * * @ORM\Table(name="order_work") * @ORM\Entity(repositoryClass="AppBundle\Repository\OrderWorkRepository") */ class OrderWork { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\ManyToOne(targetEntity="Client", cascade={"persist"}) * @ORM\JoinColumn(name="client_id", referencedColumnName="id") */ private $client; /** * @var string * * @ORM\Column(name="orderNumber", type="string", length=255) */ private $orderNumber; </code></pre> <p>and client entity have id, name, surname parameters:</p> <p>I want to do search by orders column, and by client parameters how i can which query?)</p> <p>only for orders work this:</p> <pre><code>$queryBuilder = $this-&gt;createQueryBuilder('c') -&gt;orWhere('c.orderNumber LIKE :term') -&gt;orWhere('c.device LIKE :term') -&gt;setParameter('term', '%'.$term.'%'); </code></pre>
<p>You have to make a query with a join, which is possible with the querybuilder but i like to use DQL.</p> <pre><code>public function findOrdersOnClientName($searchTerm) { return $this-&gt;getEntityManager()-&gt;createQuery( 'SELECT o, c FROM AppBundle:OrderWork o JOIN o.client c WHERE c.name LIKE :term' )-&gt;setParameter('term, '%'. $searchTerm . '%')-&gt;getResult(); } </code></pre>
How do I obtain a cross product with multiple tables? <p>I am trying to obtain a cross product between two lists. I can see that the problem is that it's trying to append <code>(CP2 T1 T2)</code> with <code>(CP2 T1 T3)</code>. I have thought of other ways, such as <code>(CP2 (CP2 T1 T2) ...)</code>, but again, the ellipses just expand into an undesired output.</p> <pre><code>(define-syntax CP (syntax-rules () ((CP T1 T2 ...) (append (CP2 T1 T2) ...) ) ) ) (define (CP2 T1 T2) (foldr append '() (map (λ(x) (map (λ(y) (append x y)) T2)) T1)) ) </code></pre> <p>Is it not possible doing it this way at all?</p> <p>Thank you.</p>
<p>It can be done with one of the for loops also ( <a href="http://docs.racket-lang.org/reference/for.html" rel="nofollow">http://docs.racket-lang.org/reference/for.html</a> ): </p> <pre><code>(define (myproduct l1 l2) (for*/list ((i l1)(j l2)) (list i j))) (myproduct '(1 2 3) '(a b c)) </code></pre> <p>Ouput: </p> <pre><code>'((1 a) (1 b) (1 c) (2 a) (2 b) (2 c) (3 a) (3 b) (3 c)) </code></pre>
AngularJS expandable table with aligned columns <p>With every example I can find of an expandable table using ng-repeat, the expanded row is "separate" content, such as an independent table inside the detail row. I have done many expandable tables using these methods, something like </p> <pre><code>&lt;tr ng-repeat-start="item in faceted.table.data" ng-init="item.showDetails = false" ng-click="faceted.table.showDetailRow($index)"&gt; &lt;td&gt; &lt;a href="" class="table-row-toggle"&gt; &lt;i class="nc-icon-mini lg fw arrows-2_small-right " ng-class="{'rotate-90': item.showDetails}"&gt;&lt;/i&gt; &lt;/a&gt; &lt;/td&gt; &lt;td&gt;{{item.partner_name}}&lt;/td&gt; &lt;td&gt;{{item.type}}&lt;/td&gt; &lt;td&gt;&gt;{{m.merchant_name}}&lt;/td&gt; &lt;/tr&gt; &lt;tr class="table-details" ng-repeat-end="item in faceted.table.data" ng-if="faceted.table.detailsShown === $index"&gt; &lt;td&gt;&lt;/td&gt; &lt;td colspan="7"&gt; &lt;table class="table table-unstyled"&gt; &lt;tbody&gt; &lt;tr ng-repeat="m in item.merchants"&gt; &lt;td&gt;{{m.merchant_name}}&lt;/td&gt; &lt;td&gt;{{m.type}}&lt;/td&gt; &lt;td&gt;{{m.state}}&lt;/td&gt; &lt;td&gt;&lt;img src="images/status.svg" alt="status"&gt;&lt;/td&gt; &lt;td&gt;{{m.modified_by}}&lt;/td&gt; &lt;td&gt;{{m.modified_date}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>However, what I need to have this time is the "detail" rows have to be part of the main table so the columns align, as in this Axure screenshot:</p> <p><a href="https://i.stack.imgur.com/vwstb.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/vwstb.jpg" alt="enter image description here"></a></p> <p>The gray rows are children of the white rows. I can access the data as in my code example, but cannot make the columns align.</p> <p>I have tried a few ways, but nothing so far seems to work.</p>
<p>You can achieve this using ng-repeat-start and ng-repeat-end. The key difference is that your detail objects need to be children of the parent objects, not children of the same object.</p> <pre><code>&lt;tbody&gt; &lt;tr ng-repeat-start="parent in vm.parents"&gt; &lt;tr class="parent-entry"&gt; &lt;!-- cells go here ex:{{parent.data}} --&gt; &lt;/tr&gt; &lt;tr class="child-entry" ng-repeat-end ng-if="parent.show"&gt; &lt;!-- cells go here, ex:{{parent.child.data}}--&gt; &lt;/tr&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre>
Button under recyclerview is not visible <p>I'm progrmming app with <code>RecyclerView</code> and bottom buttons. <code>RecyclerView</code> is filling by images, that I got from the server. Top bar is fixed</p> <p><a href="http://joxi.ru/KAxee4XTEMpPr8" rel="nofollow">http://joxi.ru/KAxee4XTEMpPr8</a></p> <p><strong>RecyclerView code</strong></p> <pre><code>&lt;android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; </code></pre> <p><strong>RecyclerView is filling by ImageViews</strong></p> <pre><code> &lt;ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="100dp" android:scaleType="centerCrop" android:layout_marginBottom="1dp" android:layout_marginEnd="1dp" android:layout_marginStart="1dp" android:layout_marginTop="1dp" /&gt; </code></pre> <p><strong>Buttons code that invisible</strong></p> <pre><code> &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="3"&gt; &lt;ru.noorsoft.rubkoff.HeButton android:id="@+id/button1" style="@style/leftButStyle" android:layout_width="wrap_content" android:layout_height="55dp" android:layout_weight="1" android:gravity="center" android:textAllCaps="false" android:textColor="@color/colorBlue" android:textSize="20sp" /&gt; &lt;ru.noorsoft.rubkoff.HeButton android:id="@+id/button2" android:background="@android:color/transparent" android:layout_width="wrap_content" android:layout_height="55dp" android:layout_weight="1" android:textColor="@color/colorBlue" android:textAllCaps="false" android:textSize="20sp" /&gt; &lt;ru.noorsoft.rubkoff.HeButton android:id="@+id/button3" style="@style/rightButStyle" android:layout_width="wrap_content" android:layout_height="55dp" android:layout_weight="1" android:textColor="@color/colorBlue" android:textAllCaps="false" android:textSize="20sp" /&gt; &lt;/LinearLayout&gt; </code></pre>
<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:tools="http://schemas.android.com/tools"&gt; &lt;RelativeLayout android:id="@+id/header" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;!-- here goes the header --&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="header"/&gt; &lt;/RelativeLayout&gt; &lt;android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" tools:listitem="@android:layout/simple_gallery_item" android:layout_below="@id/header" android:clipToPadding="false" android:paddingBottom="55dp"/&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="55dp" android:orientation="horizontal" android:layout_alignParentBottom="true" android:weightSum="3"&gt; &lt;ru.noorsoft.rubkoff.HeButton android:id="@+id/button1" style="@style/leftButStyle" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:textAllCaps="false" android:textColor="@color/colorBlue" android:textSize="20sp" /&gt; &lt;ru.noorsoft.rubkoff.HeButton android:id="@+id/button2" android:background="@android:color/transparent" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:textColor="@color/colorBlue" android:textAllCaps="false" android:textSize="20sp" /&gt; &lt;ru.noorsoft.rubkoff.HeButton android:id="@+id/button3" style="@style/rightButStyle" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:textColor="@color/colorBlue" android:textAllCaps="false" android:textSize="20sp" /&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre>
How to include value within he file= string of a write.xlsx command <p>I'm struggling with finding out how to get a vlaue to resolve within speech marks. In the blow example, the is a load of other code logic between the setting of outputfolder and the write.xlsx line. Any suggestions?</p> <pre><code>client_name &lt;-"client a" project_name &lt;-"project x" outputfolder &lt;-"D:/client_abc_folder" write.xlsx(df, file="outputfolder/client_name_project_name.xlsx", sheetName="my analysis", row.names = FALSE, append=TRUE) </code></pre>
<p>Use <code>paste0(outputfolder, "/", client_name, "_", project_name, ".xlsx")</code></p>
how to change an old commit to become a fixup commit <p>I have list of commits:</p> <pre><code>1a First commit 2b Second commit 3c Third commit 4d fixup! First Commit 5e fixup! Second Commit 6f fixup! Third Commit HEAD 6f </code></pre> <p>I want to be able to change a commit in the past to become a fixup, and in some cases I want to redirect all fixup! pointing to that commit to point to the new fixup! commit</p> <p>say.</p> <pre><code>1a First commit 2b Second commit 3c fixup! First Commit 4d fixup! First Commit 5e fixup! Second Commit 6f fixup! First Commit </code></pre>
<ul> <li><p>If you want to keep these commits marked as <code>fixup!</code>:</p> <p>Use <code>git rebase -i</code> and change <code>pick 3c Third commit</code> to <code>reword 3c Third commit</code>. You will also need to restore the order and operations of the commits marked with <code>fixup!</code> if <code>autosquash</code> is enabled in your configuration.</p></li> <li><p>If you don't want to just convert <code>3c</code> to <code>fixup!</code>, but you also want to apply the fix-ups as amends to the corresponding commits:</p> <p>Use <code>git rebase -i --autosquash</code> and change <code>pick 3c Third commit</code> to <code>fixup 3c Third commit</code> and move it up to right after the <code>pick 1a First commit</code>. The other commits will already be reordered.</p></li> </ul>
How to return percentage in PostgreSQL? <p>CREATE TEMPORARY TABLE</p> <pre><code>CREATE TEMP TABLE percentage( gid SERIAL, zoom smallint NOT NULL, x smallint NOT NULL, y smallint NOT NULL ); </code></pre> <p>INSERT DATA</p> <pre><code>INSERT INTO percentage(zoom, x, y) VALUES (0,5,20), (0,5,21), (0,5,21), (0,5,22), (0,5,22), (0,5,22), (0,5,23), (0,5,23), (0,5,23), (0,5,23), (0,5,24), (0,5,24), (0,5,24), (0,5,24), (0,5,24), (1,5,20), (1,5,21), (1,5,21), (1,5,22), (1,5,22), (1,5,22), (1,5,23), (1,5,23), (1,5,23), (1,5,23), (1,5,24), (1,5,24), (1,5,24), (1,5,24), (1,5,24); </code></pre> <p>How many times certain tile shows up (<strong>tile</strong> is represented by <strong>x and y</strong>)</p> <pre><code>SELECT zoom, x, y, count(*) AS amount FROM percentage GROUP BY zoom,x,y ORDER BY zoom, amount; </code></pre> <p>Result:</p> <pre><code> zoom | x | y | amount ------+---+----+-------- 0 | 5 | 20 | 1 0 | 5 | 21 | 2 0 | 5 | 22 | 3 0 | 5 | 23 | 4 0 | 5 | 24 | 5 1 | 5 | 20 | 1 1 | 5 | 21 | 2 1 | 5 | 22 | 3 1 | 5 | 23 | 4 1 | 5 | 24 | 5 (10 rows) </code></pre> <p><strong>Question</strong></p> <p>How to get back percentage of each tile (x and y) for certain zoom, or in other words, how many times have the certain tile showed up for certain zoom?</p> <p>Wanted result:</p> <pre><code> zoom | x | y | amount | percentage ------+---+----+--------+----------- 0 | 5 | 20 | 1 | 6.667 0 | 5 | 21 | 2 | 13.333 0 | 5 | 22 | 3 | 20 0 | 5 | 23 | 4 | 26.667 0 | 5 | 24 | 5 | 33.333 1 | 5 | 20 | 1 | 6.667 1 | 5 | 21 | 2 | 13.333 1 | 5 | 22 | 3 | 20 1 | 5 | 23 | 4 | 26.667 1 | 5 | 24 | 5 | 33.333 (10 rows) </code></pre> <p>*This is just a sample data, percentages are not supposed to be the same, except as a pure coincidence!</p>
<p>If am not wrong you are looking for this </p> <pre><code>SELECT zoom,x,y, amount, ( amount / Cast(Sum(amount) OVER(partition BY zoom) AS FLOAT) ) * 100 as amt_percentage FROM (SELECT zoom,x, y, Count(*) AS amount FROM percentage GROUP BY zoom,x,y) a </code></pre> <p>Or even </p> <pre><code>SELECT zoom,x,y, Count(*) AS amount, ( Count(*) / Cast(Sum(Count(*))OVER(partition BY zoom) AS FLOAT) ) * 100 AS amt_percentage FROM percentage GROUP BY zoom,x,y </code></pre> <p><em>Casting</em> the denominator to <code>FLOAT</code> is avoid the <code>Integer</code> division </p>
how to add two numbers input like one + two and output should be three in java? <p>Today I went one interview, interviewer ask me this question, I tried with StringBuffer but he not convinced please tell how I will do approach. </p>
<p>Am not telling this is the right answer, but maybe the HR just wanted to check your creativity applied to java language..</p> <p>something like:</p> <pre><code>public class Test { public static void main(String[] args) { System.out.println(Number.values()[Number.One.getNumber() + Number.Two.getNumber()]); } } public enum Number { Zero(0), One(1), Two(2), Three(3); private final int someIndexThatLooksLikeACardinalButIsNot; private Number(int card) { this.someIndexThatLooksLikeACardinalButIsNot = card; } public int getNumber() { return this.someIndexThatLooksLikeACardinalButIsNot; } } </code></pre> <h1>Note before down vote:</h1> <p>If your Enum would be defined in the exactly order, then there is no need for an int variable for cardinality value, but <strong>IT IS</strong> a good practice not relying to the order of the defined fields in the enum...(It has to work even if the order changes.)</p>
Getting error:No adapter attached; skipping layout in recyclerview <p>I tried to fetch the json values from url and shows in listview with adapter in recylerview. but the listview is empty and getting this error 'No adapter attached; skipping layout'. When I tried with the below code its working</p> <pre><code>for (int i = index; i &lt; end; i++) { User user = new User(); user.setName("Name " + i); mUsers.add(user); } </code></pre> <p>Here is my part of code, if needed I'll upload complete code </p> <pre><code>public class OtherNews extends AppCompatActivity { JSONArray jsonarray; private RecyclerView mRecyclerView; private List&lt;User&gt; mUsers = new ArrayList&lt;&gt;(); private UserAdapter mUserAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); mRecyclerView = (RecyclerView) findViewById(R.id.recycleView); mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); mUserAdapter = new UserAdapter(); new DownloadJSON().execute(); mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() { @Override public void onLoadMore() { Log.e("haint", "Load More"); mUsers.add(null); mUserAdapter.notifyItemInserted(mUsers.size() - 1); //Load more data for reyclerview new Handler().postDelayed(new Runnable() { @Override public void run() { Log.e("haint", "Load More 2"); //Remove loading item mUsers.remove(mUsers.size() - 1); mUserAdapter.notifyItemRemoved(mUsers.size()); //Load data int index = mUsers.size(); int end = index + 20; for (int i = index; i &lt; end; i++) { User user = new User(); user.setName("Name " + i); user.setEmail("alibaba" + i + "@gmail.com"); mUsers.add(user); } mUserAdapter.notifyDataSetChanged(); mUserAdapter.setLoaded(); } }, 5000); } }); } // DownloadJSON AsyncTask private class DownloadJSON extends AsyncTask&lt;Void, Void, Void&gt; { private static final String TAG = ""; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { // Create an array HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall("http://xxxxxxxxx.in/projects/falcon/getallnews.php?page=2"); if (jsonStr != null) { try { JSONObject jsonobject = new JSONObject(jsonStr); jsonarray = jsonobject.getJSONArray("news"); // Getting JSON Array node for (int i = 0; i &lt; jsonarray.length(); i++) { User user = new User(); String title = jsonobject.getString("title"); user.setName(title); mUsers.add(user); } } catch (final JSONException e) { } } else { Log.d(TAG, "someOther)"); } return null; } @Override protected void onPostExecute(Void args) { mRecyclerView.setAdapter(mUserAdapter); } } </code></pre> <p>I get the value in this line of code, but couldn't set in list view.</p> <pre><code>String title = jsonobject.getString("title"); user.setName(title); </code></pre>
<p>The issue is exactly like it sounds, an adapter is not being attached when it needs it. You don't attach it until <code>onPostExecute</code>. Just attach it right from the beginning:</p> <pre><code>mRecyclerView = (RecyclerView) findViewById(R.id.recycleView); mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); mUserAdapter = new UserAdapter(); mRecyclerView.setAdapter(mUserAdapter); </code></pre> <p>As you modify the adapter in other parts of the code, your RecyclerView will update automatically, so long as you call <code>notifyDataSetChanged()</code> or some related method.</p>
Angular 2 Final Release cannot find name module - moduleId: module.id <p>I just upgraded to the Angular 2 Final Release from RC 4 and I am now getting an error <code>cannot find name 'module'</code> on my code:</p> <pre><code>@Component({ selector: 'dashboard', moduleId: module.id, templateUrl: 'dashboard.component.html', styleUrls: ['dashboard.component.css'], styles: ['.chart {display: block; width: 100%;} .title.handle{background-color:transparent;}'] }) </code></pre> <p>Any ideas?</p> <p>Thanks in advance!</p> <p>UPDATE, this is the error:</p> <pre><code>zone.js:355 Unhandled Promise rejection: Template parse errors: Only void and foreign elements can be self closed "span" ("i role="presentation"&gt;&lt;a role="menuitem" tabindex="-1" href="http://BruinAlert.ucla.edu"&gt;BruinAlert [ERROR -&gt;]&lt;span class="icon-external-link" /&gt;&lt;/a&gt;&lt;/li&gt; &lt;li role="presentat"): WidgetBankComponent@104:138 Only void and foreign elements can be self closed "span" ("tion"&gt;&lt;a role="menuitem" tabindex="-1" href="https://logon.ucla.edu/passchange.php"&gt;Change Password [ERROR -&gt;]&lt;span class="icon-external-link" /&gt;&lt;/a&gt;&lt;/li&gt; at DirectiveNormalizer.normalizeLoadedTemplate (http://localhost:56159/node_modules/@angular/compiler//bundles/compiler.umd.js:13373:21) at eval (http://localhost:56159/node_modules/@angular/compiler//bundles/compiler.umd.js:13366:53) at ZoneDelegate.invoke (http://localhost:56159/node_modules/zone.js/dist/zone.js:203:28) at Zone.run (http://localhost:56159/node_modules/zone.js/dist/zone.js:96:43) at http://localhost:56159/node_modules/zone.js/dist/zone.js:462:57 at ZoneDelegate.invokeTask (http://localhost:56159/node_modules/zone.js/dist/zone.js:236:37) at Zone.runTask (http://localhost:56159/node_modules/zone.js/dist/zone.js:136:47) at drainMicroTaskQueue (http://localhost:56159/node_modules/zone.js/dist/zone.js:368:35) at XMLHttpRequest.ZoneTask.invoke (http://localhost:56159/node_modules/zone.js/dist/zone.js:308:25)consoleError @ zone.js:355_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386ZoneTask.invoke @ zone.js:308 zone.js:357 Error: Uncaught (in promise): Error: Template parse errors:(…)consoleError @ zone.js:357_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386ZoneTask.invoke @ zone.js:308 </code></pre>
<p>Edit after updated question:</p> <p>Your HTML template is incorrect, you have a self-closing span element like this:</p> <p><code>&lt;span class="icon-external-link" /&gt;</code> </p> <p>which is not allowed in HTML. </p> <p>Change it to <code>&lt;span class="icon-external-link"&gt;&lt;/span&gt;</code></p> <hr> <p>Before edit:</p> <p>Are you using the latest angular-cli with Webpack? If yes, you should remove all <code>moduleId</code> references, as this upgrade guide describes:</p> <p><a href="https://github.com/angular/angular-cli/wiki/Upgrading-from-Beta.10-to-Beta.14" rel="nofollow">https://github.com/angular/angular-cli/wiki/Upgrading-from-Beta.10-to-Beta.14</a></p> <blockquote> <ol start="12"> <li>Remove all mention of moduleId: module.id. In webpack, module.id is a number but Angular expect a string.</li> </ol> </blockquote>
Error: double free or corruption (out): 0x00007fffffffddf0 *** <p>I am playing around with hierarchical objects and pointers and have written a base class Circle, then two classes Cylinder and Sphere that both derive from Circle. When I run the program I get the error: double free or corruption (out): 0x00007fffffffddf0 ***</p> <p>So I tried running the code through GDB. I found that the error occurs when I call the Cylinder destructor, which calls the virtual destructor for Circle. However I don't understand why this is happening. From my research it seems this kind of error occurs when the code tries to deallocate memory that is not available to it.</p> <p>I thought perhaps the destructor for Cylinder was causing the problem, since it is called first, so I commented out all of the Sphere and Circle object lines in main() and just used the Cylinder code. When the destructor for the Cylinder pointer was called it resulted in a Segmentation Fault, so I am trying to access memory out of range. </p> <p>Now I'm thoroughly confused.</p> <p>Here is my code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; // used for square static constexpr float PI = 3.14159; using namespace std; class Circle{ protected: float radius; public: float getRadius(){ return radius; } void setRadius(float r){ radius = r; } float calcCircleArea(){ return PI * pow(radius, 2); } float calcCircumference(){ return 2 * PI * radius; } Circle(){ // default constructor } Circle(float rad){ radius = rad; // overloaded constructor } virtual ~Circle(){ // virtual destructor cout &lt;&lt; "Destroying Circle Constructor" &lt;&lt; endl; } }; class Cylinder: public Circle{ private: float height; public: float getHeight(){ return height; } void setHeight(float h){ height = h; } float calcVol(){ float circleArea = calcCircleArea(); float vol = circleArea * height; } float calcSurfaceArea(){ float circum = calcCircumference(); float circleArea = calcCircleArea(); float cylSurfArea = (circleArea *2) + (circum * height); } Cylinder(){} // default constructor Cylinder(float r, float h){ // overloaded constructor radius = r; height = h; } ~Cylinder(){ // destructor cout &lt;&lt; "Destroying Cylinder Constructor" &lt;&lt;endl; } }; class Sphere : public Circle { public: float calcSurfaceArea(){ float r = getRadius(); return 4* PI * pow(r,2); } float calcVol(){ float r = getRadius(); return (4.0/3.0) * PI * pow(r,3); } Sphere(){} // default constructor Sphere(float r){ radius = r; } ~Sphere(){ // destructor cout &lt;&lt; "Destroying Sphere Constructor" &lt;&lt; endl; } }; int main(){ cout &lt;&lt; "Enter radius of circle and height of cyl:" &lt;&lt; endl; float r; float h; cin &gt;&gt; r &gt;&gt; h; Sphere s1(r); Cylinder cyl1(r,h); Circle cir1(r); //**************************** // Set up pointers //**************************** Circle *circPtr; circPtr = &amp;cir1; Sphere *sPtr; sPtr = &amp;s1; Cylinder *cylPtr; cylPtr = &amp;cyl1; cout &lt;&lt; "Sphere vol : " &lt;&lt; sPtr-&gt;calcVol() &lt;&lt; endl; cout &lt;&lt; "Sphere SA : " &lt;&lt; sPtr-&gt;calcSurfaceArea() &lt;&lt; endl; cout &lt;&lt; "Cyl vol : " &lt;&lt; cylPtr-&gt;calcVol() &lt;&lt; endl; cout &lt;&lt; "Cyl SA : " &lt;&lt; cylPtr-&gt;calcSurfaceArea() &lt;&lt; endl; cout &lt;&lt; "Circle area : " &lt;&lt; circPtr-&gt;calcCircleArea() &lt;&lt; endl; cout &lt;&lt; "Circle circum : " &lt;&lt; circPtr-&gt;calcCircumference() &lt;&lt; endl; cout &lt;&lt; "sphere RADIUS : " &lt;&lt; sPtr-&gt;getRadius() &lt;&lt; endl; cout &lt;&lt; "cyl pointer VOLUME : " &lt;&lt; cylPtr-&gt;calcVol() &lt;&lt; endl; cout &lt;&lt; "circ pointer AREA: " &lt;&lt; circPtr-&gt;calcCircleArea() &lt;&lt; endl; delete cylPtr; delete sPtr; return 0; } </code></pre>
<p>You're allocating your cylinder and sphere on the stack, then calling delete on pointers to them. This will destroy your objects twice. Once when you call delete, and once when they go out of scope (main ends).</p> <p>Don't call delete on objects that you didn't create with new. Especially don't call delete on the address of stack objects.</p>
How can I get access to StackOverflow data? <p>I need to create reports around tag usage and unanswered posts. What're the different mechanisms available to access this data?</p>
<p>There are mainly 3 options:</p> <p>1) Use <a href="https://data.stackexchange.com/" rel="nofollow">SEDE</a> (Stack Exchange Data Explorer), which allows you to easily query the data. You can download the queried rows, however it does not allow you to run queries locally and can only be used manually.</p> <p>2) Use <a href="https://api.stackexchange.com/">SE API</a>, which allows you to query some things of Stack Overflow over REST calls.</p> <p>3) Download a public release of the SO <a href="https://archive.org/details/stackexchange" rel="nofollow">data dump</a> and use historical data.</p>
How can I remove night time points from GPS track data in R? <p>I have some tracking that looks like the sample below. I would like to be able to remove the rows that occur before 06:00 and after 18:00 i.e. the night time values. </p> <pre><code>tracks &lt;- read.table(text = " 05/04/2015 16:04, 53.3854 , -6.29421 05/04/2015 17:17, 53.38464, -6.29412 05/04/2015 17:33, 53.38457, -6.29409 05/04/2015 17:49, 53.38463, -6.29418 05/04/2015 19:20, 53.38458, -6.29408 05/04/2015 19:49, 53.38452, -6.29394 05/04/2015 20:19, 53.38464, -6.29411 05/04/2015 21:20, 53.38441, -6.29421 06/04/2015 07:13, 53.38459, -6.29414 06/04/2015 08:30, 53.3846, -6.29414 06/04/2015 16:56, 53.38458, -6.29413 06/04/2015 17:05, 53.38469, -6.29416 06/04/2015 17:13, 53.38464, -6.29409 06/04/2015 17:26, 53.38463, -6.29412 06/04/2015 17:39, 53.38463, -6.29411 06/04/2015 19:51, 53.38465, -6.29411 06/04/2015 21:29, 53.38451, -6.29415" , header = F, sep = ",") </code></pre>
<p>You can do this by first extracting the hours and minutes from <code>V1</code> and then use this to subset rows of <code>track</code>:</p> <pre><code>hm &lt;- strftime(as.POSIXct(tracks$V1, format="%m/%d/%Y %H:%M"), "%H:%M") tracks &lt;- tracks["06:00" &lt; hm &amp; hm &lt; "18:00",] ## V1 V2 V3 ##1 05/04/2015 16:04 53.38540 -6.29421 ##2 05/04/2015 17:17 53.38464 -6.29412 ##3 05/04/2015 17:33 53.38457 -6.29409 ##4 05/04/2015 17:49 53.38463 -6.29418 ##9 06/04/2015 07:13 53.38459 -6.29414 ##10 06/04/2015 08:30 53.38460 -6.29414 ##11 06/04/2015 16:56 53.38458 -6.29413 ##12 06/04/2015 17:05 53.38469 -6.29416 ##13 06/04/2015 17:13 53.38464 -6.29409 ##14 06/04/2015 17:26 53.38463 -6.29412 ##15 06/04/2015 17:39 53.38463 -6.29411 </code></pre>
On Touch Method SurfaceView Android doesn't work <p>I created a SurfaceView (you can see it in the following) and started in from my Main Activity. I overwrote the onTouchEvent method in the SurfaceView and the problem is that the data I want to have logged with Log.d isn't logged, I don't get any Message... Does anyone have an idea how I can fix this?</p> <p><strong>My SurfaceView:</strong></p> <pre><code>import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback { private float top; private float left; private float bottom; private float right; private MainThread thread; MainGamePanel(Context context) { super(context); getHolder().addCallback(this); thread = new MainThread(getHolder(), this); setFocusable(true); } @Override public void surfaceCreated(SurfaceHolder holder) { setWillNotDraw(false); thread.setRunningMode(MainThread.RUNNING); thread.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; while (retry) { try { thread.join(); retry = false; } catch (Exception e) { } } } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); right = x + 30; left = x - 30; top = y - 30; bottom = y + 30; Log.d("tag", x + " " + y); return true; } @Override protected void onDraw(Canvas canvas) { } } </code></pre> <p><strong>My Main Activity:</strong></p> <pre><code>import android.app.Activity; import android.os.Bundle; import android.os.PersistableBundle; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); setContentView(new MainGamePanel(getApplicationContext())); } } </code></pre>
<p>Try changing "getApplicationContext()" to "this" in following part of code:</p> <pre><code>setContentView(new MainGamePanel(getApplicationContext())); </code></pre> <p>to</p> <pre><code>setContentView(new MainGamePanel(this)); </code></pre>
How can I get value from label text field which is dynamically changes JavaFX <pre><code>&lt;Label fx:id="lblLibrarianId" layoutX="82.0" layoutY="14.0" prefHeight="24.0" prefWidth="212.0" text="$librarianId" /&gt; </code></pre> <p>I have a controller name <code>LibraryController</code>. I set label value text to <code>librarianId</code> dynamically from another controller. Now, I want to access this <code>librarianId</code> to <code>LibraryController</code>.</p> <pre><code>final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../fxmlfile/librarian.fxml")); fxmlLoader.getNamespace().put("librarianId", librarianId); </code></pre> <p>This is the way how I set the value dynamically to <code>Label text field</code>. Now I want to retrieve that <code>Label Text value</code> to my <code>LibraryController</code>.</p>
<p>In your controller, create your label object, and call getText() you'll need to use the @FXML to associate that object with the fx:id in your .fxml file</p> <p>ex.</p> <pre><code>public class LibraryController{ @FXML public Label lblLibrarianId; public String librarianID; final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../fxmlfile/librarian.fxml")); fxmlLoader.getNamespace().put("librarianId", librarianId); librarianId = lblLibrarianId.getText(); } </code></pre>
yes or no loop (TypeError: 'NoneType' object is not iterable) error <p>I'm trying to implement a yes / no / retry, but I am getting this error: 'NoneType' object is not iterable. I assume the issue is the function (def izberiEkipo() is not returning what it's suppose to.</p> <pre><code>def izberiEkipo(): m = set(['m']) p = set(['p']) while False: if reply in m: with open('vprasanja2.txt') as f: vsaVprasanja = [line.strip() for line in f] max_line = len(vsaVprasanja) True elif reply in p: with open('vprasanja.txt') as f: vsaVprasanja = [line.strip() for line in f] max_line = len(vsaVprasanja) True else: sys.stdout.write("Answer with 'm' ord 'p'") return (max_line, vsaVprasanja) def genVprasanja (): obsVred = set() maxL, vsaQ = izberiEkipo() tocke = 5 total = 0 . . [...] </code></pre>
<p>Your assumption is correct: as given, your upper function returns nothing. You've disabled the loop with a <strong>False</strong> entry condition: it won't run at all. The only <strong>return</strong> in the function is inside that loop.</p> <p>Thus, all that routine does is to create two sets of a single character each, and then return <strong>None</strong> to the main program. Since you haven't included code to reproduce the problem -- in fact, the line that throws the error isn't in your example -- and no trace-back, we can't help much farther than this.</p>
How to use SELECT INTO in a plpgsql PROCEDURE? <p>I'm trying to use <a href="https://www.postgresql.org/docs/9.2/static/sql-selectinto.html" rel="nofollow">SELECT INTO</a> in a plpgsql procedure.</p> <pre><code>CREATE OR REPLACE FUNCTION reset_data() RETURNS void AS $$ BEGIN DROP TABLE IF EXISTS experiment; SELECT * INTO experiment FROM original; END; $$ LANGUAGE plpgsql; </code></pre> <p>This results in an error: </p> <pre><code>ERROR: "experiment" is not a known variable LINE 5: SELECT * INTO experiment FROM original; ^ ********** Error ********** ERROR: "experiment" is not a known variable SQL state: 42601 Character: 113 </code></pre> <p>Apparently, we cannot use SELECT INTO like this. How do we do it?</p>
<p>It's discouraged to use <code>select into</code> to create a table based on a select statement.</p> <p>It is recommended to use the (standard compliant) <a href="https://www.postgresql.org/docs/current/static/sql-createtableas.html" rel="nofollow"><code>create table as</code></a>.</p> <p>The documentation for <code>select into</code> <a href="https://www.postgresql.org/docs/current/static/sql-selectinto.html#AEN91273" rel="nofollow">explicitly mentions PL/pgSQL as one of the reasons</a>:</p> <blockquote> <p><code>CREATE TABLE AS</code> is functionally similar to <code>SELECT INTO</code>. <code>CREATE TABLE AS</code> is the recommended syntax, since this form of <code>SELECT INTO</code> is not available in ECPG or PL/pgSQL, because they interpret the <code>INTO</code> clause differently</p> </blockquote> <p>So your function should be:</p> <pre><code>CREATE OR REPLACE FUNCTION reset_data() RETURNS void AS $$ BEGIN DROP TABLE IF EXISTS experiment; create table experiment as SELECT * FROM original; END; $$ LANGUAGE plpgsql; </code></pre>
SQL Query with one column and multiple LIKEs <p>I got a table with a column which contains content like Driver||Helper||Garden. I want to export this table to a new system, where I have diffrent columns for each user Skill (as it should be).</p> <p>Question: How can I get this kind of information in a nice SQL export.</p> <pre><code>SELECT user_id, driver, helper, garden FROM `ujc72_comprofiler` WHERE cb_erfahrungen LIKE "%Driver%" </code></pre> <p>Gives me the users with a certain skill, but I want multiple columns for one user for my export.</p>
<p>You need to split the string. So,it will divide Driver|Helper|Garden to separate Driver, Helper and Garder columns. </p> <p>This function is absent in mysql. You have to create it your own. Check this link: <a href="https://blog.fedecarg.com/2009/02/22/mysql-split-string-function/" rel="nofollow">https://blog.fedecarg.com/2009/02/22/mysql-split-string-function/</a></p> <hr> <p>Also, you may work with <code>SUBSTRING_INDEX</code> function:</p> <pre><code>mysql&gt; SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2); -&gt; 'www.mysql' mysql&gt; SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2); -&gt; 'mysql.com' </code></pre>
Racket - Building the built-in member function <p>I like writing code to the same thing that built-in functions do. It is always a great exercise for me.</p> <p>In racket there is a bult-in function called "member" which checks if a certain element is inside a list. If true, the function returns the rest/cdr o the list If false, the function returns #f. Examples:</p> <pre><code>&gt; (member 2 (list 1 2 3 4)) '(2 3 4) &gt; (member 9 (list 1 2 3 4)) #f </code></pre> <p>I did the following code:</p> <pre><code>(require racket/trace) (define (member-mine lista num) (cond ((equal? (car lista) num) (cdr lista)) ((equal? (car lista) '()) #f) (else (member-mine (cdr lista) num)))) (define small-list (list 1 2 3 4 5 6 7 8)) (trace member-mine) </code></pre> <p>And, when I try using it with the cool tool trace, I am partially successful.</p> <p>Calling:</p> <pre><code>(member-mine small-list 1) </code></pre> <p>Returns:</p> <pre><code>&gt;(member-mine '(1 2 3 4 5 6 7 8) 1) &lt;'(2 3 4 5 6 7 8) </code></pre> <p>Calling:</p> <pre><code>(member-mine small-list 8) </code></pre> <p>Returns:</p> <pre><code>&gt;(member-mine '(1 2 3 4 5 6 7 8) 8) &gt;(member-mine '(2 3 4 5 6 7 8) 8) &gt;(member-mine '(3 4 5 6 7 8) 8) &gt;(member-mine '(4 5 6 7 8) 8) &gt;(member-mine '(5 6 7 8) 8) &gt;(member-mine '(6 7 8) 8) &gt;(member-mine '(7 8) 8) &gt;(member-mine '(8) 8) &lt;'() </code></pre> <p>The problem is when I call an element which is not in the list given. The output should be #f:</p> <pre><code>(member-mine small-list 9) </code></pre> <p>Which returns is an error:</p> <pre><code>&gt;(member-mine '(1 2 3 4 5 6 7 8) 9) &gt;(member-mine '(2 3 4 5 6 7 8) 9) &gt;(member-mine '(3 4 5 6 7 8) 9) &gt;(member-mine '(4 5 6 7 8) 9) &gt;(member-mine '(5 6 7 8) 9) &gt;(member-mine '(6 7 8) 9) &gt;(member-mine '(7 8) 9) &gt;(member-mine '(8) 9) &gt;(member-mine '() 9) . . car: contract violation expected: pair? given: '() </code></pre> <p>How do I manage to deal with the empty?</p>
<p>There are some issues with your code. As a first observation you have switched the contract so that the list comes first instead of last. </p> <p>It also seem that you are checking if one of the elements is the empty list and not the list itself. Thus your <code>member</code> would terminate with <code>#f</code> in this case:</p> <pre><code>(member-mine '(() 1 2 3 4 5 6 7 8) 1) ; ==&gt; #f </code></pre> <p>So your member should check if the whole argument is <code>null?</code> (<code>empty?</code>) or perhaps check if it's not <code>pair?</code>. Then it should evaluate to <code>#f</code>.</p> <p>If the first element matches your search, then the original <code>member</code> evaluates to the whole argument with the match as the first element and not the <code>cdr</code> like in your code.</p>
How to configure git-diff so that long line not wrap around? <p>I sometimes have long line of code in git repo (e.g. a json config file), and <code>git diff</code> will generate output like below.</p> <p><img src="https://www.dropbox.com/s/71o88x38fgmwhlb/git-diff-config-multi-lines.png?dl=1" alt="long line"></p> <p>On an EC2 instance, I <code>git diff</code> doesn't wrap the content to the next line, generating following output (I can use left/right keys to navigate), which I personally prefer.</p> <p><img src="https://www.dropbox.com/s/neuqxrxi8n82w12/git-diff-config-one-line.png?dl=1" alt="short line"></p> <p>Does any one know how I can config the <code>git-diff</code> to change from one behavior to another?</p>
<p>It's your terminal or pager program that wraps the lines, not <code>git diff</code>. Try redirecting the output of <code>git diff</code> into a file and open it with an editor that allows to control wrapping - you will see that the lines are not actually wrapped. </p> <p>You can try this:</p> <pre><code>git diff|cut -c -$COLUMNS </code></pre> <p>Note however that it will disable colors and paging.</p>
find a date range from min and max date field <p>I am trying to find the earliest instance of a date for a unique ID (unique ID has multiple rows of data with different dates) and then filter that result to find the data between years 2005 and 2010 using a subquery. I keep getting 'Incorrect syntax near the keyword 'group'':</p> <pre><code>Select * from (select custnum, YEAR(min(Date_field)) as field1, Field2, field3, field4, field5 from table1 group by custnum, field2, field3, field4, field5) having YEAR(min(Date_field)) between 2005 and 2010 </code></pre> <p>Any Ideas? Thanks for your help-</p>
<p>If I understood you correctly, you can use:</p> <pre><code>WITH CTE AS ( SELECT custnum, Field2, Field3, Field4, Field5, Field1 = MIN(Date_Field) OVER(PARTITION BY custnum) FROM dbo.table1 ) SELECT * FROM CTE WHERE Field1 BETWEEN '20050101' AND '20101231'; </code></pre>
Migrating from log4j-1.2 to slf4j with log4j-2.6 binding <p>I am trying to migrate an existing project from direct log4j to slf4j with log4j binding. Also I am upgrading the the version of log4j from 1.2 to 2.6</p> <p>Some of the common code change are :-</p> <p>1.</p> <pre><code>import org.apache.log4j.Logger; . . . private final static Logger log = Logger.getLogger(SearchXYZ.class); </code></pre> <p>becomes</p> <pre><code>import org.slf4j.Logger; import org.slf4j.LoggerFactory; . . . private final static Logger log = LoggerFactory.getLogger(SearchXYZ.class); </code></pre> <p>2.</p> <pre><code>import org.apache.log4j.Logger; . . . private static final Logger logger = Logger.getLogger(XYZ.class); . . . logger.fatal("FAILURE", throwableObject); </code></pre> <p>becomes</p> <pre><code>import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; . . . private static final Logger logger = LoggerFactory.getLogger(XYZ.class); private static Marker fatal = MarkerFactory.getMarker("FATAL"); . . . logger.error(fatal, "FAILURE", throwableObject); </code></pre> <ol start="3"> <li>Removed Appenders.</li> </ol> <p>and so on.</p> <p>One place I'm stuck is Configurator file. </p> <pre><code>AppConfigLog4jConfigurator.configureForBootstrap(); </code></pre> <p>It gives compile time error saying :-</p> <blockquote> <p>class file for org.apache.log4j.spi.Configurator not found</p> </blockquote> <p>What does this function do? What is a possible replacement for this?</p>
<p>First, I am not really sure why you are switching to the SLF4J API since the Log4j 2 API supports everything SLF4J does and much more. In my own code I have found that switching only requires changing the imports and LoggerFactory to LogManager.</p> <p>Configurator is a class in Log4j 1 that is used to configure Log4j. It is similar to the Configurator class in Log4j 2. You probably want to call one of the initialize methods.</p>
How do you validate an email field in angular 2 using model driven form <p>How do you validate an email field in angular 2 using model driven form, this is what I have so far.</p> <p><em>This is my form component</em></p> <pre><code>export class signinComponent { signinform: FormGroup; constructor(public fb: FormBuilder) { this.signinform = this.fb.group({ name: ['', Validators.required], email: ['', Validators.required] }); } } </code></pre> <p><em>This is my form html</em></p> <pre><code>&lt;form class="ui form" [formGroup]="signinform" novalidate&gt; &lt;div&gt; &lt;input type="email" class="emailinput" [formControl]="signinform.controls['email']" placeholder="Email Address"&gt; &lt;/div&gt; &lt;/form </code></pre>
<p>Validation method:</p> <pre><code>authEmailValidation( control: FormControl ): {[s:string]:boolean} { let pattern = /^(([^&lt;&gt;()\[\]\\.,;:\s@"]+(\.[^&lt;&gt;()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if ( !pattern.test( control.value ) ) { return { email: true }; } return null; } </code></pre> <p>In your component:</p> <pre><code>this.signinform = this.fbuilder.group( { email : ["", [this.authEmailValidation]], // Other fields.... } ); </code></pre> <p>Note: dnt forget in constructor : </p> <pre><code>private signinform : FormGroup; private fbuilder: FormBuilder // and import them </code></pre>
visual studio 2015 find and replace not working <p>After Windows 10 auto installed the Anniversary Update, along with installing Visual Studio 2015 Update 3 (using Visual Studio Enterprise Edition), any time I try to use the Find in Files, or Replace in Files window has a scrambled UI, and no am unable to click / use any of the controls.</p> <p>I have attached screen shots of the Find in Files, Replace in Files for reference purposes.</p> <p>Any ideas on how to fix it. Never realized how much I depended on the Find in Files tool until it's been taken away from me!</p> <p><img src="https://i.stack.imgur.com/L372D.png" alt="Find in File UI"></p> <p><img src="https://i.stack.imgur.com/h9guV.png" alt="Replace in Files UI"></p>
<p>The issue seems to have fixed itself with the Oct 12 windows update. From looking at the descriptions of the 'Cumulative Update for Windows 10 Version 1607 for x64-based Systems (<a href="https://support.microsoft.com/en-us/kb/3194798" rel="nofollow">KB3194798</a>)'. Unable to duplicate this issue anymore</p>
Why is arithmetic + preferred over textual one? <p>If I run</p> <pre><code>select '1' + '1' </code></pre> <p>the result is 11, since I have added a text to another one.</p> <p>If I run</p> <pre><code>select 1 + '1' </code></pre> <p>the result is 2. I assume the arithmetic operator is chosen over the concatenator because of the type of the first operand. If my reasoning was valid, then the result of</p> <pre><code>select '1' + 1 </code></pre> <p>would be 11. But instead, it is 2. So, it seems that the operator + is tried to be used as an arithmetic operator and if neither of the operands is arithmetic, then goes on to the next operator. If that is true, that would explain why did I get the error of</p> <blockquote> <p>Conversion failed when converting the varchar value 'customer_' to data type int.</p> </blockquote> <p>instead of <code>customer_&lt;somenumber&gt;</code> when I ran a <code>select and had 'customer_' + &lt;somenumber&gt;</code>.</p> <p>Long story short: I think I observed that arithmetic <code>+</code> is preferred over its meaning of concatenation at SQL Server. Am I right? If so, is there an official reason of this behavior?</p>
<p>What you're running into is a matter of <a href="https://msdn.microsoft.com/en-us/library/ms190309.aspx" rel="nofollow">data type precedence</a>. SQL Server looks to character data types <strong>after</strong> numerics. So regardless of the ordering of your operands (<code>1 + '1'</code> vs <code>'1' + 1</code>), it's attempting to convert your types to numerics, and succeeding.</p> <p>The same happens with your second attempt - it's trying to convert the string <code>customer_</code> to an integer because you're using an arithmetic operator along with an integer.</p>
Git: Branch of Branch is not fully Rendering CSS <p>I am new to Git. For my project, I have a branch called staging which is a branch off of master. I created a new branch called salesforce_update off of the staging branch. When I am on the staging branch, everything runs and renders well. When I switch over to the salesforce_update branch, it runs fine but when it renders, all of the styling on the page is gone. The data on the page displays correctly and functionality still works. Is there a reason why this is happening?</p>
<p>If you are using a task runner to compile your assets you may run into issues when switching branches with it running. Make sure to restart your task runner after switching.</p>
Get Post title in span tag <p>i want to get the wordpress title post to a span tag.</p> <p>i use the code below with the_title() in span tags:</p> <pre><code>&lt;?php echo '&lt;div&gt; &lt;img src="image.jpg"/&gt; &lt;h2&gt;&lt;span&gt;'.the_title().'&lt;/span&gt; &lt;/h2&gt;&lt;/div&gt;'; ?&gt; </code></pre> <p>but the title is show in a tag P, the result is:</p> <pre><code>&lt;p&gt;TITLE_OF_THE_POST_IS_SHOW_HERE &lt;div&gt; &lt;img src="image.jpg"/&gt; &lt;h2&gt;&lt;span&gt;&lt;/span&gt; &lt;/h2&gt;&lt;/div&gt; </code></pre> <p>in result, the span tags is empty, how do insert the title in the span tag?</p>
<p>I would advice changing this </p> <pre><code>&lt;?php echo '&lt;div&gt; &lt;img src="image.jpg"/&gt; &lt;h2&gt;&lt;span&gt;'.the_title().'&lt;/span&gt; &lt;/h2&gt;&lt;/div&gt;'; ?&gt; </code></pre> <p>to something like this </p> <pre><code>&lt;div&gt; &lt;img src="image.jpg"/&gt; &lt;h2&gt; &lt;?php the_title( '&lt;span&gt;', '&lt;/span&gt;' ); ?&gt; &lt;/h2&gt; &lt;/div&gt; </code></pre> <p>the php the_title function see documentation <a href="https://codex.wordpress.org/Function_Reference/the_title" rel="nofollow">Here</a> accepts parameters so you can define the parent tag <code>&lt;span&gt;</code> inside of the wordpress function <code>the_title()</code>.</p> <p>Keep in mind that <code>the_title</code> shows the current post title. If you want to get a title from another post you can use <code>get_the_title( post = 3 )</code> as Mark B mentioned above.</p>
Subcomponents dagger2 implementation <p>i'm trying to apply MVP concepts using dagger2 following <a href="https://github.com/googlesamples/android-architecture/tree/todo-mvp-dagger/" rel="nofollow">this</a> Google repo on Github i have multiple fragments splash screen i have created the first splash screen fragment using MVP</p> <p>and there is it's component class </p> <pre><code>@AScoped @Component(dependencies = DataRepoComponent.class,modules = SplashScreenModule.class) public interface SplashScreenComponent { void inject(SplashScreenActivity splashScreenActivity); } </code></pre> <p>this component class depends on a data provider component called DataRepoComponent </p> <pre><code>@Singleton @Component(modules = {DataRepoModule.class, ApplicationModule.class}) public interface DataRepoComponent { DataRepo getDataRepo(); } </code></pre> <p>and following is the data repo module </p> <pre><code>@Module public class DataRepoModule { @Singleton @Provides OperatorHelper provideSharedPreferncesHelper(Context context){ return new OperatorHelper(context); } @Singleton @Provides SharedPreferences provideSharedPreference(Context context){ return PreferenceManager.getDefaultSharedPreferences(context); } } </code></pre> <p>and everything works just fine till this when i try to add anther splash screen fragment lets call it FirstSplashScreenFragment when i add it's component like this </p> <pre><code>@AScoped @Component(dependencies = DataRepoComponent.class, modules = FirstSplashScreenModule.class) public interface FirstSplashScreenComponent { void inject(SplashScreenActivity splashScreenActivity); } </code></pre> <p>i get the following errors 1 - </p> <blockquote> <p>Error:(5, 49) error: cannot find symbol class DaggerDataRepoComponent</p> <p>cannot be provided without @Proides-annotated method </p> </blockquote>
<p>To be honest, It's really hard to find out your problem because some pieces of your puzzle is missing, but I guess this might help:</p> <p>add this to your DataRepoComponent:</p> <pre><code>@Singleton @Provides DataRepo provideDataRepo(){ return new DataRepo(); } </code></pre> <p>by the way, I think looking at this sample repo could help you get more familiar with dagger:</p> <blockquote> <p><a href="http://github.com/mmirhoseini/fyber_mobile_offers" rel="nofollow">http://github.com/mmirhoseini/fyber_mobile_offers</a></p> </blockquote>
NSLog output no where to be found, Xcode8 <p>I'm trying to use NSLog statements to figure out the execution flow of my app, so I have one in main.m right after autoreleasepool:</p> <pre><code>@autoreleasepool { NSLog(@"app started"); //added breakpoint here, but debugger stopped at next line BOOL runningTests = NSClassFromString(@"XCTestCase") != nil; //stopped here instead of nslog. ... </code></pre> <p>Now, that statement is no where to be found. I've tried searching the console, using 'command + /' to bring up a console for the simulator and searched through the system.log there but still nothing. To see if I was even going through main I added a breakpoint on the log statement and it was being hit, or at least the debugger stopped on the statement after the log (shown in code snippet). Is there something that I don't understand about the app life cycle, for example are the logs being cleared at some point when the application is launched? I also have other NSLog statements in other functions that I expect to be called but they aren't printed either. Why aren't my logs being printed to console?</p> <p>Side notes: </p> <p>My console is indeed active, and the output I'm looking at is 'All Output'.</p> <p>Is there another way I can determine the execution flow of my application? It's a really large app with lots of storyboards and view controllers. By execution flow I mean which views are hit first, what functions are called from those views, how the app determines the next view when the app loads (depending on if the user is logged in) etc...</p> <p>Thanks in advance!</p> <p>Edit: the pre-processor macros I have <a href="https://i.stack.imgur.com/Dz2iu.png" rel="nofollow"><img src="https://i.stack.imgur.com/Dz2iu.png" alt="enter image description here"></a></p>
<p>the NSlog is executed but is hidden among lots of other console debug outputs to solve this issue:</p> <pre><code>In Xcode8: Product -&gt; Scheme -&gt; Edit Scheme -&gt; Run -&gt; Arguments -&gt; Environment Variables </code></pre> <p>add <code>OS_ACTIVITY_MODE</code> and check it, but don't add any value.</p>
NLog - Variable Update (at runtime) <p>Trying to update a variable at runtime with NLog on a vb.net (asp.net) application and doesn't appear to be working.</p> <pre class="lang-xml prettyprint-override"><code>&lt;nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log"&gt; &lt;variable name="DebugInfoLayout" value="[${date:format=MM/dd/yyyy hh\:mm\:ss.fff tt}] [${gdc:item=location}] | ${level} | ${message}" /&gt; &lt;variable name="InfoLayout" value="[${date:format=MM/dd/yyyy hh\:mm\:ss.fff tt}] ${gdc:item=SoftwareName} Version ${gdc:item=SoftwareVersion} - ${message}" /&gt; &lt;variable name="LogLayout" value="[${date:format=MM/dd/yyyy hh\:mm\:ss.fff tt}] ${message}" /&gt; &lt;variable name="logDir" value="C:/Logfiles/" /&gt; &lt;variable name="ArchiveDir" value="C:/Logfiles/Archive" /&gt; &lt;variable name="Line" value="" /&gt; &lt;targets async="false"&gt; &lt;target name="Errors" xsi:type="File" fileName="${logDir}/${var:Line}errors.log" layout="${DebugInfoLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/errors_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" archiveOldFileOnStartup="true" /&gt; &lt;target name="Info" xsi:type="File" fileName="${logDir}/${var:Line}info.log" layout="${InfoLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/info_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30"/&gt; &lt;target name="Debug" xsi:type="File" fileName="${logDir}/${var:Line}debug.log" layout="${DebugInfoLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/debug_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" /&gt; &lt;/targets&gt; &lt;rules&gt; &lt;logger name="Errors" minlevel="Trace" maxlevel="Fatal" writeTo="Errors" /&gt; &lt;logger name="Info" minlevel="Trace" maxlevel="Warn" writeTo="Info" /&gt; &lt;logger name="Debug" minlevel="Trace" maxlevel="Fatal" writeTo="Debug" /&gt; &lt;/rules&gt; &lt;/nlog&gt; </code></pre> <p>The variable I am trying to update is called "Line" and I have the following code:</p> <pre class="lang-vb prettyprint-override"><code>NLog.GlobalDiagnosticsContext.Set("Line", "myLine") </code></pre> <p>However - the log file name is always "debug.log" instead of "myLinedebug.log".</p>
<p>Instead of </p> <pre class="lang-vb prettyprint-override"><code>GlobalDiagnosticsContext.Set("Line", "myLine")` </code></pre> <p>use </p> <pre class="lang-vb prettyprint-override"><code>LogManager.Configuration.Variables("line") = "myLine" </code></pre> <p>Although the GlobalDiagnosticsContext and variables use alike concepts, those are not the same. The <code>GlobalDiagnosticsContext</code> is used for <code>${gdc}</code> renderer. </p> <p>See <a href="https://github.com/nlog/nlog/wiki/Var-Layout-Renderer" rel="nofollow">the docs of <code>${var}</code></a></p>
What is the priceRange parameter for Google Structured Data Reviews <p>I am trying to determine what are the acceptable values for the <code>priceRange</code> parameter. </p> <p><strong>On Google I see $$$ and thats it</strong></p> <p>Can someone explain if I should be using <code>$$$</code> literally or a decimal amount.</p> <p>I cannot seem to find this information on the internet.</p> <p>Any help would be appreciated.</p>
<p>It seems there is no "standard" for this, and probably is born out of the rating system for Restaurants.</p> <p>It seems the convention is:</p> <blockquote> <ul> <li>$ = Inexpensive, usually $10 and under</li> <li>$$ = Moderately expensive, usually between $10-$25 </li> <li>$$$ = Expensive, usually between $25-$45 </li> <li>$$$$ = Very Expensive, usually $50 and up</li> </ul> <p><a href="https://answers.yahoo.com/question/index?qid=20100623180706AAnObPJ" rel="nofollow">Source</a></p> </blockquote> <p>It seems TripAdvisor use the local currency symbol as the indicator:</p> <blockquote> <p>As a reviewer in Korean, you will fill in according to Won ₩, in Greek it will be according to Euros €. Aussies, on the .com.au version of the website get just $ signs, so rather subtle there. The understanding would be AUD$.</p> <p><a href="https://www.tripadvisor.co.uk/ShowTopic-g1-i12104-k7052014-What_should_the_Dollar_igns_mean_in_the_restaurant_reviews-Help_us_make_TripAdvisor_better.html#54767518" rel="nofollow">Source</a></p> </blockquote> <p>But a user has quite rightly pointed out on the official schema.org Github that <code>priceRange</code> is ambiguous.</p> <blockquote> <p>The property schema.org/priceRange is ambiguous because it specifies text for a currency range...</p> <p><a href="https://github.com/schemaorg/schemaorg/issues/1307" rel="nofollow">Source</a></p> </blockquote> <hr> <h2>TL;DR</h2> <blockquote> <p>Use the <code>price</code> property with a range modeled as a <code>PriceSpecification</code> <a href="http://schema.org/price" rel="nofollow">http://schema.org/price</a></p> <p>Source - <a href="https://github.com/schemaorg/schemaorg/issues/1307" rel="nofollow">Github Issue</a></p> </blockquote>
ERROR ITMS-90685: "CFBundleIdentifier Collision. There is more than one bundle" <p>When I am try to submit my app to app store I am getting the error </p> <pre><code>ERROR ITMS-90685: "CFBundleIdentifier Collision. There is more than one bundle with the CFBundleIdentifier value com.companyname.projectName under the application ProjectName.app" </code></pre> <p>Can any one help me, I used Xcode 7.3.1</p>
<p>Have you got an App Extension in your app? I had this error because of Cocoapods embedded frameworks inside App Extension folder.</p> <p>You need to remove build phase <code>'[CP] Embed Pods Frameworks'</code> from Extension target.</p> <p>I wrote such ruby script for that:</p> <pre><code># remove.rb require 'xcodeproj' project_path = "Keyboard.xcodeproj" project = Xcodeproj::Project.open(project_path) project.targets.each do |target| puts target.name if target.name.include?("Extension") phase = target.shell_script_build_phases.find { |bp| bp.name == '[CP] Embed Pods Frameworks' } if !phase.nil? puts "Deleting Embed Pods Frameworks phase from #{target.name}…" target.build_phases.delete(phase) end end end project.save </code></pre> <p>In <strong>CocoaPods 1.1.0</strong> that should be fixed: <a href="https://github.com/CocoaPods/CocoaPods/issues/4203" rel="nofollow">https://github.com/CocoaPods/CocoaPods/issues/4203</a></p>
How can I convert these ASCI codes to Unicode? <p>jslint appears to complain here:</p> <pre><code>Unexpected '\' before 'X'. Priv.SELECTOR = /^(@|#|\.)([\x20-\x7e]+)$/; </code></pre> <p>Perhaps if I used Unicode things would work?</p>
<p>It seems that <code>\uXXXX</code> notation is recognized by jslint as valid. Use</p> <pre><code>Priv.SELECTOR = /^([@#.])([\u0020-\u007e]+)$/; </code></pre> <p>or</p> <pre><code>Priv.SELECTOR = new RegExp("^([@#.])([\\u0020-\\u007e]+)$"); </code></pre> <p>Note that the backslashes must be doubled inside a <code>RegExp</code> constructor.</p>
Is a compound index needed for querying on one field and using another for sorting? <p>In MongoDB, let's say I have the following query:</p> <pre><code>db.things.find({ name: 'some string' }).sort({ age: -1 }) </code></pre> <p>I know that having an index for <code>age</code> will help performance, but do I create the indexes for <code>name</code> and <code>age</code> separately, or as a compound?</p> <pre><code>db.things.createIndex({ name: 1, age: -1 }) </code></pre>
<p>Create a compound index. Mongo DB's documentation goes into more detail here:</p> <p><a href="https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/" rel="nofollow">https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/</a></p> <p>From that page:</p> <blockquote> <p>The following operations can use the index to get the sort order: </p> <p>...</p> <p>db.data.find( { a: 5 } ).sort( { b: 1, c: 1 } ) ----------------------------------- { a: 1 , b: 1, c: 1 }</p> </blockquote>
Checking if another window is closed c++ <p>I'm developing an application that checks open windows on a user computer on Windows (just like the Task Manager)</p> <p>I used <strong>EnumWindows</strong> to list all the active window and it works, now i want to create a function that write a message on the console when a windows has been closed. Is possible or i have to check an <strong>array of WindowHandler</strong> in a separate thread and how do I check their status?</p> <p>Thank for the help.</p>
<p>The easiest solution is to use <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd373889.aspx" rel="nofollow">WinEvents</a>, by registering for <code>EVENT_OBJECT_DESTROY</code> events. The code is fairly straight forward:</p> <pre><code>#include &lt;windows.h&gt; namespace { HWINEVENTHOOK g_WindowDestructionHook = NULL; } inline void CALLBACK WinEventProc( HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime ) { // Filter interesting events only: if ( idObject == OBJID_WINDOW &amp;&amp; idChild == CHILDID_SELF ) { wprintf( L"Window destroyed: HWND = %08X\n", hwnd ); } } inline void RegisterWindowDestructionHook() { g_WindowDestructionHook = ::SetWinEventHook( EVENT_OBJECT_DESTROY, EVENT_OBJECT_DESTROY, NULL, WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT ); } inline void UnregisterHook() { ::UnhookWinEvent( g_WindowDestructionHook ); } </code></pre> <p>Using this is equally simple:</p> <pre><code>::CoInitialize( NULL ); RegisterWindowDestructionHook(); MSG msg = {}; while ( ::GetMessageW( &amp;msg, nullptr, 0, 0 ) &gt; 0 ) { ::TranslateMessage( &amp;msg ); ::DispatchMessageW( &amp;msg ); } UnregisterHook(); ::CoUninitialize(); </code></pre>
Tests: check if tuple is returned <p>I am writing a test which checks response from gen_server. The response itself is either <code>{profile, SomeProfileFromGenServer}</code> or <code>{error, ErrorResponse}</code></p> <p>So I wanted to write a test which does:</p> <pre><code>Profile = mygenserver:get_profile(), ?assertEqual(Profile, {profile, SomeProfile}) </code></pre> <p>As I don't really care about the SomeProfile value. But this says that SomeProfile is unbound :( Is there a way to fix it?</p>
<p>You can use <code>?assertMatch</code>, with the first argument being a pattern:</p> <pre><code>?assertMatch({profile, _}, Profile) </code></pre>
SFINAE does not work as expected <p>I am reading <a href="http://baptiste-wicht.com/posts/2015/03/named-optional-template-parameters-compile-time.html" rel="nofollow">this article</a> and find this piece of code using <code>SFINAE</code> very interesting:</p> <pre><code>template&lt;typename D, typename T2, typename... Args&gt; struct get_value_int&lt;D, T2, Args...&gt; { template&lt;typename D2, typename T22, typename Enable = void&gt; struct impl : std::integral_constant&lt;int, get_value_int&lt;D, Args...&gt;::value&gt; {}; template&lt;typename D2, typename T22&gt; struct impl &lt;D2, T22, std::enable_if_t&lt;std::is_same&lt;typename D2::type_id, typename T22::type_id&gt;::value&gt;&gt; : std::integral_constant&lt;int, T22::value&gt; {}; static constexpr const int value = impl&lt;D, T2&gt;::value; }; </code></pre> <p>As I understand, if the template class <code>std::enable_if_t</code> could not be instaniated, the first version of <code>impl</code> would be.</p> <p>However, when I try to write a simpler piece of code, which I think pretty much the same as the one above, it gets compile errors. Do I misunderstand something here?</p> <pre><code> template&lt;typename T,typename N = void&gt; class A { }; template &lt;typename T&gt; class A&lt;T, typename enable_if&lt;false&gt;::type&gt; { }; </code></pre>
<p>SFINAE occurs in immediate context, here your condition doesn't depend of <code>T</code> so it is a hard failure, your code should be something like:</p> <pre><code>template &lt;typename T&gt; class A&lt;T, typename enable_if&lt;condition&lt;T&gt;::value&gt;::type&gt; { }; </code></pre>
Fast optimization of "pathological" convex function <p>I have a simple convex problem I am trying to speed up the solution of. I am solving the argmin (<em>theta</em>) of</p> <p><img src="http://latex.codecogs.com/gif.latex?-%5Csum_%7Bt%3D1%7D%5E%7BT%7D%5Clog%281%20&plus;%20%5Cboldsymbol%7B%5Ctheta%27%7D%20%5Cboldsymbol%7Br_t%7D%29" alt="eq"></p> <p>where <em>theta</em> and <em>rt</em> is <em>Nx1</em>.</p> <p>I can solve this easily with <code>cvxpy</code> </p> <pre><code>import numpy as np from scipy.optimize import minimize import cvxpy np.random.seed(123) T = 50 N = 5 R = np.random.uniform(-1, 1, size=(T, N)) cvtheta = cvxpy.Variable(N) fn = -sum([cvxpy.log(1 + cvtheta.T * rt) for rt in R]) prob = cvxpy.Problem(cvxpy.Minimize(fn)) prob.solve() prob.status #'optimal' prob.value # -5.658335088091929 cvtheta.value # matrix([[-0.82105079], # [-0.35475695], # [-0.41984643], # [ 0.66117397], # [ 0.46065358]]) </code></pre> <p>But for a larger <code>R</code> this gets too slow, so I am trying a gradient based method with <code>scipy</code>'s <code>fmin_cg</code>:</p> <p><code>goalfun</code> is a <code>scipy.minimize</code> friendly function that returns the function value and the gradient.</p> <pre><code>def goalfun(theta, *args): R = args[0] N = R.shape[1] common = (1 + np.sum(theta * R, axis=1))**-1 if np.any( common &lt; 0 ): return 1e2, 1e2 * np.ones(N) fun = np.sum(np.log(common)) thetaprime = np.tile(theta, (N, 1)).T np.fill_diagonal(thetaprime, np.ones(N)) grad = np.sum(np.dot(R, thetaprime) * common[:, None], axis=0) return fun, grad </code></pre> <p>Making sure the function and gradients are correct:</p> <pre><code>goalfun(np.squeeze(np.asarray(cvtheta.value)), R) # (-5.6583350819293603, # array([ -9.12423065e-09, -3.36854633e-09, -1.00983679e-08, # -1.49619901e-08, -1.22987872e-08])) </code></pre> <p>But solving this just yields garbage, regardless of <code>method</code>, iterations, etc. (The only things that yields <code>Optimization terminated successfully</code> is if <code>x0</code> is practically equal to the optimal <em>theta</em>)</p> <pre><code>x0 = np.random.rand(R.shape[1]) minimize(fun=goalfun, x0=x0, args=R, jac=True, method='CG') # fun: 3.3690101669818775 # jac: array([-11.07449021, -14.04017873, -13.38560561, -5.60375334, -2.89210078]) # message: 'Desired error not necessarily achieved due to precision loss.' # nfev: 25 # nit: 1 # njev: 13 # status: 2 # success: False # x: array([ 0.00892177, 0.24404118, 0.51627475, 0.21119326, -0.00831957]) </code></pre> <p>I.e. this seemingly innocuous problem that <code>cvxpy</code> handles with ease, turns out to be completely pathological for a non-convex solver. Is this problem really that nasty, or am I missing something? What would be an alternative to speed this up?</p>
<p>I believe the issue is that it is possible for <code>theta</code> to be such that the <code>log</code> argument becomes negative. It seems that you have identified this issue, and have <code>goalfun</code> return the tuple <code>(100,100*ones(N))</code> in this case, apparently, as a heuristic attempt to suggest the solver that this "solution" is not <em>preferable</em>. However, a stronger condition must be imposed, i.e., this "solution" is not <em>feasible</em>. Of course, this can be done by providing appropriate constraints. (Interestingly, <code>cvxpy</code> appears to handle this issue automatically.) </p> <p>Here is a sample run, without bothering with providing derivatives. Note the use of a feasible initial estimate <code>x0</code>.</p> <pre><code>np.random.seed(123) T = 50 N = 5 R = np.random.uniform(-1, 1, size=(T, N)) def goalfun(theta, *args): R = args[0] N = R.shape[1] common = (1 + np.sum(theta * R, axis=1))**-1 return np.sum(np.log(common)) def con_fun(theta, *args): R = args[0] return 1+np.sum(theta * R, axis=1) cons = ({'type': 'ineq', 'fun': lambda x: con_fun(x, R)}) x0 = np.zeros(R.shape[1]) minimize(fun=goalfun, x0=x0, args=R, constraints=cons) </code></pre> <blockquote> <pre><code> fun: -5.658334806882614 jac: array([ 0.0019, -0.0004, -0.0003, 0.0005, -0.0015, 0. ]) message: 'Optimization terminated successfully.' nfev: 92 nit: 12 njev: 12 status: 0 success: True x: array([-0.8209, -0.3547, -0.4198, 0.6612, 0.4605]) </code></pre> </blockquote> <p>Note that when I run this, I get an <code>invalid value encountered in log</code> warning, indicating that at some point in the search a value of <code>theta</code> is checked which barely satisfies the constraints. However, the result is reasonably close to that of <code>cvxpy</code>. It would be interesting to check if the <code>cvxpy</code> solution changes when the constraints are explicitly imposed in the <code>cvxpy.Problem</code> formulation.</p>
working with DOM end events <p>I have a small problem. If I have a form with few inputs[type="text"] and div's around them (plus and minus)... how to increment and dicrement input without creating variables, classes and ids for every tag? someone said I can use arrays but I don't know how to do it... </p> <p>the example is with this type of solution - classes for every tag... </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 child = document.querySelector("#child"); var adult = document.querySelector("#adult"); var rooms = document.querySelector("#rooms"); var plusChild = document.querySelector(".plus_child"); var minusChild = document.querySelector(".minus_child"); var childV = child.value; var adultV = adult.value; var roomsV = rooms.value; plusChild.addEventListener("click", function(){ if(childV&lt;10){ childV++; child.value = "" + childV; } }); minusChild.addEventListener("click", function(){ if(childV&gt;0) { childV--; child.value = "" + childV; } }); </code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.main-form { width: 500px; margin: 0 auto; } .input { display: inline-block; width: 100px; height: 15px; background: none; outline: none; } .plus { display: inline-block; background: #999999; width: 15px; height: 15px; } .minus { display: inline-block; background: #999999; width: 15px; height: 15px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Document&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="" class="main-form"&gt; &lt;div class="input-item"&gt; &lt;span&gt;child&lt;/span&gt; &lt;div class="toggle plus plus_child"&gt;+&lt;/div&gt; &lt;input type="text" class="input" placeholder="0" id="child"&gt; &lt;div class="toggle minus minus_child"&gt;-&lt;/div&gt; &lt;/div&gt; &lt;br&gt; &lt;div class="input-item"&gt; &lt;span&gt;adult&lt;/span&gt; &lt;div class="toggle plus"&gt;+&lt;/div&gt; &lt;input type="text" class="input" placeholder="0" id="adult"&gt; &lt;div class="toggle minus"&gt;-&lt;/div&gt; &lt;/div&gt; &lt;br&gt; &lt;div class="input-item"&gt; &lt;span&gt;rooms&lt;/span&gt; &lt;div class="toggle plus"&gt;+&lt;/div&gt; &lt;input type="text" class="input" placeholder="0" id="rooms"&gt; &lt;div class="toggle minus"&gt;-&lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<p>you can simply use var child= document.getElementById("child"); child.value++; or child.value--;</p>
Cannot figure out REGEX java <p>I am trying to write a REGEX which can get string between two words. Here is the code,</p> <pre><code>Pattern MY_PATTERN = Pattern.compile("/\\x22(.*?)/\\x22"); Matcher m = MY_PATTERN.matcher("sasaa \\x22 kjhkjhk \\x22,sasas"); while (m.find()) { String s = m.group(1); System.out.println("Tocken:"+s); } </code></pre> <p>I am trying to get <strong>kjhkjhk</strong> but matcher does not return anything, please tell me what I am doing wrong.</p>
<blockquote> <p>Pattern.compile("\\\\x22(.*?)\\\\x22");</p> </blockquote> <p>You must escape backslash in Patterns with another backslash. Since backslash must be already escaped with another backslash in any Java string in the first place (like you did in the input string), you must have 4 of them in total.</p>
Create semi transparent uibutton with solid white text <p>I am trying to create button similar to following: <a href="https://i.stack.imgur.com/c66iW.png" rel="nofollow"><img src="https://i.stack.imgur.com/c66iW.png" alt="enter image description here"></a></p> <p>I have tried to give alpha with white text color but I am getting following:</p> <p><a href="https://i.stack.imgur.com/mezJb.png" rel="nofollow"><img src="https://i.stack.imgur.com/mezJb.png" alt="enter image description here"></a></p> <p><strong>Edit:</strong></p> <pre><code>textfield.backgroundColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 0.7) textfield.textColor = .white </code></pre> <p>Above code gives second image. But above image looks ugly. </p> <p>How can I create uitextfield like first image?</p> <p><strong>Edit:</strong><br> Complete Solution: </p> <pre><code>txtLogin.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.1) txtLogin.textColor = .white txtLogin.attributedPlaceholder = NSAttributedString(string:"Username", attributes:[NSForegroundColorAttributeName: UIColor(red: 245, green: 245, blue: 241, alpha: 0.7)]) let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 20)) txtLogin.leftView = paddingView txtLogin.leftViewMode = UITextFieldViewMode.always let layer: CALayer! = txtLogin.layer layer.cornerRadius = 4.0 layer.borderWidth = 0 </code></pre> <p>Regards</p>
<p>What you need to do is set the alpha of the button to the point that you want. So for example this would have a semi-transparent background and white text color:</p> <pre><code>button.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.1) button.textColor = .white button.attributedPlaceholder = NSAttributedString(string:"placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.white]) </code></pre>
Extension methods for EntityTypeConfiguration and <datatype>PropertyConfiguration <p>With Entity Framework I might have a configuration that looks like:</p> <pre><code>internal class MyDbContext : DbContext { .... protected override void OnModelCreating(DbModelBuilder mb) { builder.Entity&lt;MyEntity&gt;() .ToTable("MyTable", "MySchema"); builder.Entity&lt;MyEntity&gt;() .Property(e =&gt; e.Name) .IsRequired() .HaxMaxLength(10); builder.Entity&lt;MyEntity&gt;() .Property(e =&gt; e.City) .HaxMaxLength(10); } } </code></pre> <p>I'd like to write an extension method so I could write it like:</p> <pre><code> builder.Entity&lt;MyEntity&gt;() .ToTable("MyTable", "MySchema") .Property(e =&gt; e.Name, n =&gt; n.IsRequired() .HaxMaxLength(10)) .Property(e =&gt; e.City, c =&gt; c.HasxMaxLength(50)); </code></pre> <p>I'm pretty sure I have the signature correct, but I don't know how to get the inner plumbing to work correctly. </p> <pre><code> public static EntityTypeConfiguration&lt;TEntityType&gt; Property&lt;TEntityType&gt;( this EntityTypeConfiguration&lt;TEntityType&gt; instance, Expression&lt;Func&lt;TEntityType, byte[]&gt;&gt; propertyExpression, Func&lt;BinaryPropertyConfiguration, BinaryPropertyConfiguration&gt; propertyConfiguration) where TEntityType : class { Func&lt;TEntityType, byte[]&gt; func = propertyExpression.Compile(); // ?? return instance; } </code></pre>
<p>After a little playing around, I realized I don't need to execute/compile any of it, I just need to chain the parameters together in the correct sequence.</p> <pre><code> public static EntityTypeConfiguration&lt;TEntityType&gt; Property&lt;TEntityType&gt;( this EntityTypeConfiguration&lt;TEntityType&gt; instance, Expression&lt;Func&lt;TEntityType, byte[]&gt;&gt; propertyExpression, Func&lt;BinaryPropertyConfiguration, BinaryPropertyConfiguration&gt; propertyConfiguration) where TEntityType : class { propertyConfiguration(instance.Property(propertyExpression)); return instance; } </code></pre>
Why does my object move in the wrong direction <p>I have a made a simple program which is meant to move a ball left and right horizontally within a canvas. The user will use the left and right keys to move the ball accordingly by 5 pixels a time. If the x coordinate of the ball is less than 40 or more than 240 then it will do nothing.</p> <pre><code>try: import tkinter as tk except ImportError: import Tkinter as Tk window = tk.Tk() game_area = tk.Canvas(width=270, height=400, bd=0, highlightthickness=0, bg="white") ball = game_area.create_oval(10, 10, 24, 24, fill="red") game_area.move(ball, 120, 4) coords = 120 def move_left(event): global coords if coords &lt; 40: pass else: coords = int(coords)- 5 game_area.move(ball, coords, 4) game_area.update() def move_right(event): global coords if coords &gt; 240: pass else: coords = int(coords)+5 game_area.move(ball, coords, 4) game_area.update() window.bind("&lt;Left&gt;", move_left) window.bind("&lt;Right&gt;", move_right) game_area.pack() window.mainloop() </code></pre> <p>However, pressing either key moves the ball towards the right (more than 5 pixels across) and off the screen despite the <code>if</code> function which is meant to prevent this.</p>
<p>According to the <a href="http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.move-method" rel="nofollow">Tkinter Canvas documentation</a>, the second argument to the <code>move</code> method, <code>dx</code>, is an offset. Try calling it like</p> <pre><code>game_area.move(ball, -5, 4) </code></pre> <p>Then you don't need the following line, either.</p> <pre><code>coords = int(coords)- 5 </code></pre>
How can I update the highscore of a game with a database without reloading the page? <p>I made a JS snake <a href="http://msolonko.net/snake" rel="nofollow">game</a> using HTML5 canvas. If the user loses the game, the score is sent to the database using AJAX. The PHP script compares it to the current value and saves it if it is larger. Now, I am struggling to find a way to update the score inside the game because the page never gets reloaded(and i don't want it to). Here is my PHP script:</p> <pre><code>$query = "SELECT * FROM shighscore"; $result = mysqli_query($link, $query); $score = mysqli_fetch_array($result)[0];//this is the highscore if(array_key_exists("jsscore", $_POST)){//if AJAX posted the var if($_POST["jsscore"] &gt; $score){ $query = "UPDATE shighscore SET score = ".mysqli_real_escape_string($link, $_POST['jsscore']); mysqli_query($link, $query); $score = $_POST["jsscore"]; //score var is updated echo "&lt;p id = 'dbvalue'&gt;".$score."&lt;/p&gt;";//this is echoed with the new score value } } </code></pre> <p>In my JS, I do this:</p> <pre><code>$.ajax({ method: "POST", data: {jsscore : score}//variable with the current score }).done(function(data){ var dbscore = document.getElementById("dbvalue").innerHTML;//gets value of the &lt;p&gt; that was echoed by php alert(dbscore);//it never alerts $("#dbvalue").remove();//remove the unneeded &lt;p&gt; tag if(dbscore == score){ $("#worldscore").html("World High &lt;br&gt;Score: " + score);//updates html } }); </code></pre> <p>I used other methods like making a function where:</p> <pre><code>var db = Number("&lt;?php echo $score;?&gt;"); </code></pre> <p>I think that the line of code is only updated when the page first opens. Since I do not reload the page, the new value of score never goes to the JS variable. What can I do? The error in the console is "cannot read property of innerHTML if null". Why is the paragraph with the id of 'dbvalue' null if it is echoes right before the js accesses it?</p> <p>Can I do all this in the same file("index.php") or do I have to make another one as shown <a href="http://stackoverflow.com/questions/10341434/get-variable-from-php-file-using-jquery-ajax">here</a>?</p>
<p>I think to specify the url in the $.ajax call</p> <pre><code>$.ajax({ url: "test.html", cache: false, success: function(html){ $("#results").append(html); } </code></pre> <p>});</p> <p>Take a look at this link:</p> <p><a href="http://stackoverflow.com/questions/9436534/ajax-tutorial-for-post-and-get">AJAX url sample</a></p>
Bootstrap col-md-4 to col-sm-6 <p>I have seen this question: <a href="http://stackoverflow.com/questions/29926617/boostrap-3-col-md-4-to-col-sm-6-or-grid-of-3x2-to-2x3">Boostrap 3 - col-md-4 to col-sm-6, or grid of 3x2 to 2x3</a></p> <p>But it hasn't worked for me.</p> <p>This is my HTML:</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;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"&gt; &lt;div class="services-offered"&gt; &lt;div class="row"&gt; &lt;div class="col-md-4 col-sm-6 col-xs-12 service"&gt; &lt;div class="service-icon"&gt;&lt;span class="fa fa-5x fa-code"&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="service-content"&gt; &lt;h3&gt;Web Development&lt;/h3&gt; &lt;p&gt;My main area of expertise is in web development. I create professional looking websites at affordable prices. All of my websites come with speed, security and search engine optimisation as a standard.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-6 col-xs-12 service"&gt; &lt;div class="service-icon"&gt;&lt;span class="fa fa-5x fa-database"&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="service-content"&gt; &lt;h3&gt;Web App Development&lt;/h3&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-6 col-xs-12 service"&gt; &lt;div class="service-icon"&gt;&lt;span class="fa fa-5x fa-wordpress"&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="service-content"&gt; &lt;h3&gt;WordPress Development&lt;/h3&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-6 col-xs-12 service"&gt; &lt;div class="service-icon"&gt;&lt;span class="fa fa-5x fa-code"&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="service-content"&gt; &lt;h3&gt;Web Development&lt;/h3&gt; &lt;p&gt;My main area of expertise is in web development. I create professional looking websites at affordable prices. All of my websites come with speed, security and search engine optimisation as a standard.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-6 col-xs-12 service"&gt; &lt;div class="service-icon"&gt;&lt;span class="fa fa-5x fa-database"&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="service-content"&gt; &lt;h3&gt;Web App Development&lt;/h3&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-6 col-xs-12 service"&gt; &lt;div class="service-icon"&gt;&lt;span class="fa fa-5x fa-wordpress"&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="service-content"&gt; &lt;h3&gt;WordPress Development&lt;/h3&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>And the output can be seen <a href="http://dev.shivampaw.com/me/" rel="nofollow">on this page</a> underneath the header (services section)</p> <p>As you can see. The classes are <code>col-md-4 col-sm-6 col-xs-12 service</code> however it is position like this:</p> <pre><code>x x x x x x </code></pre> <p>When viewing on a <code>md</code> and above</p> <p>How can this be fixed?</p>
<p>Bootstrap uses floats to organize its column divs. If a column div is a different height it won't be able to float all the way to the left. In your example it looks like the first and second service divs are taller than the 3rd. This is causing the second row to not be able to float left all the way. The fix for this is to set a height on your columns that will be consistent and allow the <code>float:left</code> to float all the way to the left. Something like </p> <pre><code>.service { height:200px; } </code></pre> <p>view this codepen to see how the floats cause this: </p> <p><a href="http://codepen.io/egerrard/pen/PGRQYK" rel="nofollow">http://codepen.io/egerrard/pen/PGRQYK</a></p>
Transform a factor into a matrix of 2 columns in R <p>I have a column of continuous values that goes from 0 to 21600 approximately. </p> <p>I am trying to get this data binned in ranges of 100 and get the frequencies of them, e.g: [0,100) - 35, [100,200) - 57, and so on.</p> <p>What I am doing is this:</p> <p>binned &lt;- cut(x, breaks = c(0, seq(100, 21600, by = 100)))</p> <p>And I get the data in ranges, e.g (7.5e+03,7.6e+03] (1.8e+03,1.9e+03] (1e+03,1.1e+03] (1.1e+03,1.2e+03] (100,200] ... and so on</p> <p>What I want now is to get a matrix of two columns, the first one with the categories (the ranges like [0, 100), [100,200) and the second one with its frequency</p> <p>Can anyone help me? This may be trivial but I am a newbe in R :(</p> <p>Thank you</p>
<p>There are a few ways to do this. But first, what you want is a data.frame (or even better a data.table or a tbl) since you are now dealing with things of different types. The counts are numbers and the ranges are factors.</p> <p>To count easily, use <code>table</code> and from there put it into a data.frame</p> <pre><code>count_bins &lt;- table(binned) catfreq &lt;- data.frame(count_bins) </code></pre> <p>Alternatively, you can replace <code>data.frame</code> with <code>data.table</code> which I prefer for a variety of reasons.</p>
Drop Foreign Key not working when Key_name does not match Column_name <p>When I run:</p> <pre><code>ALTER TABLE `example` DROP FOREIGN KEY `example_configs_user_email_foreign`; </code></pre> <p>It runs without error however, the foreign key is not dropped. When I look at the table indexes it still shows:</p> <pre><code>Key_name: example_configs_user_email_foreign Column_name: user_email Non_unique: 1 </code></pre> <p>My table:</p> <pre><code>CREATE TABLE `example` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `url_slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `email_address` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `example_configs_url_slug_unique` (`url_slug`), KEY `example_configs_user_email_foreign` (`user_email`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; </code></pre> <p>What am I missing? What do I need to do to drop the FK.</p>
<pre><code>create schema test8484a; use test8484a; create table sometable ( id int auto_increment primary key, user_email varchar(255) not null COLLATE utf8_unicode_ci NOT NULL, key `keyname8282`(user_email) )engine=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `example` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `url_slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `user_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `example_configs_url_slug_unique` (`url_slug`), CONSTRAINT `example_configs_user_email_foreign` FOREIGN KEY (`user_email`) REFERENCES sometable(`user_email`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; show create table example; CREATE TABLE `example` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `url_slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `user_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `example_configs_url_slug_unique` (`url_slug`), KEY `example_configs_user_email_foreign` (`user_email`), -- created on your behalf CONSTRAINT `example_configs_user_email_foreign` FOREIGN KEY (`user_email`) REFERENCES `sometable` (`user_email`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- find the FK name above in case some name mangling occurred alter table example drop foreign key example_configs_user_email_foreign; show create table example; CREATE TABLE `example` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `url_slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `user_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `example_configs_url_slug_unique` (`url_slug`), KEY `example_configs_user_email_foreign` (`user_email`) -- residue remains *********** ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci -- cleanup: drop schema test8484a; </code></pre> <p>Use <code>show create table theTableName</code> to inspect the names and the indexes that remain. Note the residue Helper index that remains after the "drop FK".</p> <p>Upon creation of the FK initially, the Helper index in the child table is created. After the drop FK that index is still there.</p> <p>From the manual page entitled <a href="https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html" rel="nofollow">Using FOREIGN KEY Constraints</a>:</p> <blockquote> <p>MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index <strong>is created on the referencing table automatically if it does not exist.</strong> This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.</p> </blockquote>
cropper is not a function on is not a function <p>I'm trying to make use of <a href="https://github.com/fengyuanchen/cropper" rel="nofollow">cropper plugin by fengyuanchen</a> but meeting quite an impossible error</p> <p>I constantly get into <code>Uncaught TypeError: canvas.cropper</code> is not a function even though I already tried everything I searched in your guide and even issues but I couldn't solve it. I try to initialize a cropper in canvas when my button is clicked, like this</p> <pre><code>$('#crop-mode').click(function(e){ var canvas=$('#image-display canvas')[0]; var options={ viewMode:0, dragMode:'crop', aspectRatio: NaN, preview:'.extra-preview', responsive:true, cropBoxMovable: true, cropBoxResizable: true, autoCropArea:0.8 }; canvas.cropper(options); canvas.on({ 'build.cropper': function (e) { console.log(e.type); }, 'built.cropper': function (e) { console.log(e.type); }, 'cropstart.cropper': function (e) { console.log(e.type, e.action); }, 'cropmove.cropper': function (e) { console.log(e.type, e.action); }, 'cropend.cropper': function (e) { console.log(e.type, e.action); }, 'crop.cropper': function (e) { console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY); }, 'zoom.cropper': function (e) { console.log(e.type, e.ratio); } }); }); </code></pre> <p>I'm completely in vain</p> <p>There is also another error: <code>canvas.on is not a function</code></p> <p>I don't know why. I already include jQuery 3.1</p>
<p>From the jQuery docs:</p> <blockquote> <p>Attach an event handler function for one or more events to the selected elements.</p> </blockquote> <p>Now, <code>canvas</code> after <code>var canvas=$('#image-display canvas')[0];</code> is not a selected element. It's the first property of the selected element. <code>$()</code> will return a selected element (if found, obviously), but <code>$()[0]</code> is something completely else. Drop the <code>[0]</code>.</p>
Distinguish between days in Spiral graph <p>so is there any idea for how to do this ,Please ? Thanks in advance.</p> <p>here's my <a href="https://www.dropbox.com/s/ni5aperr0yeertv/All_smry.csv?dl=0" rel="nofollow">data</a> for almost 5weeks</p> <pre><code>head(All.smry) Source: local data frame [6 x 7] Groups: day [1] day hour.group meanTT spiralTime Speed DayName Monthes &lt;date&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dttm&gt; &lt;dbl&gt; &lt;fctr&gt; &lt;fctr&gt; 1 2016-09-04 13.00 7.340000 2016-09-04 13:00:00 29.82016 Sunday September 2 2016-09-04 13.25 6.580000 2016-09-04 13:15:00 33.26444 Sunday September 3 2016-09-04 13.50 5.731111 2016-09-04 13:30:00 38.19155 Sunday September 4 2016-09-04 13.75 5.764444 2016-09-04 13:45:00 37.97070 Sunday September 5 2016-09-04 14.00 5.915556 2016-09-04 14:00:00 37.00075 Sunday September 6 2016-09-04 14.25 6.012222 2016-09-04 14:15:00 36.40584 Sunday September </code></pre> <p>here' thew summary of my data</p> <pre><code> summary(All.smry) day hour.group meanTT spiralTime Min. :2016-09-04 Min. : 0.00 Min. : 3.950 Min. :2016-09-04 13:00:00 1st Qu.:2016-09-14 1st Qu.: 6.00 1st Qu.: 4.533 1st Qu.:2016-09-14 04:37:30 Median :2016-09-23 Median :12.00 Median : 5.552 Median :2016-09-23 17:45:00 Mean :2016-09-23 Mean :11.92 Mean : 5.910 Mean :2016-09-23 17:42:08 3rd Qu.:2016-10-03 3rd Qu.:18.00 3rd Qu.: 6.738 3rd Qu.:2016-10-03 06:52:30 Max. :2016-10-12 Max. :23.75 Max. :26.476 Max. :2016-10-12 20:00:00 Speed DayName Monthes Min. : 8.267 Friday :480 October :1137 1st Qu.:32.486 Monday :566 September:2530 Median :39.423 Saturday :480 Mean :39.546 Sunday :524 3rd Qu.:48.282 Thursday :480 Max. :55.413 Tuesday :576 Wednesday:561 </code></pre> <p>here's the code i use </p> <pre><code>Title &lt;- "SpiralGraph From GoogleTraffic" SubTitle &lt;- paste("From",min(as.Date(All$spiralTime)),"To", max(as.Date(All$spiralTime)),sep = " ") RoadName &lt;- paste("For",name,sep = " ") ggplot(All.smry, aes(x=as.numeric(hour.group), xend=as.numeric(hour.group) + 0.25, y=spiralTime, yend=spiralTime, colour=meanTT)) + geom_segment(size=1.1) + scale_x_continuous(limits=c(0,24), breaks=0:23, minor_breaks=0:24, labels=paste0(rep(c(12,1:11),2), rep(c("AM","PM"),each=12))) + scale_y_datetime(limits=range(All.smry$spiralTime) + c(-3*24*3600,0), breaks=seq(min(All.smry$spiralTime), max(All.smry$spiralTime),"1 day"), date_labels="%b %e") + scale_colour_gradientn(colours=c("#009966","orange","#FF0000","#660000")) + coord_polar() + theme_bw(base_size=10) + labs(x="Hour",y="Day",color="Mean Travel Time") + theme(panel.grid.minor.x=element_line(colour="grey60", size=0.3))+ theme(axis.title.y=element_blank(),axis.text.y=element_blank(),axis.ticks.y=element_blank() ,axis.title.x=element_blank())+ ggtitle(bquote(atop(bold(.(Title)), atop(italic(.(SubTitle)),italic(.(RoadName)) )))) + theme(axis.title.y=element_blank(),axis.text.y=element_blank(),axis.ticks.y=element_blank() ,axis.title.x=element_blank())+theme(text = element_text(size=7)) </code></pre> <p>here's a pic for my graph</p> <p><a href="https://i.stack.imgur.com/GKAdE.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/GKAdE.jpg" alt="enter image description here"></a></p> <p>So, any help please ?.. i wanna have the lines covers the days i wanna show and show them into the legends bar </p>
<p>Try to remove <code>coord_polar()</code> to have a better understanding of what happens.</p> <p>You can either add diagonal lines between your existing colored diagonal bars, a bit like I said in my firt comment. This requires some tweaking but it should work.</p> <p>Another solution is to act directly on the colored bar, using <code>linetype</code> (see <a href="http://sape.inf.usi.ch/quick-reference/ggplot2/linetype" rel="nofollow">http://sape.inf.usi.ch/quick-reference/ggplot2/linetype</a> to known which linetypes are available)</p> <pre><code>All.smry$weekDayNumber &lt;- strftime(All.smry$spiralTime, "%u") All.smry[which(All.smry$weekDayNumber &lt;=5), "momentOfWeek"] &lt;- "weekDay" All.smry[which(All.smry$weekDayNumber &gt; 5), "momentOfWeek"] &lt;- "weekEnd" ggplot(All.smry, aes(x=as.numeric(hour.group), xend=as.numeric(hour.group) + 0.25, y=spiralTime, yend=spiralTime, colour=meanTT)) + geom_segment(aes(linetype = momentOfWeek), size=1.1) + scale_linetype_manual(name = "Moment of week", values = c("solid","dashed"), labels = c("Week day", "Week-end"), breaks = c("weekDay", "weekEnd")) + ... </code></pre>
Restrict Special Characters in HTML & AngularJs <pre><code> ` ~ ! @ # $ % ^ &amp; * ( ) _ + = { } | [ ] \ : ' ; " &lt; &gt; ? , . / </code></pre> <p>I want to restrict the above mentioned special characters and numbers in the input text field. I used the</p> <pre><code>ng-pattern="/^[a-zA-Z ]*$/" </code></pre> <p>to restrict the special characters. This pattern is blocking all the special characters. I am facing issue when i want to enter name "Pérez Gil" I don't want to restrict other language text . Anyone please help.</p>
<p><strong>Updates:</strong></p> <p>I think $parsers is the best options here. See the updated code and plunker.</p> <p>Controller</p> <pre><code>angular.module('ngPatternExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.regex = /^[^`~!@#$%\^&amp;*()_+={}|[\]\\:';"&lt;&gt;?,./1-9]*$/; }]) .directive('myDirective', function() { function link(scope, elem, attrs, ngModel) { ngModel.$parsers.push(function(viewValue) { var reg = /^[^`~!@#$%\^&amp;*()_+={}|[\]\\:';"&lt;&gt;?,./1-9]*$/; // if view values matches regexp, update model value if (viewValue.match(reg)) { return viewValue; } // keep the model value as it is var transformedValue = ngModel.$modelValue; ngModel.$setViewValue(transformedValue); ngModel.$render(); return transformedValue; }); } return { restrict: 'A', require: 'ngModel', link: link }; }); </code></pre> <p>Template</p> <pre><code>&lt;input type="text" ng-model="model" id="input" name="input" my-directive /&gt; </code></pre> <p>Here's a updated example on Plunker</p> <p><a href="https://plnkr.co/edit/eEOJLi?p=preview" rel="nofollow">https://plnkr.co/edit/eEOJLi?p=preview</a></p> <p><strong>Old Answers</strong>:</p> <p>Since you already have a list of characters that you want to restrict, you can spell them out in the ng-pattern expression like:</p> <p>Controller</p> <pre><code>angular.module('ngPatternExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.regex = /^[^`~!@#$%\^&amp;*()_+={}|[\]\\:';"&lt;&gt;?,./1-9]*$/; }]); </code></pre> <p>Template</p> <pre><code>&lt;input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /&gt; </code></pre> <p>Here's a working example on Plunker</p> <p><a href="https://plnkr.co/edit/eEOJLi?p=preview" rel="nofollow">https://plnkr.co/edit/eEOJLi?p=preview</a></p>
How to call Java method which returns String from C using JNI? <p>Is there a way to call a java method, which returns a <code>String</code> in C?<br> For <code>Integer</code> it works like that: </p> <pre><code>JNIEXPORT jint JNICALL Java_Client_getAgeC(JNIEnv *env, jobject callingObject, jobject employeeObject) { jclass employeeClass = (*env)-&gt;GetObjectClass(env, employeeObject); jmethodID midGetAge = (*env)-&gt;GetMethodID(env, employeeClass, "getAge", "()I"); int age = (*env)-&gt;CallIntMethod(env, employeeObject, midGetAge); return age; } </code></pre> <p>I've searched for a long time but nothing works for <code>String</code>. Finally, I want to get a <code>char*</code><br> Thanks in advance!</p>
<p>Below is an example of JNI code calling a method returning a string. Hope this helps.</p> <pre><code>int EXT_REF Java_JNITest_CallJava( JNIEnv* i_pjenv, jobject i_jobject ) { jclass jcSystem; jmethodID jmidGetProperty; LPWSTR wszPropName = L"java.version"; jcSystem = i_pjenv-&gt;FindClass("java/lang/System"); if(NULL == jcSystem) { return -1; } jmidGetProperty = i_pjenv-&gt;GetStaticMethodID(jcSystem, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;"); if(NULL == jmidGetProperty) { return -1; } jstring joStringPropName = i_pjenv-&gt;NewString((const jchar*)wszPropName, wcslen(wszPropName)); jstring joStringPropVal = (jstring)i_pjenv-&gt;CallStaticObjectMethod(jcSystem, jmidGetProperty, (jstring)joStringPropName); const jchar* jcVal = i_pjenv-&gt;GetStringChars(joStringPropVal, JNI_FALSE); printf("%ws = %ws\n", wszPropName, jcVal); i_pjenv-&gt;ReleaseStringChars(joStringPropVal, jcVal); return 0; } </code></pre>
How to remove 'selected' attribute from item in ModelChoiceField? <p>ModelChoiceField adds attribute <code>selected</code> in HTML, if object from choices list has FK to parent object.</p> <p>How\where can I remove this 'selected' attribute in order to get just list of choices? Want to mention, that I need to remove just 'selected' attribute, i.e the value itself should not be removed from the list of choices. I need to hook it somehow from python side, not from HTML. I tried to find needed atribute in different places inside <code>form</code>, but no luck.</p> <p>Does anyone know the part of Django code, where there is a check if an object from choices list has FK to parent model?</p>
<p>I don't know would it work or not, but an idea would be clear for you. </p> <p>So, i found source of <code>Select</code> widget that sets your <code>selected</code> property in html. It's <a href="https://docs.djangoproject.com/en/1.10/_modules/django/forms/widgets/#Select" rel="nofollow">here</a>, just search for <code>selected_html</code>.</p> <p>You can try to subclass <code>Select</code> widget:</p> <pre><code>from django.forms.widgets import Select class CustomSelect(Select): def render_option(self, selected_choices, option_value, option_label): if option_value is None: option_value = '' option_value = force_text(option_value) if option_value in selected_choices: selected_html = '' # make it empty string like in else statement or refactor all that method if not self.allow_multiple_selected: # Only allow for a single selection. selected_choices.remove(option_value) else: selected_html = '' return format_html('&lt;option value="{}"{}&gt;{}&lt;/option&gt;', option_value, selected_html, force_text(option_label)) </code></pre> <p>And then in forms</p> <pre><code>class YourForm(forms.Form): your_field = forms.ModelChoiceField(widget=CustomSelect()) ... </code></pre> <p>It's just solution that i came up with, and i know that this is not so elegant, but it seems that there is no simple way to disable that <code>selected</code> thing.</p>
Explain this Code? <p>So I know that this code takes a random 10 number array and puts it in order from lowest to highest. How does it do it though? Can you explain what the loops, the buffers and the I's and J's?</p> <pre><code>import java.util.Arrays; public class Divisible { public static void main(String[] args) { int[] array = new int [10]; //generates 10 Random numbers in the range of 1-20 for (int i = 0; i &lt; array.length; i++ ) { array[i] = (int)(Math.random()*20 + 1); } System.out.println(Arrays.toString(array)); int buffer = 0; for(int i1 = array.length-1; i1 &gt; 0; i1--) { for(int j = 0 ; j &lt; i1 ; j++) { if(array[j] &gt; array[j+1]) { buffer = array[j]; array[j] = array[j+1]; array[j+1] = buffer; } } } System.out.println(Arrays.toString(array)); } } </code></pre>
<p>It's bubble sort. See <a href="https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Bubble_sort" rel="nofollow">https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Bubble_sort</a> for explanation.</p>
Inject a p namespace attribute using spring annotations <p>I have a bean defined similar to below in my spring.xml. I am converting all my beans into annotation based. How can I inject the attributes in the below listed bean?</p> <pre><code>&lt;bean id = "dataPropDao" class = "com.service.ref.DataPropDaoImpl" p:dataSource-ref = "data.dataSource" p:sql = "PROFILE_PKG.GetProfileByCode" p:function = "true"/&gt; </code></pre>
<p>"p" namespace is used to set bean properties using setters. Equivalent of your code in Java config would be similar to:</p> <pre><code>@Configuration class MyConfig { @Bean DataPropDaoImpl dataPropDao(DataSource datasource) { DataPropDaoImpl dao = new DataPropDaoImpl(); dao.setDataSource(datasource); dao.setSql("PROFILE_PKG.GetProfileByCode"); dao.setFunction(true); return dao; } } </code></pre>
Product multiple columns by a single column in a dataframe <p>My datas as follows:</p> <pre><code>datas6=structure(list(Exp = c("BA", "CI", "CE", "DE"), Var1 = c(0L, 0L, 0L, 0L), Var2 = c(0L, 0L, 1L, 0L), Var3 = c(0L, 1L, 1L, 0L ), Var4 = c(1L, 1L, 1L, 1L), Freq = c("6", "2", "7", "5")), .Names = c("Exp", "Var1", "Var2", "Var3", "Var4", "Freq"), row.names = c(NA, 4L ), class = "data.frame") </code></pre> <p>That's a basic question and I'm sorry for that, can't find a way to multiply from datas6[2] to datas6[5] by datas6[6] such this pseudo code :</p> <pre><code>datas6[2:5]=as.numeric(datas6[2:5])*as.numeric(datas6[6]) </code></pre> <p>returns error :</p> <pre><code>Error: object (list) can not be converted automatically into a type 'double' </code></pre> <p>Tried this also :</p> <pre><code> new_df &lt;- ddply(datas6, (datas6[2:5]), transform, new_column = as.numeric(datas6[2:5])*as.numeric(datas6[6])) </code></pre> <p>do not works : <code>Error in UseMethod("as.quoted"</code>)</p> <p>Thanks a lot.</p>
<p>We can do this by</p> <pre><code>datas6[2:5] &lt;- datas6[2:5] * as.numeric(datas6[,6]) datas6[2:5] # Var1 Var2 Var3 Var4 #1 0 0 0 6 #2 0 0 2 2 #3 0 7 7 7 #4 0 0 0 5 </code></pre>
Going through a object with a variable <p>I guess I didnt really know how to ask this question for me to find an answer. </p> <p>So I have three variables that are going to make this function do what it has to</p> <pre><code> function gatherDataForGeographic(ele) { var $this = $(ele) var $main_title = $this.find('.options-title'), $option = $this.find('.option'); var arr = [] var reportAreas = reportManager.getReportAreasObject(); $option.each(function () { var $this = $(this) var $checkbox = $this.find('.checkbox'); var type = $this.data('type'), index = $this.data('index'); if ($checkbox.hasClass('checkbox--checked')) { console.log(reportAreas.type) } else { return true; } }) return arr; } //this will return an object that I need to index var reportAreas = reportManager.getReportAreasObject(); //this will get the a key that i need from the object var type = $this.data('type'); //this will give me the index I need to grab var index = $this.data('index'); </code></pre> <p>So what I am trying to do is go through the object based on the type(or key) from the option selected by a user</p> <p>The problem... It is looking for <code>reportArea.type[index]</code> and is not recognizing it as a variable and I keep getting <code>undefined</code> because .type does not exist. </p> <p>Is there a way for it to see that type is a variable and not a key? </p>
<p>You can use dynamic properties in JS using the bracket syntax, not the dot syntax:</p> <pre><code>reportAreas[type] </code></pre> <p>That will resolve to <code>reportAreas['whateverString']</code> and is equivalent to <code>reportAreas.whateverString</code>- <code>reportAreas.type</code> however, is a literal check for <code>type</code> property.</p>
Write a program in C to apply Luhn's algorithm for credit card validation <p>I am completely new to C (and all forms of programing...) and following the CS50 class this year. I'm having a really hard time with writing a simple program that uses Luhn's algorithm to test the validity of credit card numbers. </p> <p>I need my program to prompt a user for an input and re-prompt in case the input doesn't follow a credit card format (ex: negative numbers or letters, etc...) and then apply the algorithm to see if the number is a valid credit card number and if yes, whether it's Visa, MasterCard or AmEx. </p> <p>I know that this question has been answered with different codes on this website, I swear I read everything that I could possibly find (on this site and elsewhere on the net) but I'm having a really hard time understanding the C syntax and I wanted to try to come up with something myself instead of copying bits of codes I don't understand from other answers. If someone can help me out and look at what I've done so far and tell me what I'm doing wrong I would be really grateful. Also, any tips that could help me make sense of the C syntax logic better would be extremely appreciated, again I'm a totally and utter newbie (3 weeks into studying programming on a self-paced basis...) .</p> <p>My program is compiling but when I run it it's acting up in a very weird way: when I enter an input sometimes it will say that it is invalid (even if it's a valid number) and sometimes it will just not return anything after I press enter and won't stop running no matter how many times I press the return key. </p> <p>Here is my code so far:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;cs50.h&gt; #include &lt;math.h&gt; int main(void) { printf("Please give me your credit card number:\n") ; long long card_num ; do { card_num = GetLongLong() ; } while (card_num &lt; 1 || card_num &gt; 9999999999999999) ; // Make a copy of the card number to be used and modified throughout the process. long long temp_num = card_num ; int digit = 0 ; int count = 0 ; int sum_a = 0 ; int sum_b = 0 ; // Isolate every digit from the credit card number using a loop and the variable 'digit'. // Keep track of the amount and position of each digit using variable 'count'. while (card_num &gt;= 0) { digit = card_num % 10 ; count++ ; temp_num = (card_num - digit) / 10 ; break ; // Apply Luhn's algorithm using two different 'for' loops depending on the position of each digit. for (count = 0 ; count % 2 == 0 ; count++) { sum_a = sum_a + ((card_num % 10) * 2) ; while ((card_num % 10) * 2 &gt;= 10) { sum_a = (sum_a % 10) + 1 ; } } for (count = 0 ; count % 2 != 0 ; count++) { sum_b = sum_b + digit ; } return sum_a ; return sum_b ; return count ; } // Checking the validity of the number according to Luhn's algorithm int total_sum = sum_a + sum_b ; if (total_sum % 10 != 0) { printf("This is an invalid number.\n") ; } // If the number entered doesn't have the right amount of digits according // to variable 'count', declare the number as invalid. if (count != 13 || count != 15 || count != 16) { printf("This is an invalid number.\n") ; } // Reset value of variable 'temp_num' and apply calculations that will isolate the first two digits. // Store the results in a variable 'company_id'. temp_num = card_num ; int company_id ; while (temp_num &gt; 100) { temp_num = card_num - (card_num % 10) ; company_id = temp_num / 10 ; } return company_id ; // Print the type of credit card depending on the company ID and amount of digits. if (company_id &gt; 50 &amp;&amp; company_id &lt; 56 &amp;&amp; count == 16) { printf("MASTERCARD\n") ; } else if ((company_id == 4) &amp;&amp; (count == 13 || count == 16)) { printf("VISA\n") ; } else if ((company_id == 34 || company_id == 37) &amp;&amp; (count == 15)) { printf("AMEX\n") ; } else { printf("This is an invalid number.\n") ; } return 0 ; } </code></pre>
<p>Your answer is a out of order pastiche with sections that don't follow logically from the previous.</p> <p>Specific issues:</p> <p>This logic:</p> <pre><code>if (count != 13 || count != 15 || count != 16) </code></pre> <p>invalidates every card, the <strong>or</strong>s (||) should be <strong>and</strong>s (&amp;&amp;) for this to work.</p> <p>This loop makes no sense:</p> <pre><code>while (card_num &gt;= 0) { digit = card_num % 10 ; count++ ; temp_num = (card_num - digit) / 10 ; break ; ... } </code></pre> <p>The <code>break</code> is unconditional so it exits the loop and ignores the next twenty lines.</p> <p>You appear to have spliced in subroutines from elsewhere as you call <code>return</code> five times, only the last of which is valid:</p> <pre><code>return sum_a ; return sum_b ; return count ; return company_id ; return 0 ; </code></pre> <p>In several places you use <code>card_num</code> when you should be using <code>temp_num</code>.</p> <p>You fail to exit the program once you know the card is invalid -- instead you just keep on testing. You fail to acknowledge when a card is valid.</p> <p>You count the number of digits in the card number but wait until after you run other checks before testing if that digit count was valid or not.</p> <p>What follows is my rework of your code to address the above and some style issues:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;cs50.h&gt; #include &lt;math.h&gt; int main(void) { printf("Please give me your credit card number: ") ; long long card_num = 0LL; while (card_num &lt; 1LL || card_num &gt; 9999999999999999LL) { card_num = GetLongLong(); } // Make a copy of the card number to be used and modified throughout the process. long long temp_num = card_num; // Isolate every digit from the credit card number using a loop and the variable 'digit'. // Keep track of the amount and position of each digit using variable 'count'. int count = 0; while (temp_num &gt; 0LL) { temp_num = temp_num / 10LL; count++; } // If the number entered doesn't have the right amount of digits according // to variable 'count', declare the number as invalid. if (count != 13 &amp;&amp; count != 15 &amp;&amp; count != 16) { printf("This is an invalid number (# of digits).\n"); return 1; } // Reset value of variable 'temp_num' and apply calculations that will isolate the first two digits. // Store the results in a variable 'company_id'. temp_num = card_num; while (temp_num &gt; 100LL) { temp_num = temp_num / 10LL; } int company_id = temp_num; // Print the type of credit card depending on the company ID and amount of digits. if (company_id &gt; 50 &amp;&amp; company_id &lt; 56 &amp;&amp; count == 16) { printf("MASTERCARD\n") ; } else if ((company_id == 34 || company_id == 37) &amp;&amp; (count == 15)) { printf("AMEX\n") ; } else if ((company_id / 10 == 4) &amp;&amp; (count == 13 || count == 16 || count == 19)) { printf("VISA\n") ; } else { printf("This card was issued by an unknown company.\n"); } // Apply Luhn's algorithm. int sum = 0; temp_num = card_num; for (int i = 1; i &lt;= count; i++) { int digit = temp_num % 10LL; if (i % 2 == 0) { digit *= 2; if (digit &gt; 9) { digit -= 9; } } sum += digit; temp_num /= 10LL; } // Checking the validity of the number according to Luhn's algorithm if (sum % 10 != 0) { printf("This is an invalid number (Luhn's algorithm).\n"); return 1; } printf("This is a valid number.\n"); return 0; } </code></pre> <p>This is not a finished program -- there's error checking and other details needed. Rather than summing the digits when a doubled card number is greater than 9, I used the simpler approach of subtracting 9.</p>
Getting @section from multiple views in your layout <p>I have the following code in my master.blade layout:</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;div id="wrapper"&gt; @yield('loginpopup') &lt;div id="content-component"&gt; @yield('content') &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This in my view, test-page.blade.php</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>@extends('layouts.master') @section('content') &lt;div id="test-name"&gt;&lt;/div&gt; @endsection</code></pre> </div> </div> </p> <p>This in my view, login-popup.blade.php</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>@extends('layouts.master') @section('loginpopup') &lt;div class="login_popup"&gt;&lt;/div&gt; @endsection</code></pre> </div> </div> </p> <p>When I go to mywebsite.com/test-page, I only see the content from test-page.blade loaded correctly. How can I also load the content of popuplogin from login-popup.blade?</p> <p>I want the login popup to be loaded on every page, without having to create the section in the views for each page.</p> <p>Thanks.</p>
<p>Include login-popup.blade.php in every page. You can do that by:</p> <p><code>@include('login-popup')</code></p>
Why does implicit UNNEST not work as the docs say it should? <p>According to the <a href="https://cloud.google.com/bigquery/sql-reference/query-syntax#unnest" rel="nofollow">BigQuery docs</a>:</p> <blockquote> <p>In implicit unnesting, array_path must resolve to an ARRAY and the UNNEST keyword is optional.</p> <p>Example:</p> <p><code>SELECT * FROM mytable.struct_typed_column.array_typed_field1;</code></p> </blockquote> <p>Yet when I try this on a real appengine log exported via StackDriver:</p> <pre><code>SELECT * FROM log_stream.appengine_googleapis_com_request_log_20160928.protoPayload.line </code></pre> <p>I get the error:</p> <blockquote> <p>Invalid table name: log_stream.appengine_googleapis_com_request_log_20160928:protoPayload.line </p> </blockquote> <p>To clarify what I am trying to accomplish, in case that helps, this query returns rows that I'm trying to UNNEST:</p> <pre><code>SELECT protoPayload.line FROM log_stream.appengine_googleapis_com_request_log_20160928 WHERE ARRAY_LENGTH(protoPayload.line) &gt; 0 LIMIT 10 </code></pre> <p>What am I missing?</p>
<p>I filed an (internal) bug against our documentation to clarify this section based on your feedback so hopefully we can have it fixed soon.</p> <p>This section of the <a href="https://cloud.google.com/bigquery/sql-reference/migrating-from-legacy-sql#removing_repetition_with_flatten" rel="nofollow">migration guide</a> touches on how to do what you want: . It sounds like the query that you are looking for is something like:</p> <pre><code>SELECT line FROM log_stream.appengine_googleapis_com_request_log_20160928 AS t, t.protoPayload.line AS line LIMIT 10; </code></pre> <p>This assumes that <code>line</code> repeats. If the <code>protoPayload</code> is what repeats, you would instead want something like:</p> <pre><code>SELECT protoPayload.line FROM log_stream.appengine_googleapis_com_request_log_20160928 AS t, t.protoPayload AS protoPayload LIMIT 10; </code></pre>
convert coordinates into binary image python <p>I made a GUI in which I can load an image from disk and convert the mouse motion ( drawing the contours ) into coordinates. Now I need to convert the coordinates into a binary image and I don't know how. Here is my code:</p> <pre><code>from Tkinter import * from tkFileDialog import askopenfilename from PIL import Image, ImageTk import numpy as np import cv2 class Browse_image : def __init__ (self,master) : frame = Frame(master) frame.grid(sticky=W+E+N+S) self.browse = Button(frame, text="Browse", command = lambda: browseim(self)) self.browse.grid(row=13, columnspan=1) self.photo = PhotoImage(file="browse.png") self.label = Label(frame, image=self.photo) self.label.grid(row=1,rowspan=10) self.label.bind('&lt;B1-Motion&gt;', self.mouseevent) def mouseevent(self,event): w=self.photo.width() h=self.photo.height() a = np.zeros(shape=(h,w)) #print event.x, event.y a[event.x,event.y]=1 </code></pre> <p>plt.imsave('binary.png', a, cmap=cm.gray)</p> <pre><code>def browseim(self): path = askopenfilename(filetypes=(("png files","*.png"),("jpeg files", "*.jpeg")) ) if path: img = Image.open(path) self.photo = ImageTk.PhotoImage(img) self.label.configure(image = self.photo) #self.label.image = self.photo root= Tk() b= Browse_image(root) root.mainloop() </code></pre> <p>`</p>
<p>Your issue is that you are creating a new empty array at each mouse event with the line <code>a = np.zeros(shape=(h,w))</code> in mouseevent. To fix that you should have <code>a</code> declared in the <code>__init__</code> as an attribute (ie <code>self.a = np.zeros(shape=(h,w))</code>) so that you can acces and update it without overwriting it in your <code>mouseevent</code> function.</p>
Perl: Split CSV at given string and use specific string as file name <p>So I have several large CSV files with several columns and rows (6000 odd rows and +-60 columns each) that I would like to split into seperate CSV files at a given string (number of lines between string differs), where each file is to be named the string that appears in the first row of the first column... for example:</p> <pre><code>Peter B1 C1 D1 A2 B2 C2 D2 A3 B3 C3 D3 END B4 C4 D4 Jack B5 C5 D5 A6 B6 C6 D6 A7 B7 C7 D7 END B8 C8 D8 Billy B9 C9 D9 A10 B10 C10 D10 A11 B11 C11 D11 END B12 C12 D12 </code></pre> <p>so there should be 3 files named Peter, Jack and Billy, with the word END signalling that this is the last row to be written for this file. Peter contains range A1 (contains the word Peter) to D4; Jack A5 to D8 and Billy A9 to D12.</p> <p>I have this so far:</p> <pre><code>use strict; use warnings; ### INPUT my $split_woord = 'END'; #word that signals file to be split print "Input file: "; my $file_name = &lt;STDIN&gt;; my $input_file = "file locataion/$file_name.csv"; ### OPEN open (INPUT, "&gt;", "$input_file") or die "Can't open $file_name: $!\n"; my $name= undef; while (&lt;INPUT&gt;){ my $line = $_; my ($a,$b,$c,$d)=split('\,', $line); until ($a eq $split_word){ #loop until column 1 reads 'END', then restart $name eq $a; #want to indictae first line my $output_file = "file_location/$name.csv"; open (OUTPUT, "&gt;&gt;", "$output_file") or die "Can't create $output_file: $!\n"; print OUTPUT "$a,$b,$c,$d\n"; next; } } exit; </code></pre> <p>I can't seem to get it to loop properly, and am also struggling to use the first column/row to act as the name for the file. Any help will be tremendously appreciated!!! TIA</p>
<p>First of all, your line:</p> <pre><code>open (INPUT, "&gt;", "$input_file") </code></pre> <p>Looks like it's opening a file for <strong>WRITING</strong> -- you wanted to read it, right?</p> <p>If you're really dealing with a true CSV file, you may want to explore <code>Text::CSV</code> instead of splitting just on commas. It comes standard with all recent versions, and it handles the inevitable:</p> <pre><code>ID Quote Date 1 No, I'm fine 1/1/2016 2 Roger Winco 5/1/2016 </code></pre> <p>That said, the real issue at hand...</p> <p>Assuming the names don't repeat, you should be able to open an output filehandle and continue using it until it hits the terminating word:</p> <pre><code>my $OUTPUT; open my $INPUT, '&lt;', "$file_name.csv" or die; while (&lt;$INPUT&gt;) { my ($a) = split /,/, $_, 2; if ($OUTPUT eq undef) { open $OUTPUT, '&gt;', "$a.csv" or die; } print $OUTPUT $_; if ($a eq $split_woord) { close $OUTPUT; $OUTPUT = undef; } } close $INPUT; </code></pre>
How two recursion function in program works? <p>I am learning Recursion and understand single recursion like Factorial . I am facing problem to understand how two recursive function works ? I am trying to understand this code :</p> <pre><code>def countdown(n,m): if n == 0: # this is the base case return # return, instead of making more recursive calls print("before recursion",n) countdown(n - 1,m) # first recursive call print("first recursion",n) countdown(n - 1,m) print("Second recursion",n) # second recursive call countdown(3,4) </code></pre> <p>And the output is :</p> <pre><code>before recursion 3 before recursion 2 before recursion 1 first recursion 1 Second recursion 1 first recursion 2 before recursion 1 first recursion 1 Second recursion 1 Second recursion 2 first recursion 3 before recursion 2 before recursion 1 first recursion 1 Second recursion 1 first recursion 2 before recursion 1 first recursion 1 Second recursion 1 Second recursion 2 Second recursion 3 </code></pre> <p>I tried to understand with visual python :</p> <p><a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&amp;cumulative=false&amp;curInstr=0&amp;heapPrimitives=false&amp;mode=display&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" rel="nofollow">Visualize Python code live</a></p> <p>I am understanding first recursion process but when second recursion start , I am facing problem to understand behaviour of second recursion </p> <p>Let me explain what i am not understanding :</p> <p>Ok so this is situation where first recursion finish after finding this base condition (n==0)</p> <p><a href="https://i.stack.imgur.com/9R6aV.png" rel="nofollow"><img src="https://i.stack.imgur.com/9R6aV.png" alt="First recursion found base condition"></a></p> <p>Now here second recursion start work</p> <p><a href="https://i.stack.imgur.com/U7oHo.png" rel="nofollow"><img src="https://i.stack.imgur.com/U7oHo.png" alt="enter image description here"></a></p> <p>, My confusion is until i have learned "below part of recursion would not execute until recursion found its base condition so first recursion didn't print <code>"first recursion 1"</code> until it found base condition in this program , i understand this point clearly. But now when second recursion start working it print immediately <code>"Second recursion 1"</code>(<code>print("Second recursion",n)</code> ) without completing recursion ?? My main confusion is this.</p> <p>If you are confuse please see step 36 to 43 here <a href="http://pythontutor.com/visualize.html#code=def%20countdown(n,m%29%3A%0A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%20%20%23%20this%20is%20the%20base%20case%0A%20%20%20%20%20%20%20%20return%20%20%23%20return,%20instead%20of%20making%20more%20recursive%20calls%0A%20%20%20%20print(%22before%20recursion%22,n%29%0A%0A%20%20%20%20countdown(n%20-%201,m%29%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20first%20recursive%20call%0A%20%20%20%20print(%22first%20recursion%22,n%29%20%20%20%20%20%20%20%0A%20%20%20%20countdown(n%20-%201,m%29%0A%20%20%20%20print(%22Second%20recursion%22,n%29%20%20%20%20%20%20%20%20%20%20%20%20%23%20second%20recursive%20call%0A%0A%0A%0Acountdown(3,4%29&amp;cumulative=false&amp;curInstr=0&amp;heapPrimitives=false&amp;mode=display&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" rel="nofollow">Visualize Python code live</a></p> <p>If i understand this then i would be able to understand tower of hanoi problem. But i want to understand first how second recursion work in program.</p>
<p>You are confuse because you are visualizing two recursion with single stack , You have to know that Every recursion function store values its own stack , It means if you have two recursion there will be two stack , if you have three recursion there would be three stack. </p> <p>Now back to the question , I have written a post about how multiple Recursion works in single program and have <a href="http://www.cryptroix.com/understanding-multiple-recursion/" rel="nofollow">explained step by step here with two stacks.</a> </p> <p>You have to understand :</p> <ul> <li>There are two types of recursion : <ul> <li>Head Recursion</li> <li>Tail Recursion</li> </ul></li> </ul> <p>In Head recursion recursive call first find its base condition then execute rest of code. </p> <pre><code>def head_recursion(x): if x==0: return else: head_recursion(x-1) print("Head Recursion",x) head_recursion(3) </code></pre> <p>it will print :</p> <pre><code>Head Recursion 1 Head Recursion 2 Head Recursion 3 </code></pre> <p>In tail recursion , Everything execute first after recursion call main function. It means In tail recursion Recursive call is last thing in function.</p> <pre><code>def head_recursion(x): if x==0: return else: print("Head Recursion",x) head_recursion(x-1) head_recursion(3) </code></pre> <p>it will print :</p> <pre><code>Head Recursion 3 Head Recursion 2 Head Recursion 1 </code></pre> <p>In your code both recursion are Head recursion , So if both recursion keep executing until both find base condition and stack returned all values.</p> <p>You have to understand what is different between calling and returning values of recursion.</p> <p>Go through this link and understand whole process how two recursion works in single program.</p> <p><a href="http://www.cryptroix.com/understanding-multiple-recursion/" rel="nofollow">understanding multiple recursion</a></p>
(Python) How to find the index of the maximum value of a list? <p>The instructions for the program: To create an empty list and fill it with 20 random integers between 1-500 inclusive, print the list on a single line, and print the maximum value of that list on a separate line. The max value function cannot be used.</p> <p>But then it asks to print the index of the maximum value in the list. Here's what I have so far:</p> <pre><code>import random print() nums = [] for num in range(20): nums.append(random.randint(1, 500)); sep='' max = nums[0] for i in nums: if i &gt; max: max = i print(nums) print("The maximum value that appears in the list is " + str(max) + ".") </code></pre> <p>So I have the max value problem solved, but I'm having a hard time determining how exactly to find the index of the maximum value from the list.</p> <p>Any help appreciated.</p>
<p>Lists have a <code>.index</code> method. That should fit the bill.</p> <pre><code>&gt;&gt;&gt; ["a","b","c"].index("b") 1 </code></pre>
How to find uses-feature in APK? <p>I know I can use </p> <pre><code>aapt d permissions foo.apk </code></pre> <p>to find out which permissions a certain APK needs. But how can I check which <code>&lt;uses-feature&gt;</code> tags were used?</p>
<p><code>aapt dump badging</code> will list <code>&lt;uses-feature&gt;</code> as part of its output:</p> <pre><code>feature-group: label='' uses-feature: name='android.hardware.camera' uses-feature-not-required: name='android.hardware.camera.autofocus' uses-feature-not-required: name='android.hardware.camera.front' uses-feature-not-required: name='android.hardware.microphone' uses-feature: name='android.hardware.faketouch' uses-implied-feature: name='android.hardware.faketouch' reason='default feature for all apps' </code></pre>
Spawn A Player when player pass y coordnat <p>I'm working on a plugin. I want to spawn a player when a player come a y coordinates(Fall Down). I tried scheluder (some resources says) but i didn't do it how can do it?</p> <p>Thanks For Answers</p>
<p>You can use an event handler for the PlayerMoveEvent, and then check if the Y coordinate is less than your threshold, and if it is, teleport them to spawn with the Entity#teleport(Location) method.</p>
BigQuery standart SQL - how to calculate 2 timestamp2 difference in minutes <p>I'm using BigQuery standart SQL and i need to find the difference between 2 timestamps, in minutes.</p> <p>For example:</p> <p>Timestamp1 = '2016-10-10 09:40:00' | Timestamp2 = '2016-10-10 09:50:00' </p> <p>I want to return the difference:</p> <p>Timestamp2-Timestamp1 = 10</p> <p>I found how to do it with Legacy SQL, but it doesn't help: <a href="https://cloud.google.com/bigquery/query-reference#datediff" rel="nofollow">https://cloud.google.com/bigquery/query-reference#datediff</a></p> <p>Thank you !</p>
<p>check for <a href="https://cloud.google.com/bigquery/sql-reference/functions-and-operators#regexp_contains" rel="nofollow">TIMESTAMP_DIFF</a> function </p> <pre><code>SELECT TIMESTAMP "2016-10-10 09:50:00" as first_timestamp, TIMESTAMP "2016-10-10 09:40:00" as second_timestamp, TIMESTAMP_DIFF(TIMESTAMP "2016-10-10 09:50:00", TIMESTAMP "2016-10-10 09:40:00", MINUTE) AS minutes; </code></pre>
My Mutex is not working <pre><code> private static bool Created; private static System.Threading.Mutex PaintGuard = new System.Threading.Mutex(false, "MonkeysUncleBob", out Created); //Function that is attached to each pages "LayoutUpdated" call. private async void AnyPageLayoutUpdated(object sender, object e) { if (Created) { PaintGuard.WaitOne(); try { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&gt; { LCDDriver.ILI9488.PaintScreen(sender); }); } catch (Exception f) { } finally { PaintGuard.ReleaseMutex(); } } } </code></pre> <p>The problem is that somehow multiple threads can enter into the code still. I have verified this by using the debugger, and I can see multiple threads entering into the try before executing the finally.</p> <p>I must be using it wrong.</p>
<p><code>await</code> is not compatible with <code>Mutex</code>. You can use an async-compatible mutex like <code>SemaphoreSlim</code> or the <a href="https://github.com/StephenCleary/AsyncEx.Coordination" rel="nofollow"><code>AsyncLock</code> that I have as part of my AsyncEx library</a>.</p> <p>However, if you need a <em>named</em> mutex, then you'll have to do something quite different. What that is depends on what exactly you're trying to do.</p> <p><strong>Update due to comments:</strong></p> <p>Since you're on the UI thread, there's no need to call into the dispatcher. You just need a <code>SemaphoreSlim</code> to keep them one-at-a-time:</p> <pre><code>private readonly SemaphoreSlim _mutex = new SemaphoreSlim(1); //Function that is attached to each pages "LayoutUpdated" call. private async void AnyPageLayoutUpdated(object sender, object e) { await _mutex.WaitAsync(); try { LCDDriver.ILI9488.PaintScreen(sender); } finally { _mutex.Release(); } } </code></pre>
Create a Pivot style table in SQL <p>I'm not sure how to get what I'm trying to do across in the title, any help there would be appreciated.</p> <p>Here's the problem:</p> <p>I've got a large data set, currently more than 108k rows with 5 columns. I'm trying to display it in a particular way so that it will look similar to how it looks in the current Pivot table in Excel. I have the data imported into MSSQL here's a sample:</p> <pre><code>State Project ClassOfPlant Description ProjApprovalDate FL 4139904 TR 2016 CO161 OA341 SPECIAL SERVICES BLANKET 2016-10-11 FL 4144128 TR WSSD RWB M6 GPON CARD ADDITION TO SUPPORT GROWTH 2016-10-11 FL 4145813 OP BRND-RBB-FTTP-GFLD-CROSSINGS-FISHHAWK RANCH W PH4B 2016-10-11 FL 4146018 OP LKLDN-TMF-GFLD 56 SFU DONOVAN RD ESTATES DESIGN 2016-10-11 </code></pre> <p>Here is how I would like it to look when I return the results:</p> <pre><code>State ClassOfPlant Project Description ProjApprovalDate FL FL TR FL 4139904 2016 CO161 OA341 SPECIAL SERVICES BLANKET 10/11/2016 FL 4144128 WSSD RWB M6 GPON CARD ADDITION TO SUPPORT GROWTH 10/11/2016 FL OP FL 4145813 BRND-RBB-FTTP-GFLD-CROSSINGS-FISHHAWK RANCH W PH4B 10/11/2016 FL 4146018 LKLDN-TMF-GFLD 56 SFU DONOVAN RD ESTATES DESIGN 10/11/2016 </code></pre> <p>There would be additional formatting, like lines around each column and row and different formatting on the date, but that's not important right now. I just need to find out how to pull the data so it looks right.</p> <p><strong>EDIT</strong></p> <p>I cannot use SSRS, I am putting this on a report website that I created. I have been able to get what I need through PHP, but it takes a long time to load and I'm not able to limit the number of rows to make use of pagination. My hope is that I can use a single query and then use pagination to make several pages and speed up the load of the pages.</p>
<p>SQL CLI tools are not really designed for neat presentation of data. You will probably find that it is more trouble than it is worth to try to do this in SQL. For a quick solution, I would look into using <a href="https://www.r-project.org/" rel="nofollow">R</a> to format the data. </p>
NullPointerException while calling findViewById method from Main Activity in app using ViewPager <p>I tried to write app using ViewPager and I want to add a listener to TextView in my app. Adding listener in Fragment code is simple, but how can I create it in MainActivity without getting NullPointerException ?</p> <p>MainActivity:</p> <pre><code>import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.TabHost; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, TabHost.OnTabChangeListener{ ViewPager viewPager; TabHost tabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initTabHost(); initViewPager(); final TextView textView = (TextView) findViewById(R.id.txt_frag1); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setText("Changed text"); } }); } private void initTabHost() { tabHost = (TabHost) findViewById(R.id.tabHost); tabHost.setup(); String[] tabNames = {"FRAG1","FRAG2"}; for(int i=0; i&lt;tabNames.length;i++){ TabHost.TabSpec tabSpec; tabSpec = tabHost.newTabSpec(tabNames[i]); tabSpec.setIndicator(tabNames[i]); tabSpec.setContent(new FakeContent(getApplicationContext())); tabHost.addTab(tabSpec); } tabHost.setOnTabChangedListener(this); } public class FakeContent implements TabHost.TabContentFactory{ Context context; public FakeContent(Context mcontext){ context=mcontext; } @Override public View createTabContent(String tag) { View fakeView = new View(context); fakeView.setMinimumHeight(0); fakeView.setMinimumWidth(0); return fakeView; } } private void initViewPager() { viewPager = (ViewPager) findViewById(R.id.view_pager); List&lt;Fragment&gt; listFragments = new ArrayList&lt;Fragment&gt;(); listFragments.add(new BlankFragment()); listFragments.add(new BlankFragment2()); MyFragmentAdapter myFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(),listFragments); viewPager.setAdapter(myFragmentAdapter); viewPager.setOnPageChangeListener(this); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int selectedItem) { tabHost.setCurrentTab(selectedItem); } @Override public void onTabChanged(String tabId) { int selectedItem = tabHost.getCurrentTab(); viewPager.setCurrentItem(selectedItem); //TabHost ustawianie na środku HorizontalScrollView hScrollView = (HorizontalScrollView) findViewById(R.id.h_scroll_view); View tabView = tabHost.getCurrentTabView(); int scrollPos = tabView.getLeft() -(hScrollView.getWidth() -tabView.getWidth())/2; hScrollView.smoothScrollTo(scrollPos,0); } } </code></pre> <p>MyFragmentAdapter:</p> <pre><code>public class MyFragmentAdapter extends FragmentPagerAdapter { List&lt;Fragment&gt; listFragments; public MyFragmentAdapter(FragmentManager fm, List&lt;android.support.v4.app.Fragment&gt; listFragments) { super(fm); this.listFragments = listFragments; } @Override public android.support.v4.app.Fragment getItem(int position) { return listFragments.get(position); } @Override public int getCount() { return listFragments.size(); } } </code></pre> <p>activity_main.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_smart_led" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.pietr343.viewpagerr.MainActivity"&gt; &lt;TabHost android:id="@+id/tabHost" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;HorizontalScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/h_scroll_view" android:fillViewport="true" android:scrollbars="none"&gt; &lt;TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content"&gt;&lt;/TabWidget&gt; &lt;/HorizontalScrollView&gt; &lt;FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/view_pager" &gt;&lt;/android.support.v4.view.ViewPager&gt; &lt;/FrameLayout&gt; &lt;/LinearLayout&gt; &lt;/TabHost&gt; &lt;/LinearLayout&gt; </code></pre> <p>Fragments are standard blank fragments with one TextView.</p>
<p>There is no view by the id txt_frag1 in you activity_main layout.Because of this you are getting a NPE.First add a textview with the same in activity_main xml and then access it in java.</p>
Bluebird.resolve(jQuery.ajax) Warning promise rejected with non-error [object Object] <p>Problem: when passing jQuery.ajax to Promise.resolve in Bluebird.js, it throws a warning when the request fails.</p> <p>Is this the correct behavior? For some reason that I couldn't find, Bluebird does not emit this warning when it is included directly in the page. It does emit the warning when it is bundled with Webpack.</p> <p>If this is the correct behavior, what is the correct approach for using jQuery.ajax in Bluebird? And why it does not happen when Bluebird is included directly in the page?</p> <p>UPDATE: After digging a little bit, I find that it is simply a difference of the two different builds of Bluebird. The unminified build emits warnings, but the minified build does not. Is there a reason for this?</p> <p>UPDATE 2: What causes the warning is a .finally attached to the promise. Like so:</p> <pre><code>Promise .resolve($.getJSON('/notfound')) .finally(() =&gt; {}) .catch(() =&gt; {}); </code></pre> <p>This causes a warning: <a href="https://jsfiddle.net/gf0jk80s/1/" rel="nofollow">https://jsfiddle.net/gf0jk80s/1/</a></p> <p>This does not cause a warning: <a href="https://jsfiddle.net/gf0jk80s/2/" rel="nofollow">https://jsfiddle.net/gf0jk80s/2/</a></p> <p>As you can see the only difference is the build version used. I would really appreciate if somebody can point me to what is wrong with my code. Ideally, I would like it to not cause warnings for both build versions of Bluebird. In the example, the functions are empty, but in the real code I actually do things in those two handlers.</p>
<blockquote> <p>After digging a little bit, I find that it is simply a difference of the two different builds of Bluebird. The unminified build emits warnings, but the minified build does not. Is there a reason for this?</p> </blockquote> <p>This is done because the unminified version is considered the "debug" version of the library that developers will use when writing and doing initial testing and is easier to step through with a debugger. It is designed to be verbose with warnings to tell a developer when they might have done something wrong.</p> <p>The minified version is like the "production" version of the library that is optimized for space and there's generally no point in having the production version of your app emit warnings to the user's console.</p> <p>In the C/C++ world, this is analogous to a debug version of a DLL and an optimized version of a DLL. The debug version would contain things like <code>ASSERT()</code> to inform a developer if something was not as it should be, the optimized version would not.</p>
Canvas DrawLine Is Invisible <p>I am trying to draw a single line in Android using canvas </p> <p><strong>My class :</strong></p> <pre><code>public class LineDrawer extends View { public LineDrawer(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setStrokeWidth(10); float left = 20; float top = 20; float right = 50; float bottom = 100; canvas.drawLine(left, top, right, bottom, paint); } } </code></pre> <p><strong>My Main Activity :</strong></p> <pre><code>public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LineDrawer lineDrawer = new LineDrawer(this); setContentView(R.layout.activity_Main); } } </code></pre> <p>I cannot find where is the problem , I try all the solutions in the internet but nothing happen , still a blank activity..</p> <p>Should I import some code ?</p>
<p><code>lineDrawer</code> is created but not added anywhere. Just creating a view is not enough, you need to add it to the current displayed views to be taken into account and drawn. You have two options:</p> <ul> <li><p>Add it to your XML layout. You will have to add the following constructor to your custom view.</p> <p><code>public LineDrawer(Context context, AttributeSet attrs) { super(context, attrs); }</code></p></li> <li>Use addView(). Anyway, given how simple is your example, I'll use first (common) method.</li> </ul> <p>As an additional comment, the <code>Paint paint</code> object should be created on view initialization, as is a costly operation. See in the <a href="https://developer.android.com/training/custom-views/custom-drawing.html#createobject" rel="nofollow">original documentation</a> for more information about this.</p>
gitlab runner The requested URL returned error: 403 <p>I'm currently using gitlab.com (not local installation) with their multi-runner for CI integration. This works great on one of my projects but fails for another.</p> <p>I'm using 2012R2 for my host with MSBuild version 14.0.23107.0. I know the error below shows 403 which is an access denied message. My problem is finding the permission setting to change.</p> <p>Error message:</p> <blockquote> <p>Running with gitlab-ci-multi-runner 1.5.3 (fb49c47) Using Shell executor... Running on WIN-E0ORPCQUFHS...</p> <p>Fetching changes...</p> <p>HEAD is now at 6a70d96 update runner file remote: Access denied fatal: unable to access '<a href="https://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@gitlab.com/##REDACTED##/ADInactiveObjectCleanup.git/" rel="nofollow">https://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@gitlab.com/##REDACTED##/ADInactiveObjectCleanup.git/</a>': The requested URL returned error: 403 Checking out 60ea1410 as Production...</p> <p>fatal: reference is not a tree: 60ea1410dd7586f6ed9535d058f07c5bea2ba9c7 ERROR: Build failed: exit status 128</p> </blockquote> <p>gitlab-ci.yml file:</p> <pre><code>variables: Solution: ADInactiveObjectCleanup.sln before_script: #- "echo off" #- 'call "%VS120COMNTOOLS%\vsvars32.bat"' ## output environment variables (usefull for debugging, propably not what you want to do if your ci server is public) #- echo. #- set #- echo. stages: - build #- test #- deploy build: stage: build script: - echo building... - '"%ProgramFiles(x86)%\MSBuild\14.0\Bin\msbuild.exe" "%Solution%" /p:Configuration=Release' except: #- tags </code></pre>
<p>This looks like you need to add add a <code>cd</code> command to print current directory to your before_script. Then go fix permissions to access the parent of that folder. If you installed your gitlab runner to c:\glrunner, it's probably c:\glrunner\builds permission you need to fix.</p> <p>Second problem is you may need to force a fresh git clone by deleting the builds folder.</p> <p>You may want to change the login credentials for the gitlab runner service to a <code>gitlabuser</code> which should be a non-admin account, which may have fewer priveges than the LOCAL SYSTEM account that your gitlab runner is using by default. </p> <p>If you want to know who is logged in, add <code>set</code> to your before_script as well, and you'll get an environment variable dump. From that you can see which account is logged in, and where its USERPROFILE is and other things.</p>
Fixed Header Scrolling Issue <p>I'm creating a fixed nav so when the user scrolls and hits the top of the nav the nav is position:fixed to the top of the screen.</p> <p>It's more a query than anything else because when the variable 'navOffset' is inside the scroll function the header jitters, but when outside the function it works smoothly.</p> <p>The class 'fixed' which gets added kept getting added and removed when inside.</p> <p>Is this because it doesn't have anything time to calculate the offset or something? I couldn't work out why.</p> <p>Cheers</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;&lt;/title&gt; &lt;style media="screen"&gt; html, body { padding: 0; margin: 0; color: #fff; } * { box-sizing: border-box; } .pd { padding: 8rem; } .header { background: orangered; } .section-a { background: steelblue; } .section-b { background: orange; } .section-c { background: purple } .section-d { background: black; } footer { background: red; } nav { background: #333; color: #fff; padding: 3rem 0; text-align: center; } nav ul { display: inline-block; } nav li { display: inline-block; padding-right: 5px; } .fixed { top: 0; left: 0; width: 100%; position: fixed; z-index: 10000; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="header pd"&gt; &lt;h1&gt;Header&lt;/h1&gt; &lt;/div&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;Section A&lt;/li&gt; &lt;li&gt;Section B&lt;/li&gt; &lt;li&gt;Section C&lt;/li&gt; &lt;li&gt;Section D&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;div class="section-a pd"&gt; &lt;h3&gt;Section A&lt;/h3&gt; &lt;/div&gt; &lt;div class="section-b pd"&gt; &lt;h3&gt;Section B&lt;/h3&gt; &lt;/div&gt; &lt;div class="section-c pd"&gt; &lt;h3&gt;Section C&lt;/h3&gt; &lt;/div&gt; &lt;div class="section-d pd"&gt; &lt;h3&gt;Section D&lt;/h3&gt; &lt;/div&gt; &lt;/body&gt; &lt;script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; (function(){ $(document).on("scroll", function(){ var navOffset = $("nav").offset(); var scrollTop = $(document).scrollTop(); if(scrollTop &gt; navOffset.top) { console.log(scrollTop); $("nav").addClass("fixed"); } else { $("nav").removeClass("fixed"); } }); }()); &lt;/script&gt; &lt;/html&gt; </code></pre>
<p>Try this. I changed var navOffset = $("nav").position(); <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>(function(){ $(document).on("scroll", function(){ var navOffset = $("nav").position(); var scrollTop = $(document).scrollTop(); console.log(navOffset) if(scrollTop &gt; navOffset.top) { console.log(scrollTop); $("nav").addClass("fixed"); } else { $("nav").removeClass("fixed"); } }); }());</code></pre> </div> </div> </p>
Using Javascript I want a button to show or hide a div by changing the css <p>Using JavaScript, I want a button to show or hide a div by changing the CSS.</p> <p>HTML:</p> <pre><code>&lt;div id="bottomContainer"&gt; &lt;div id="count" class="count"&gt;...&lt;/div&gt; &lt;div id="visualizations&gt;...&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.bottomContainer { display: block; } </code></pre> <p>I want to use javascript to do the following</p> <p>[button]</p> <p>When button is clicked Javascript changes the CSS for bottomContainer to the following</p> <pre><code>.bottomContainer { display: none; } </code></pre> <p>Is this possible?</p>
<p>Yes, a number of ways. With vanilla JS, you would do something like:</p> <pre><code>document.getElementById('myButtonId').addEventListener('click', function () { document.getElementById('bottomContainer').style.display = "none"; } </code></pre> <p>This is just one of a few ways. You could also make a css rule for a <code>.hide</code> class that has the <code>display: none</code> rule, or do this with jQuery's <code>.hide()</code> method, or any number of framework-based means.</p>
Disable scroll zoom on mapbox <p>I'm trying to disable scroll zoom on a mapbox map, but it is not working. Can anyone let me know what's wrong with my code? The error I get is "Uncaught TypeError: Cannot read property 'disable' of undefined" </p> <pre><code>&lt;script&gt; L.mapbox.accessToken = 'pk.token'; var map = L.mapbox.map('map', 'mapbox.streets', { legendControl: { position: 'topright' } }) .setView([56.3, 11.5], 7); var popup = new L.Popup({ autoPan: false }); // statesData comes from the 'us-states.js' script included above var statesLayer = L.geoJson(statesData, { style: getStyle, onEachFeature: onEachFeature }).addTo(map); function getStyle(feature) { return { weight: 2, opacity: 0.1, color: 'black', fillOpacity: 0.7, fillColor: getColor(feature.properties.density) }; } // get color depending on population density value function getColor(d) { return d &gt; 1000 ? '#512b00' : d &gt; 500 ? '#8E4C01' : d &gt; 200 ? '#cc4c02' : d &gt; 100 ? '#ec7014' : d &gt; 50 ? '#fe9929' : d &gt; 20 ? '#fec44f' : d &gt; 10 ? '#fee391' : d &gt; 5 ? '#fff7bc' : '#ffffe5'; } function onEachFeature(feature, layer) { layer.on({ mousemove: mousemove, mouseout: mouseout, click: zoomToFeature }); } var closeTooltip; function mousemove(e) { var layer = e.target; popup.setLatLng(e.latlng); popup.setContent('&lt;div class="marker-title"&gt;' + layer.feature.properties.name + '&lt;/div&gt;' + layer.feature.properties.density + ' feriehuse'); if (!popup._map) popup.openOn(map); window.clearTimeout(closeTooltip); // highlight feature layer.setStyle({ weight: 3, opacity: 0.3, fillOpacity: 0.9 }); if (!L.Browser.ie &amp;&amp; !L.Browser.opera) { layer.bringToFront(); } } function mouseout(e) { statesLayer.resetStyle(e.target); closeTooltip = window.setTimeout(function() { map.closePopup(); }, 100); } function zoomToFeature(e) { map.fitBounds(e.target.getBounds()); } map.legendControl.addLegend(getLegendHTML()); function getLegendHTML() { var grades = [0, 5, 10, 20, 50, 100, 200, 500, 1000], labels = [], from, to; for (var i = 0; i &lt; grades.length; i++) { from = grades[i]; to = grades[i + 1]; labels.push( '&lt;li&gt;&lt;span class="swatch" style="background:' + getColor(from + 1) + '"&gt;&lt;/span&gt; ' + from + (to ? '&amp;ndash;' + to : '+')) + '&lt;/li&gt;'; } return '&lt;span&gt;Antal feriehuse&lt;/span&gt;&lt;ul&gt;' + labels.join('') + '&lt;/ul&gt;'; } // disable map zoom when using scroll map.scrollZoom.disable(); &lt;/script&gt; </code></pre>
<p>This is a mapbox.js / leaflet map, not mapbox-gl-js, so the difference is in Leaflet the scroll zoom control is called <code>scrollWheelZoom</code> not <code>scrollZoom</code>. If you replace the last line of your script with the following it should work. <a href="http://jsfiddle.net/x5j669zj/" rel="nofollow">http://jsfiddle.net/x5j669zj/</a></p> <pre><code>if (map.scrollWheelZoom) { map.scrollWheelZoom.disable(); } </code></pre>
cannot install python using brew <p>Trying to install python using the following command:</p> <p><code>brew install python</code></p> <p>But unfortunately I am getting the following error:</p> <pre><code>&gt;brew install python ==&gt; Downloading https://homebrew.bintray.com/bottles/python-2.7.12_2.el_capitan. Already downloaded: /Users/maguerra/Library/Caches/Homebrew/python-2.7.12_2.el_capitan.bottle.tar.gz ==&gt; Pouring python-2.7.12_2.el_capitan.bottle.tar.gz ==&gt; Using the sandbox ==&gt; /usr/local/Cellar/python/2.7.12_2/bin/python -s setup.py --no-user-cfg insta Last 15 lines from /Users/maguerra/Library/Logs/Homebrew/python/post_install.01.python: copying setuptools/command/rotate.py -&gt; build/lib/setuptools/command copying setuptools/command/saveopts.py -&gt; build/lib/setuptools/command copying setuptools/command/sdist.py -&gt; build/lib/setuptools/command copying setuptools/command/setopt.py -&gt; build/lib/setuptools/command copying setuptools/command/test.py -&gt; build/lib/setuptools/command copying setuptools/command/upload.py -&gt; build/lib/setuptools/command copying setuptools/command/upload_docs.py -&gt; build/lib/setuptools/command creating build/lib/setuptools/extern copying setuptools/extern/__init__.py -&gt; build/lib/setuptools/extern copying setuptools/script (dev).tmpl -&gt; build/lib/setuptools copying setuptools/script.tmpl -&gt; build/lib/setuptools running install_lib copying build/lib/easy_install.py -&gt; /usr/local/lib/python2.7/site-packages copying build/lib/pkg_resources/__init__.py -&gt; /usr/local/lib/python2.7/site-packages/pkg_resources error: [Errno 13] Permission denied: '/usr/local/lib/python2.7/site- packages/pkg_resources/__init__.py' Warning: The post-install step did not complete successfully You can try again using `brew postinstall python` ==&gt; Caveats Pip and setuptools have been installed. To update them pip install --upgrade pip setuptools You can install Python packages with pip install &lt;package&gt; They will install into the site-package directory /usr/local/lib/python2.7/site-packages See: https://github.com/Homebrew/brew/blob/master/docs/Homebrew-and Python.md .app bundles were installed. Run `brew linkapps python` to symlink these to /Applications. ==&gt; Summary 🍺 /usr/local/Cellar/python/2.7.12_2: 3,150 files, 42.5M </code></pre> <p>Has anyone seen this before, or now how to address this issue in order to complete the python installation process? </p>
<p>The error message says you don’t have permission to write under <code>/usr/local/lib/python2.7/site-packages/pkg_resources</code>.</p> <p>The following steps should work:</p> <ol> <li><p>Remove your broken Python install:</p> <pre><code>brew uninstall python </code></pre></li> <li><p>Ensure you own that directory:</p> <pre><code>sudo chown -R $(whoami):admin /usr/local/lib/python2.7/site-packages </code></pre></li> <li><p>Retry:</p> <pre><code>brew install python </code></pre></li> </ol>
Location for public files in angular2 app <p>I'm using ng serve to serve my angular 2 sample application. I created the sample application using the angular command line interface (CLI). I want to have a few jpg images in my angular application (company logo, etc...). However, I can't seem to find any folder which is public where I can put the logos and still have them visible. I have tried the following:</p> <pre><code>/src/app/shared/logo.jpg /src/app/logo.jpg /src/componentName/logo.jpg /public/logo.jpg </code></pre> <p>I've also tried going to localhost/logo.jpg and localhost/componentName/logo.jpg and localhost/app/shared/logo.jpg and localhost/public/logo.jpg and localhost/app/logo.jpg but all of these produce a 404 not found error.</p> <p>If I go to the standard <a href="http://localhost" rel="nofollow">http://localhost</a> in my browser, I do get the angular 'app works!' message, so my server is working. I omitted the 'http://' from my previous links since stackoverflow only permits 2 links per post.</p> <p>Where in the angular folder structure should I put a logo image that I want to be publicly accessible? Or where do I go to configure what folders are public in an angular 2 app?</p> <p>Thanks.</p>
<p>Using the latest <code>angular-cli</code> all static files go into the <code>assets</code> folder under: <code>/src/assets</code>.</p> <p><a href="https://github.com/angular/angular-cli#project-assets" rel="nofollow">https://github.com/angular/angular-cli#project-assets</a></p> <p>The folder name can be changed in <code>angular-cli.json</code> </p>
Get UserId of Facebook user <p>I have a snippet where I allow a user on my MVC Asp.net Site to publish a POST. It works fine.</p> <p>What I need is when the POST is published and a facebook user clicks on it (There is a url action that takes you to mywebsite if the user clicks on it) . How would I get the userId or something indicating it was clicked by XXXX facebook user?</p> <p>Once a user on my site publishes this post, a friend may click on the link and I want to know what user clicked on it.</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 facebookShare() { FB.ui({ method: 'feed', name: "My gallery - Price: $49.99", link: "https://mygallery.net/Product/Details/99", picture: "http://mygallery.com//Images/Products/image.jpg", description: "In the last 100 years of....", caption: "Product Name: Awesome Pix-X", quote:"Quote: You will always be mine!" }, function (response) { if (response &amp;&amp; !response.error_message) { alert('post_id : ' + response.post_id); } else { alert('Error while posting.'); } }); } </code></pre> </div> </div> </p> <p>So Do I add a query parameter in here to dynamically get facebook user who clicks on it? link: "<a href="https://mygallery.net/Product/Details/99" rel="nofollow">https://mygallery.net/Product/Details/99</a>",</p>
<p>If the user did not authorize your App, there is no way to know. If he authorized your App, you can get his id with <code>FB.getLoginStatus</code>, for example.</p>
Toggle open/close sliding panel <p>I have been working on a project and its almost functioning perfectly however I have one more hurdle.</p> <pre><code>$(document).ready(function() { $("a.shareTab").each(function(index, item) { $(this).on("click", function() { $('.sharepanel' + $(item).data("panel")).animate({ 'width': 'show' }, 1000, function() { $('.sharepanel' + $(item).data("panel") + ' .shareFade').fadeIn(100); }); }); }); $('.shareClose').on('click', function() { $('div.shareFade').fadeOut(100, function() { $('.sharePanel').animate({ 'width': 'hide' }, 1000); }); }); }); </code></pre> <p>When each panel opens it overlaps so if you open the last panel you then cant open the first panel, is it possible to add a toggle to close a panel as one opens, fiddle below.</p> <p><a href="https://jsfiddle.net/kellyhawker/e1szqj20/7/" rel="nofollow">FIDDLE</a></p>
<p>One way would be to hide all of the panels once a panel is clicked and then reopen the desired panel.</p> <pre><code>$(document).ready(function() { $("a.shareTab").each(function(index, item) { $(this).on("click", function() { $('.sharePanel').hide(); $('.sharepanel' + $(item).data("panel")).animate({ 'width': 'show' }, 1000, function() { $('.sharepanel' + $(item).data("panel") + ' .shareFade').fadeIn(100); }); }); }); $('.shareClose').on('click', function() { $('div.shareFade').fadeOut(100, function() { $('.sharePanel').animate({ 'width': 'hide' }, 1000); }); }); }); </code></pre> <p>Here's a <a href="https://jsfiddle.net/406c27ex/1/" rel="nofollow">Fiddle</a></p>
Hide Y-axis labels when data is not displayed in Chart.js <p>I have a Chart.js bar graph displaying two sets of data: Total SQL Queries and Slow SQL Queries. I have Y-axis labels for each respective set of data. The graph can be seen below:</p> <p><a href="https://i.stack.imgur.com/yAKX2.png" rel="nofollow"><img src="https://i.stack.imgur.com/yAKX2.png" alt="SQL Performance graph"></a></p> <p>When I toggle one of the sets of data to not display, the corresponding Y-axis labels still display. When interpreting the graph, this is a bit confusing. As seen below:</p> <p><a href="https://i.stack.imgur.com/FfDQK.png" rel="nofollow"><img src="https://i.stack.imgur.com/FfDQK.png" alt="enter image description here"></a></p> <p><strong>My question:</strong> How can I hide the Y-axis labels of any set of data that is currently not being displayed?</p> <p>This is how I currently have my chart set up:</p> <pre><code>&lt;canvas id="SQLPerformanceChart" minHeight="400"&gt;&lt;/canvas&gt; &lt;script type="text/javascript"&gt; ... var data = { labels: labelArray, datasets: [{ label: "Total SQL Queries", fill: false, borderWidth: 1, borderColor: "green", backgroundColor: "rgba(0, 255, 0, 0.3)", yAxisID: "y-axis-0", data: totalQueriesArray }, { label: "Slow SQL Queries", fill: false, borderWidth: 1, borderColor: "orange", backgroundColor: "rgba(255, 255, 0, 0.3)", yAxisID: "y-axis-1", data: slowQueriesArray, }] }; var options = { animation: false, scales: { yAxes: [{ position: "left", ticks: { beginAtZero: true }, scaleLabel: { display: true, labelString: 'Total SQL Queries' }, id: "y-axis-0" }, { position: "right", ticks: { beginAtZero: true }, scaleLabel: { display: true, labelString: 'Slow SQL Queries' }, id: "y-axis-1" }] }, tooltips: { enabled: true, mode: 'single', callbacks: { title: function(tooltipItem, data) { return data.label; }, beforeLabel: function(tooltipItem, data) { if (tooltipItem.index == 24) { return data.labels[tooltipItem.index] + " - Now"; } else { return data.labels[tooltipItem.index] + " - " + data.labels[(tooltipItem.index) + 1]; } } } } } var ctx = document.getElementById("SQLPerformanceChart"); var SQLPerformanceChart = new Chart(ctx, { type: 'bar', data: data, options: options }); &lt;/script&gt; </code></pre>
<p>You can add a callback function to legends onClick:</p> <pre><code>var options = { animation: false, scales: { yAxes: [{ position: "left", ticks: { beginAtZero: true }, scaleLabel: { display: true, labelString: 'Total SQL Queries' }, id: "y-axis-0" }, { position: "right", ticks: { beginAtZero: true }, scaleLabel: { display: true, labelString: 'Slow SQL Queries' }, id: "y-axis-1" }] }, legend: { onClick: function(event, legendItem) { //get the index of the clicked legend var index = legendItem.datasetIndex; //toggle chosen dataset's visibility SQLPerformanceChart.data.datasets[index].hidden = !SQLPerformanceChart.data.datasets[index].hidden; //toggle the related labels' visibility SQLPerformanceChart.options.scales.yAxes[index].display = !SQLPerformanceChart.options.scales.yAxes[index].display; SQLPerformanceChart.update(); } } } </code></pre>
c lang - different array length by pointer <p>I have problem with my own function for get array length. Code:</p> <pre><code>#include &lt;stdio.h&gt; int main() { int a[] = {5,4,1,2,1}; //len -&gt; 6!! FAIL! WHY? //int a[] = {5,4,1,2}; //len -&gt; 4 OK! int len = 0; int *p = a; while(*p != '\0'){ printf("%d\n", *p); len++; *p++; } printf("len: %d\n", len); return 0; } </code></pre> <p>code above output:</p> <pre><code>5 4 1 2 1 32767 len: 6 </code></pre> <p>but this array int a[] = {5,4,1,2}; - produce len = 4 - ok.</p> <p>why it happens? </p>
<p>It fails because there's no <code>0</code> at the end of your array. It's not added automatically, you need to do it explicitly. As a result, you accessed outside the array, which results in undefined behavior. The fact that one of your tests seemed to work was purely luck, you can't depend on it.</p> <pre><code>int a[] = {5, 4, 1, 2, 1, 0}; </code></pre> <p>The only time that C automatically adds a null terminator is when you use a string literal to initialize a <code>char</code> array, e.g.</p> <pre><code>char c[] = "abcde"; </code></pre>
IEnumerable not not, but returning null reference exception on iteration (C#) <p>I have an IEnumerable that I run a foreach on. It's throwing a null reference exception in certain cases on the foreach line, it says </p> <blockquote> <p>ienumerable threw an exception of type 'System.NullReferenceException</p> </blockquote> <pre><code>if (ienumerable != null) { foreach (var item in ienumerable) { ...... } } </code></pre> <p>I put in a null check before the foreach loop, and the iEnumerable passes the null check, but then when I run the foreach loop on it it throws the null reference exception.</p>
<p>Iterators can do just about anything when iterated, including throw exceptions. So basically, you need to know what the source is. For example, this is a non-null iterator that throw in the same way:</p> <pre><code>var customers = new [] { new Customer { Name = "abc" }, new Customer { }, new Customer { Name = "def" } }; IEnumerable&lt;int&gt; lengths = customers.Select(x =&gt; x.Name.Length); </code></pre> <p>this won't fail until the second time through the loop. So: look at where the iterator came from, and how the iterator is implemented.</p> <p>Purely for fun, here's another that will fail identically:</p> <pre><code>IEnumerable&lt;int&gt; GetLengths() { yield return 3; throw new NullReferenceException(); } </code></pre>
Python or Numpy Approach to MATLAB's "cellfun" <p>Is there a python or numpy approach similar to MATLABs "cellfun"? I want to apply a function to an object which is a MATLAB cell array with ~300k cells of different lengths. </p> <p>A very simple example:</p> <pre><code>&gt;&gt;&gt; xx = [(4,2), (1,2,3)] &gt;&gt;&gt; yy = np.exp(xx) Traceback (most recent call last): File "&lt;pyshell#47&gt;", line 1, in &lt;module&gt; yy = np.exp(xx) AttributeError: 'tuple' object has no attribute 'exp' </code></pre>
<p>The most readable/maintainable approach will probably be to use a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>yy = [ np.exp(xxi) for xxi in xx ] </code></pre> <p>That relies on <code>numpy.exp</code> to implicitly convert each tuple into a <code>numpy.ndarray</code>, which in turn means that you'll get a list of <code>numpy.ndarray</code>s back rather than a list of tuples. That's probably OK for nearly all purposes, but if you absolutely have to have tuples that's also easy enough to arrange:</p> <pre><code>yy = [ tuple(np.exp(xxi)) for xxi in xx ] </code></pre> <p>For some purposes (e.g. to avoid memory bottlenecks) you may prefer to use a <a href="https://docs.python.org/2/reference/expressions.html#generator-expressions" rel="nofollow">generator expression</a> rather than a list comprehension (round brackets instead of square).</p>
IllegalArgumentException when using FXML <p>I've been following along the TornadoFX guide for using FXML (<a href="https://github.com/edvin/tornadofx/wiki/FXML" rel="nofollow">https://github.com/edvin/tornadofx/wiki/FXML</a>), but am getting a error: </p> <pre><code>java.lang.IllegalArgumentException: FXML not found for class ui.view.BoardView </code></pre> <p>Here's my BoardView.kt view:</p> <pre><code>class BoardView : View() { override val root: BorderPane by fxml() val hello: Label by fxid() init { hello.text = "Hello World" } } </code></pre> <p>And here's the FXML file (in the same package, ui.view) *</p> <pre><code>&lt;BorderPane xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1"&gt; &lt;padding&gt; &lt;Insets top="20" right="20" bottom="20" left="20" /&gt; &lt;/padding&gt; &lt;center&gt; &lt;HBox alignment="CENTER" spacing="10"&gt; &lt;Label fx:id="hello"&gt; &lt;font&gt; &lt;Font size="20"/&gt; &lt;/font&gt; &lt;/Label&gt; &lt;/HBox&gt; &lt;/center&gt; &lt;/BorderPane&gt; </code></pre> <p>Here's the full stack trace if it helps:</p> <pre><code>java.lang.IllegalArgumentException: FXML not found for class ui.view.BoardView at tornadofx.UIComponent$fxml$1.&lt;init&gt;(Component.kt:360) at tornadofx.UIComponent.fxml(Component.kt:353) at tornadofx.UIComponent.fxml$default(Component.kt:353) at ui.view.BoardView.&lt;init&gt;(BoardView.kt:12) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:422) at java.lang.Class.newInstance(Class.java:442) at tornadofx.FXKt.find(FX.kt:238) at tornadofx.App.start(App.kt:29) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(LauncherImpl.java:863) at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(PlatformImpl.java:326) at com.sun.javafx.application.PlatformImpl.lambda$null$174(PlatformImpl.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(PlatformImpl.java:294) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191) at java.lang.Thread.run(Thread.java:745) </code></pre> <p>I've tried giving arguments to fxml(), from "BoardView" to "BoardView.fxml" to moving the fxml file into src/main/resources. I couldn't see anything obvious looking at the Component.kt source file.</p> <p>Thanks for any help you can give me.</p>
<p>Short answer first: Put the file in <strong>src/main/resources/ui/view/BoardView.fxml</strong> and don't supply a path parameter to the <strong>fxml()</strong> call.</p> <p>If you are using Maven, it will not copy fxml files in <strong>src/main/java</strong> to the target directory by default, so even if you have the fxml file in the same package it will not be available unless you instruct Maven to copy resources with .fxml extension.</p> <p>I recommend that you put it in <strong>src/main/resources</strong> instead, but remember that it also has to be in the same package there, so the correct path would be <strong>src/main/resources/ui/view/BoardView.fxml</strong>.</p> <p>Alternatively, if you put it directly in <strong>src/main/resources</strong> you must add this path parameter to the fxml delegate:</p> <pre><code>override val root : BorderPane by fxml("/BoardView.fxml") </code></pre> <p>Note the <strong>/</strong> prefix to make it look in the root of the classpath.</p> <p>A good tip would be to compile the project and look in the output folder (<strong>target</strong> by default for Maven projects) and check that the fxml file is in the location you expect.</p>
Thymeleaf Loop Until a Number <p>I make a search and get response from server with Thymeleaf. This holds the number of results:</p> <pre><code>${response.count} </code></pre> <p>I want to make an iteration like that:</p> <pre><code>for (int i = 1; i &lt;= response.count; i++) { if (response.page == i) { &lt;button class="active"&gt;Dummy&lt;/button&gt; } else { &lt;button&gt;Dummy&lt;/button&gt; } } </code></pre> <p>How can I do that? I've tried something like that:</p> <pre><code>${#numbers.sequence(0, response.count)} </code></pre> <p>but didn't work.</p> <p>EDIT: I've tried that but didn't work too:</p> <pre><code>&lt;button th:each="i: ${#numbers.sequence(0, response.count - 1)}" th:class="${i == response.page} ?: active"&gt;Dummy&lt;/button&gt; </code></pre>
<p>This works for me:</p> <pre><code>&lt;th:block th:each="i: ${#numbers.sequence(0, response.count - 1)}"&gt; &lt;button th:if="${response.page == i}" class="active"&gt;Dummy&lt;/button&gt; &lt;button th:unless="${response.page == i}"&gt;Dummy&lt;/button&gt; &lt;/th:block&gt; </code></pre>
Ansible apt module - "unsupported parameter for module: “name" <p>Ansible version 2.1.2.0 (homebrew, macOS - having removed any previous versions)</p> <pre><code>ansible myserver -m apt -a “name=backup2l,state=present” --ask-pass </code></pre> <p>returns this error:</p> <pre><code>myserver | FAILED! =&gt; { "changed": false, "failed": true, "msg": "unsupported parameter for module: “name" } </code></pre> <p>This seems the correct syntax according to <a href="http://docs.ansible.com/ansible/apt_module.html#examples" rel="nofollow">the examples</a>:</p> <pre><code># Install the package "foo" - apt: name=foo state=present </code></pre> <p>I've tried wrapping the values for <code>name</code> and <code>state</code> in single quotes, also using a space between the parameters (it doesn't like that – "ERROR! Missing target hosts").</p> <p>Any ideas?</p>
<p>ansible arguments are seperated by spaces like a command line, not a function call. </p> <p>Try:</p> <pre><code>ansible myserver -m apt -a “name=backup2l state=present” --ask-pass </code></pre>
window.location does not get updated <p>I have a Javascript function as shown below for my HTML form. I am getting the <code>window.location.href</code> as source. Then I am removing two unwanted querystring parmaeters from that. This part works fine (as can be seen from first and second alert screenshots).</p> <p>But setting the <code>location</code> with new value doesn’t work. The third alert (from window.location or even document.location) still includes the unwanted query string parameters. When I observed the POST url, it has the unwanted query string parameter.</p> <p>How to get the window.location updated by removing the unwanted query string parameters (so that the POST will not have the unwanted query string parameters)?</p> <pre><code>function sort_table(strHead) { var source = window.location.href; alert("SOURCE-----"+source) var removed = excludeQueryString (source,"SortColumnAutoRefresh"); removed = excludeQueryString (removed,"SortOrderAutoRefresh"); alert("REMOVED-----"+removed); //location.replace(removed); document.location.replace(removed); alert("LATESTLoc-----"+window.location); //alert("***"+document.location); document.getElementById('hidSort').value=strHead; document.frmCountList.submit(); } function excludeQueryString(url, parameter) { var urlparts= url.split('?'); if (urlparts.length&gt;=2) { var prefix= encodeURIComponent(parameter)+'='; var pars= urlparts[1].split(/[&amp;;]/g); for (var i= pars.length; i-- &gt; 0;) { if (pars[i].lastIndexOf(prefix, 0) !== -1) { pars.splice(i, 1); } } url= urlparts[0] + (pars.length &gt; 0 ? '?' + pars.join('&amp;') : ""); return url; } else { return url; } } </code></pre> <p>Alerts </p> <p><a href="https://i.stack.imgur.com/C0Hbf.png" rel="nofollow"><img src="https://i.stack.imgur.com/C0Hbf.png" alt="enter image description here"></a></p>
<p>This is a function I whipped up right now:</p> <pre><code>function redirectOnBadArgs(badargs) { var i, j, newloc, args, segs, isbad, redirect; redirect = false; newloc = location.href.split("?"); if (newloc.length === 2) { args = newloc[1].split("&amp;"); i = 0; while (i &lt; args.length) { isbad = false; for (j = 0; j &lt; badargs.length; j++) { if (args[i].indexOf(badargs[j] + "=") === 0) { isbad = true; break; } } if (isbad) { args.splice(i, 1); redirect = true; continue; } i++; } newloc[1] = args.join("&amp;"); } newloc = newloc.join("?"); if (redirect) { // DEBUG: alert("redirecting to " + newloc); location.href = newloc; } } </code></pre> <p>Pass it an array of bad arguments, like this:</p> <pre><code>onload = function () { redirectOnBadArgs([ "badarg1", "badarg2" ]); }; </code></pre> <p>Remember, you should redirect on page load, not on submit, or you won't POST any data!</p>
Parse comma separated string into rows <p>I have a User Table, which has a role column. Each user can have multiple roles (or none) and for ease of use, I used a comma separated list to store the roles.</p> <pre><code>USERNAME ROLE ---------------------- bob role1,role2 sally role2 </code></pre> <p>Now, needing to check on specific roles, I've created a view to get the user-role mappings (Similar to a basic XREF table) by using the following subselect:</p> <pre><code>SELECT DISTINCT username, trim(regexp_substr(str, '[^,]+', 1, level)) authority FROM (SELECT username, role str FROM user WHERE role IS NOT NULL ) roles_table CONNECT BY instr(str, ',', 1, level - 1) &gt; 0 </code></pre> <p>to get</p> <pre><code>USERNAME AUTHORITY ---------------------- bob role1 bob role2 sally role2 </code></pre> <p>The problem is that this subquery takes an inordinate amount of time to run. Is there a better way of formatting it to optimize the process? </p> <p>Or would I need to update my entire structure and revert to using a XREF table? If the latter, could I create a XREF view and speed it up somehow by using indices?</p> <p>Thanks!</p>
<p>You can speed it up by using instr and substr (rather than regexp versions), or speed it up A LOT if the input is CLOB and you use the dbms_lob versions of instr and substr. </p> <p>You can create a materialized view with <code>on commit refresh fast</code> (at the cost of making transactions on the base table a bit slower).</p> <p>The best choice is to replace the base table with one that is in first normal form - essentially with the RESULT of your current view. But perhaps that is not an option.</p> <p><strong>EDIT</strong>: I just looked at the query again and see what you are doing.... not good! The way you wrote the hierarchical query, it generates an inordinate number of rows, which you then reduce with DISTINCT. Try this first, perhaps it's all you need:</p> <pre><code>select username, trim(regexp_substr(str, '[^,]+', 1, level)) authority from user connect by instr(str, ',', 1, level - 1) &gt; 0 and prior username = username and prior sys_guid() is not null; </code></pre>
How can I add an if else conditional statement to this function? <p>How can a modify this function so if the user enters less than 2500 cubic ft the price is equal to 0?</p> <pre><code>function updateCombustibleMaterialFireFee(cubicft) { var price = 42; if (cubicft &gt; 5000) { price += (cubicft-5000)/1000*22; } // Change the parameters to the correct fee code, fee schedule, etc. // updateFee(fcode, fsched, fperiod, fqty, finvoice, pDuplicate, pFeeSeq) updateFee("FPERMIT47","FIRE","FINAL",price,"N","N"); logDebug("$" + price); } </code></pre>
<pre><code>function updateCombustibleMaterialFireFee(cubicft) { var price = 42; if (cubicft &lt; 2500) { price = 0; } else if (cubicft &gt; 5000) { price += (cubicft - 5000) / 1000 * 22; } // Change the parameters to the correct fee code, fee schedule, etc. // updateFee(fcode, fsched, fperiod, fqty, finvoice, pDuplicate, pFeeSeq) updateFee("FPERMIT47", "FIRE", "FINAL", price, "N", "N"); logDebug("$" + price); } </code></pre>
Need help converting from ASCII to binary <p>I'm very new to C, so I don't know much about it. Pointers are something I still haven't learned... I need to show a single character in decimal and binary. In decimals its easy but I can't get it to binary in any way... I get the ASCII number and compare it's module with 2 but it shows a really awkward number... what is wrong with the code?(It's in portuguese This is my code: </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;conio.c&gt; //library my professor created to assist his students #include &lt;string.h&gt; #define MAXIMO 8 int main( void ) { char caracter; int aux, resto[MAXIMO], contador, decimal, numero; printf( "Digite um UNICO caracter: " ); caracter = getch(); numero = caracter; decimal = caracter; aux = 0; do { if (numero % 2 == 0) { resto[aux] = 0; } else { resto[aux] = 1; } numero = numero / 2; aux++; } while (numero &gt;= '0'); //system("cls"); printf( "\n\n%d\n\n", aux ); printf( "\nCaracter em Binario: " ); for (contador = aux; contador &gt;= 0; contador--) { printf( "%d", resto[contador] ); } printf( "\nValor decimal do caracter: %d", decimal ); getch(); return 0; } </code></pre> <p>somethings I use like getch(); and return 0; in the end are just so my teacher don't kill me... I don't fully know why it's there but it has to be.</p>
<p>Your code had some errors in the <code>while</code> condition:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #define MAXIMO 8 int main( void ) { char caracter; int aux, resto[MAXIMO], contador, decimal, numero; printf( "Digite um UNICO caracter: " ); caracter = getchar(); // I used getchar instead of getch() numero = caracter; decimal = caracter; aux = 0; do { if (numero % 2 == 0) { resto[aux] = 0; } else { resto[aux] = 1; } numero = numero / 2; aux++; } while (numero &gt; 0); // &gt; than 0 not &gt;= '0' //system("cls"); printf( "\n\n%d\n\n", aux ); printf( "\nCaracter em Binario: " ); for (contador = aux-1; contador &gt;= 0; contador--) //aux-1 { printf( "%d", resto[contador] ); } printf( "\nValor decimal do caracter: %d", decimal ); getchar(); return 0; } </code></pre> <h2>N.B.</h2> <ul> <li>'0' and 0 <strong>are differents</strong></li> <li><code>&gt;</code> (greater) and <code>&gt;=</code> (greater or equal) have <strong>different</strong> meaning</li> </ul>