Affichage des articles dont le libellé est Recent Questions - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Recent Questions - Stack Overflow. Afficher tous les articles

dimanche 12 février 2017

Recent Questions - Stack Overflow

The Problem

Summarised: How do I populate a pre-rendered Django ChoiceField / ModelChoiceField dynamically when using Angular http service to retrieve data from server.

I am unable to populate a Django ModelChoiceField with returned data from a function. I did have this working with angular templating, however the problem is that I will be unable to validate these fields with form.is_valid() before saving to the database as currently I have hardcoded the <select> fields into my html.

The reason why I have a ModelChoiceField is because I have tried filtering the values of the notification_type and appending them to the notification_type field. Even though the form field was populated successfully with values, I was unable to return data and display within my templates as I have a Angular controller expecting the data.

The Code

html

<div>
    <label>Select department</label>
    <div>
        
    </div>
</div>
<div>
    <label>Select notification type</label>
    <div ng-controller="selectNotificationTypeCtlr">
        <select ng-change="getNotfications()" ng-model="selectedNotificationType">
                <option ng-repeat="i in notificationTypes" value="{[{ i.pk }]}">{[{ i.fields.notification_type }]}</option> <!-- fields.notification_type -->
        </select>
    </div>
</div>

app.js

selectNotification.controller('selectDepartmentCtlr', function($scope, $http) {
$scope.getNotificationType = function() {
    var id = $scope.selectedDepartment;
    var notificationTypes = [];
    $http({
        method : "GET",
        url : id
     }).then(function success(response) {
        $scope.notificationTypes = response.data;
     }, function error(response) {
        var errorMessage = "Oops it looks like something went wrong. Please try again.";
     });
   };
});

As you can see I understand the process, its just integrating it with Django forms.

views.py

@login_required(login_url="/login/")
def get_notification_types(request, id):
if request.method == "GET":
    department = Department.objects.get(id=id)
    notification_types = NotificationType.objects.filter(department=department.id)
    return HttpResponse(serializers.serialize('json', notification_types))

forms.py

from django import forms
from notifications.models import Department
from notifications.models import NotificationType


class SelectNotificationForm(forms.Form):
    department = forms.ModelChoiceField(queryset=Department.objects.all(), widget=forms.Select(attrs={'class':'input-element', 'ng-change':'getNotificationType()', 'ng-model':'selectedDepartment'})) #widget=forms.Select(attrs={'class': 'add_class_here'}) # ChoiceField(widget=forms.Select()
    notification_type = forms.ModelChoiceField(queryset=NotificationType.objects.none(), widget=forms.Select(attrs={'class':'input-element'}))
    notification_name = forms.ChoiceField(widget=forms.Select(attrs={'class':'input-element'}))
    notification_contacts = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class':'input-element'}))
    subject = forms.CharField(widget=forms.Select(attrs={'class':'input-element'}))
    body = forms.CharField(widget=forms.Textarea)

How it's displayed

Here's the site functioning with my current code.

Screenshot of site

The helping hand I need

I would like to use Django to validate my form via the is_valid() function when it is saved, but I also need to populate the second ChoiceField with the JSON data object returned to my Angular Controller. The thing that's really fustrating me is that it works fine with Angular, its just the fact that I need to use the which prevents me from looping through and displaying the returned JSON object from my Angular controller.

html template that would allow me to validate the ChoiceField / ModelChoiceFields

html (Ideally I would like to render the form as per the code below, so I can validate the form.)

<div>
    <label>Select department</label>
    <div>
        
    </div>
</div>
<div>
    <label>Select notification type</label>
    <div ng-controller="selectNotificationTypeCtlr">
        
    </div>
</div>

I am aware of a workaround which would subsequently mean me setting required=False on all of the forms ChoiceFields. However, I feel this may cause issues further down the line.

Any advice or help would be much appreciated.

Solution ("ng-options" directive):

        notification_type = forms.ModelChoiceField(queryset=NotificationType.objects.none(), widget=forms.Select(attrs={'class':'input-element', 'ng-focus':'populateNotificationTypes()', 'ng-change':'x()', 'ng-model':'selectedNotificationType', 'ng-options':'x as x.fields.notification_type for x in notificationTypes', 'ng-model':'selectedNotificationType'}))

The only issue I'm having now is that values within options are displayed as value="object:id" where the id is the id of the notification_type.

Let's block ads! (Why?)



Recent Questions - Stack Overflow

jeudi 9 février 2017

Recent Questions - Stack Overflow

most recent 30 from stackoverflow.com 2017-02-09T13:59:30Z http://ift.tt/1jYWW0l http://ift.tt/1jYWW0m http://ift.tt/2kLMEYe 0 onmyway http://ift.tt/2kvW9wb 2017-02-09T13:59:11Z 2017-02-09T13:59:11Z <p><strong>I would like to implement a simple download/export function that will convert and save a rendered svg word cloud as a png in my Angular app.</strong> </p> <p>I am making use of d3 word cloud generator done by Jason Davies and a simplified script by Julien Renaux.</p> <p>I am trying to add a simple export feature, using iweczek's <em>save-svg-as-an-image</em> export function (<a href="http://ift.tt/1O5Adfb" rel="nofollow noreferrer">http://ift.tt/2kvNBW9;), but somewhere I am missing something. It could be the element id...perhaps. </p> <p><strong>This is my Angular WordCloud Directive, including the export function at the bottom (<code>scope.exportToPNG</code>):</strong></p> <pre><code>'use strict'; /** * @ngdoc: function * @name: portalDashboardApp.directive:ogWordCloud * @description: Word Cloud Generator based on the d3 word cloud generator done by Jason Davies and a simplified script by Julien Renaux * Directive of the portalDashboardApp */ angular.module('portalDashboardApp') .directive('ogWordCloud', function () { return { restrict: 'E', replace: true, scope: { words: '=' }, link: function (scope) { var fill = d3.scale.category20b(); var w = window.innerWidth - 238, h = 400; var max, fontSize; var layout = d3.layout.cloud() .timeInterval(Infinity) .size([w, h]) .fontSize(function (d) { return fontSize(+d.value); }) .text(function (d) { return d.key; }) .on("end", draw); var svg = d3.select("#wordCloudVisualisation").append("svg") .attr("width", w) .attr("height", h) .attr("xmlns", 'http://ift.tt/nvqhV5') .attr("xmlns:xlink", 'http://ift.tt/PGV9lw') .attr("version", '1.1') .attr("id", "wordCloudSVG"); var wordCloudVisualisation = svg.append("g").attr("transform", "translate(" + [w &gt;&gt; 1, h &gt;&gt; 1] + ")"); update(); window.onresize = function (event) { update(); }; var tags = []; scope.$watch('words', function () { tags = scope.words; }, true); function draw(data, bounds) { var w = window.innerWidth - 238, h = 400; svg.attr("width", w).attr("height", h); var scale = bounds ? Math.min( w / Math.abs(bounds[1].x - w / 2), w / Math.abs(bounds[0].x - w / 2), h / Math.abs(bounds[1].y - h / 2), h / Math.abs(bounds[0].y - h / 2)) / 2 : 1; var text = wordCloudVisualisation.selectAll("text") .data(data, function (d) { return d.text.toLowerCase(); }); text.transition() .duration(1000) .attr("transform", function (d) { return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; }) .style("font-size", function (d) { return d.size + "px"; }); text.enter().append("text") .attr("text-anchor", "middle") .attr("transform", function (d) { return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; }) .style("font-size", function (d) { return d.size + "px"; }) .style("opacity", 1e-6) .transition() .duration(1000) .style("opacity", 1); text.style("font-family", function (d) { return d.font; }) .style("fill", function (d) { return fill(d.text.toLowerCase()); }) .text(function (d) { return d.text; }); wordCloudVisualisation.transition().attr("transform", "translate(" + [w &gt;&gt; 1, h &gt;&gt; 1] + ")scale(" + scale + ")"); } function update() { layout.font('impact').spiral('archimedean'); fontSize = d3.scale['sqrt']().range([10, 100]); if (scope.words.length) { fontSize.domain([+scope.words[scope.words.length - 1].value || 1, +scope.words[0].value]); } layout.stop().words(scope.words).start(); } ////////////////////////////////////////////////////////////////// scope.exportToPNG = function () { var html = d3.select("svg") //svg .attr("version", 1.1) .attr("xmlns", "http://ift.tt/nvqhV5") .node().parentNode.innerHTML; //console.log(html); var imgsrc = 'data:image/svg+xml;base64,' + btoa(html); var img = '&lt;img src="' + imgsrc + '"&gt;'; d3.select("#svgdataurl").html(img); var canvas = document.querySelector("canvas"), context = canvas.getContext("2d"); var image = new Image; image.src = imgsrc; image.onload = function () { context.drawImage(image, 0, 0); var canvasdata = canvas.toDataURL("image/png"); var pngimg = '&lt;img src="' + canvasdata + '"&gt;'; d3.select("#pngdataurl").html(pngimg); var a = document.createElement("a"); a.download = "sample.png"; a.href = canvasdata; a.click(); }; } }, template: '&lt;div id="wordCloud"&gt;&lt;button class="basicButton" ng-click="exportToPNG()"&gt;Export to .PNG&lt;/button&gt;&lt;div id="wordCloudVisualisation"&gt;&lt;/div&gt;&lt;canvas id="canvas"&gt;&lt;/canvas&gt;&lt;/div&gt;' }; }); </code></pre> <p><strong>This is the export function by itself:</strong></p> <pre><code>d3.select("#save").on("click", function(){ var html = d3.select("svg") .attr("version", 1.1) .attr("xmlns", "http://ift.tt/nvqhV5") .node().parentNode.innerHTML; //console.log(html); var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html); var img = '&lt;img src="'+imgsrc+'"&gt;'; d3.select("#svgdataurl").html(img); var canvas = document.querySelector("canvas"), context = canvas.getContext("2d"); var image = new Image; image.src = imgsrc; image.onload = function() { context.drawImage(image, 0, 0); var canvasdata = canvas.toDataURL("image/png"); var pngimg = '&lt;img src="'+canvasdata+'"&gt;'; d3.select("#pngdataurl").html(pngimg); var a = document.createElement("a"); a.download = "sample.png"; a.href = canvasdata; a.click(); }; }); </code></pre> <p><strong>This is an example of a <code>&lt;div&gt;</code> where the word cloud gets generated to:</strong></p> <pre><code>&lt;og-word-cloud id="SummaryWordCloud" words="wordCloudWords"&gt;&lt;/og-word-cloud&gt; </code></pre> <p>I would appreciate all help!</p> http://ift.tt/2kLEOOa 0 Pavel Avershin http://ift.tt/2kvQwOn 2017-02-09T13:58:57Z 2017-02-09T13:58:57Z <p>I have SQL query and i need to translate it into criteria builder</p> <p>SELECT product_id, SUM(<code>quantity</code>) AS quantity, price, margin, category_id FROM <code>product_sale</code> WHERE time = '2017-02-06 22:39:11' GROUP BY <code>product_id</code></p> <p>I started well, but do not know how to go on</p> <pre><code> CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery&lt;SaleProduct&gt; cq = cb.createQuery(SaleProduct.class); Root&lt;SaleProduct&gt; saleProduct = cq.from(SaleProduct.class); cq.multiselect(saleProduct.get("productId"), cb.sum(saleProduct.&lt;Integer&gt;get("quantity"))); Predicate filterCondition = getFilterCondition(cb, saleProduct, filters); filterCondition = cb.between(saleProduct.&lt;Date&gt;get("time"), dateTo, dateFrom); filterCondition = cb.and(filterCondition, cb.equal(saleProduct.get("storeId"), storeId)); cq.where(filterCondition); cq.groupBy(saleProduct.get("productId")); </code></pre> http://ift.tt/2kLuBkR 0 magichand http://ift.tt/2kvGKMl 2017-02-09T13:58:44Z 2017-02-09T13:58:44Z <p>I have a script that should search all the files in Google drive. I implemented the script into one of Google sites page. The script works only for the files that are in root folder but doesn't work for the files that are in sub-folders. Any help appreciated. Thank you</p> <p>Here is the current script:</p> <pre><code>function doGet(e) { var results = DriveApp.getFolderById('yourGoogleDriveId').searchFiles('fullText contains "' + e.parameter.q + '"'); var output = HtmlService.createHtmlOutput('Results: &lt;br /&gt;&lt;br /&gt;&lt;ul&gt;'); while (results.hasNext()) { var file = results.next(); output.append('&lt;li&gt;&lt;a href="' + file.getUrl() + '"&gt;' + file.getName() + '&lt;/a&gt;&lt;/li&gt;'); } output.append('&lt;/ul&gt;'); return output; } </code></pre> http://ift.tt/2kLLCvv 0 Gio http://ift.tt/2kvEB3i 2017-02-09T13:58:41Z 2017-02-09T13:58:41Z <p>I have a query that builds me a list of users. I want that list of users to exclude users that appear on another query generated list. for instance this first query:</p> <pre><code> SELECT [UUID] ,[UserName] ,[FirstName] ,[LastName] ,[EmployeeNumber] ,[Inactive] ,[EmployeeType] FROM [PCA].[dbo].[Users] b Where Plant ='610' AND FirstName != 'Ei'AND FirstName != 'Recovery' AND LastName != 'Production' AND LastName != 'Lab' AND LastName != 'Kiln' AND FirstName != 'Pulp'AND FirstName != 'Roll'AND FirstName != 'Valdosta' AND FirstName != 'Guard'AND FirstName != 'Paper'AND FirstName != 'Power'AND FirstName != 'Powerhouse' AND FirstName != 'E&amp;I' AND LastName != 'Operator' AND LastName != 'Maintenance' AND FirstName != 'Maintenance' AND LastName != 'Tender' AND FirstName != 'Accounting' AND Inactive = 0 And EmployeeType != 'S' AND EmployeeType != 'C'AND EmployeeType != '' AND FirstName &lt;&gt; LastName AND b.UserName in(Select a.USLanID from [HDData].[dbo].[tblUsers] a) </code></pre> <p>build a list of 145 hourly paid users. now this second list has seven users that have been hurt within the specified time frame describe in the query. i want the first list to have all that users on it that do not appear on the second query list. so those people that got hurt on the second query should not appear on the first list. i should have 138 users on my first list after it is all said and done. how can i do this i tried using a "not in" clause but they still appear. below is my second list which also has a UUID colum name Employee:</p> <pre><code>SELECT * FROM [IncidentReporting].[dbo].[IncidentReports] WHERE Classification IN ('RE','FA') AND IncidentDate between DATEADD(Year, -1, '2017-01-01 00:00:00') AND '2017-02-09 00:00:00' AND ForceClosed = 0 AND IncidentType != 'C' AND ApprovalStatus = 'A' </code></pre> <p>This is what i have tried but returns same amount of rows with the injured users on it as well.</p> <pre><code> DECLARE @Date As DateTime DECLARE @PrevCalenderYear As DateTime SET @PrevCalenderYear = datetimefromparts(year(@Date), 1, 1, 00, 00, 00, 00) SET @Date = GetDate() SELECT [UUID] ,[UserName] ,[FirstName] ,[LastName] ,[EmployeeNumber] ,[Inactive] ,[EmployeeType] FROM [PCA].[dbo].[Users] b Where Plant ='610' AND FirstName != 'Ei'AND FirstName != 'Recovery' AND LastName != 'Production' AND LastName != 'Lab' AND LastName != 'Kiln' AND FirstName != 'Pulp'AND FirstName != 'Roll'AND FirstName != 'Valdosta' AND FirstName != 'Guard'AND FirstName != 'Paper'AND FirstName != 'Power'AND FirstName != 'Powerhouse' AND FirstName != 'E&amp;I' AND LastName != 'Operator' AND LastName != 'Maintenance' AND FirstName != 'Maintenance' AND LastName != 'Tender' AND FirstName != 'Accounting' AND Inactive = 0 And EmployeeType != 'S' AND EmployeeType != 'C'AND EmployeeType != '' AND FirstName &lt;&gt; LastName AND b.UserName in(Select a.USLanID from [HDData].[dbo].[tblUsers] a) AND b.UUID NOT IN (SELECT c.Employee FROM [IncidentReporting].[dbo].[IncidentReports] c WHERE Classification IN ('RE','FA') AND IncidentDate between DATEADD(Year, -1, @PrevCalenderYear) AND @Date AND ForceClosed = 0 AND IncidentType != 'C' AND ApprovalStatus = 'A') </code></pre> http://ift.tt/2kLIGyR 0 mirik http://ift.tt/2kvNpWZ 2017-02-09T13:58:33Z 2017-02-09T13:58:33Z <p>I have an angular2 typescript project with all files imported into the one main module.<br/> I want to embed the <strong>html</strong> templates inside the <strong>ts</strong> files and after that join them all with browserify into one file. The solution I have right now saves intermediary files to disk and after that read them again with browserify:</p> <pre><code>var embedTemplates = require('gulp-angular-embed-templates'); return gulp.src('src/**/*.ts') .pipe(embedTemplates({ sourceType: 'ts' })) .pipe(gulp.dest('./build')) .on('end', function () { var dev = browserify('./build/main.module.ts') .plugin(tsify, { target: "es6", module: "commonjs" }) .transform(babelify, { extensions: ['.tsx', '.ts'] }) .bundle() .pipe(source('app.js')) .pipe(gulp.dest('wwwroot/js')); return dev; }); </code></pre> <p>I'm looking for another solution that uses gulp pipes and doesn't create intermediary files.</p> http://ift.tt/2kLOeJK 0 Vishal Paul http://ift.tt/2kvBicc 2017-02-09T13:58:29Z 2017-02-09T13:58:29Z <p>Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Interface not registered (Exception from HRESULT: 0x80040155).</p> <p>the error occurs in the line excel1.Visible.</p> <p>var excel1 = new Excel.Application(); excel1.Visible = true;</p> <p>not able to execute the above statements. i am using office 2016 and Visual studio 15. what could be the possible solution for such errors. also no conflicting reg keys present in the system for excel. how can to use VS 15 with office excel 16??</p> http://ift.tt/2kLBPVW 0 code http://ift.tt/2kvQ4jh 2017-02-09T13:58:27Z 2017-02-09T13:58:27Z <p>I try to close connection with websocket server. I write HTML client and javascript . </p> <p>I write JavaScript function but it doesn't execute but it show the message "ggg" : my funcation is :</p> <pre><code>socket.onclose = function (event) { alert("ggg"); var code = event.code; var reason = event.reason; var wasClean = event.wasClean; if (wasClean) { textBoxPacket.innerHTML = "Connection closed normally."; } else { textBoxPacket.innerHTML = "Connection closed with message: " + reason + " (Code: " + code + ")"; } } </code></pre> http://ift.tt/2kLPZq7 0 Stéphane de Luca http://ift.tt/2kvWbnN 2017-02-09T13:58:27Z 2017-02-09T13:58:27Z <p>I have a table where each td has an input (like a spreadsheet).</p> <p>My html template the code as follows:</p> <pre><code>&lt;tr *ngFor="let project of projects" (click)="onSelect(project)"&gt; &lt;th class="panel fixed"&gt;&lt;/th&gt; &lt;th class="panel fixed"&gt;&lt;/th&gt; &lt;td *ngFor="let load of projectLoads[project.code]; let d=index" class="cell panel scrolling"&gt; &lt;input class="load" [(ngModel)]="projectLoads[project.code][d]" title="" /&gt; &lt;/td&gt; … </code></pre> <p>When I fill one cell in with a number, for example 1, the number is repeated in the next cell.</p> <p>How it comes?</p> <p>(Note that there is no ngForm in my current code.)</p> http://ift.tt/2kLFbbq 0 Bineesh http://ift.tt/2kvKkGc 2017-02-09T13:54:02Z 2017-02-09T13:58:42Z <p>I am sending data via ajax to post in mysql. In this context how to inlude image file contents ? </p> <p>If i use like : var formData = document.getElementById("img_file");<br> alert(formData.files[0]);</p> <p>, i get error . Note : img_file is the id of the file dom. Any idea about this ? </p> http://ift.tt/2kLMFeK 0 Boon http://ift.tt/2kvNry5 2017-02-09T13:48:13Z 2017-02-09T13:58:48Z <p>Value types such as struct and enum are copied by value. Is it possible to get the reference of variable of value types?</p> <pre><code>struct Test {} let t = Test() let s = t // How to get a reference to t instead of a copy of t? </code></pre> http://ift.tt/2kLB27r -6 Martynas Milinskas http://ift.tt/2kvza4u 2017-02-09T13:40:36Z 2017-02-09T13:59:02Z <p>I have problem with quick sort algorithm. I need to: generator will generate random numbers and after using quicksort you need to sort numbers in array and linked list. </p> <p><a href="http://ift.tt/2kLEejp" rel="nofollow noreferrer"><img src="http://ift.tt/2kLEejp" alt="enter image description here"></a></p> <pre><code> using System; using System.IO; using System.Diagnostics; namespace Quicksort{ class Quicksort1 { static void Main(string[] args) { int seed = (int)DateTime.Now.Ticks &amp; 0x0000FFFF; // Pirmas etapas Test_Array_List(seed); } public static void Quicksort(DataArray elements, int left, int right, IComparable Comparer) { int i = left, j = right; var pivot = elements[(left + right) / 2]; while (i &lt;= j) { while (comparer.Compare(elements[i], pivot) &lt; 0) { i++; } while (comparer.Compare(elements[j], pivot) &gt; 0) { j--; } if (i &lt;= j) { // Swap int tmp = elements[i]; elements[i] = elements[j]; elements[j] = tmp; i++; j--; } } // Recursive calls if (left &lt; j) { Quicksort(elements, left, j, comparer); } if (i &lt; right) { Quicksort(elements, i, right, comparer); } } public static void Quicksort(DataList elements, int left, int right, IComparable Comparer) { int i = left, j = right; int pivot = elements[(left + right) / 2]; while (i &lt;= j) { while (comparer.Compare(elements[i], pivot) &lt; 0) { i++; } while (comparer.Compare(elements[j], pivot) &gt; 0) { j--; } if (i &lt;= j) { // Swap double tmp = elements[i]; elements[i] = elements[j]; elements[j] = tmp; i++; j--; } } // Recursive calls if (left &lt; j) { Quicksort(elements, left, j, comparer); } if (i &lt; right) { Quicksort(elements, i, right, comparer); } } public static void Test_Array_List(int seed) { int n = 12; MyDataArray myarray = new MyDataArray(n, seed); Console.WriteLine("\n ARRAY \n"); myarray.Print(n); Quicksort(myarray); myarray.Print(n); MyDataList mylist = new MyDataList(n, seed); Console.WriteLine("\n LIST \n"); mylist.Print(n); Quicksort(mylist); mylist.Print(n); } } abstract class DataArray { protected int length; public int Length { get { return length; } } public abstract double this[int index] { get; } public abstract void Swap(int j, double a, double b); public void Print(int n) { for (int i = 0; i &lt; n; i++) Console.Write(" {0:F5} ", this[i]); Console.WriteLine(); } } abstract class DataList { protected int length; public int Length { get { return length; } } public abstract double Head(); public abstract double Next(); public abstract void Swap(double a, double b); public void Print(int n) { Console.Write(" {0:F5} ", Head()); for (int i = 1; i &lt; n; i++) Console.Write(" {0:F5} ", Next()); Console.WriteLine(); } } class MyDataArray : DataArray { double[] data; public MyDataArray(int n, int seed) { data = new double[n]; length = n; Random rand = new Random(seed); for (int i = 0; i &lt; length; i++) { data[i] = rand.NextDouble(); } } public override double this[int index] { get { return data[index]; } } public override void Swap(int j, double a, double b) { data[j - 1] = a; data[j] = b; } class MyDataList : DataList { class MyLinkedListNode { public MyLinkedListNode nextNode { get; set; } public double data { get; set; } public MyLinkedListNode(double data) { this.data = data; } } MyLinkedListNode headNode; MyLinkedListNode prevNode; MyLinkedListNode currentNode; public MyDataList(int n, int seed) { length = n; Random rand = new Random(seed); headNode = new MyLinkedListNode(rand.NextDouble()); currentNode = headNode; for (int i = 1; i &lt; length; i++) { prevNode = currentNode; currentNode.nextNode = new MyLinkedListNode(rand.NextDouble()); currentNode = currentNode.nextNode; } currentNode.nextNode = null; } public override double Head() { currentNode = headNode; prevNode = null; return currentNode.data; } public override double Next() { prevNode = currentNode; currentNode = currentNode.nextNode; return currentNode.data; } public override void Swap(double a, double b) { prevNode.data = a; currentNode.data = b; } } </code></pre> http://ift.tt/2kvBp7A 0 Jeff Nyman http://ift.tt/2kLEfUv 2017-02-09T13:39:45Z 2017-02-09T13:59:06Z <p>I have researched this and every thing I've read says that the following should work:</p> <pre><code>require 'spec_helper' require 'rspec/expectations' include RSpec::Matchers RSpec.describe 'Posts' do it 'should return 200 response when getting posts' do result_posts = RestClient.get('http://ift.tt/1n31l1Y') expect(result_posts.code).to eq(200) end end </code></pre> <p>I have that in file (<code>json_spec.rb</code>) in my <code>spec</code> directory. This is using RSpec 3.5.4.</p> <p>The message being received when running this spec is:</p> <pre><code>only the `receive`, `have_received` and `receive_messages` matchers are supported with `expect(...).to`, but you have provided: #&lt;RSpec::Matchers::BuiltIn::Eq:0x007f9b43590f48&gt; </code></pre> <p>One post suggested that I should be using</p> <pre><code>extend RSpec::Matchers </code></pre> <p>rather than trying to "include" them. I did that and the exact same error appears.</p> <p>Yet another post suggested I should no longer be requiring "rspec/expectations" but rather just "rspec". That doesn't work either. (Yet another post said the exact opposite, of course. But at least I covered my bases there.)</p> <p>Another post suggested that the include (or maybe the extend or maybe even both) had to go in an RSpec configure block, as such:</p> <pre><code>RSpec.configure do |config| include RSpec::Matchers end </code></pre> <p>That, however, also does not work.</p> <p>What you see above is literally all that I have in my <code>spec</code> directory. My <code>spec_helper.rb</code> file initially just contained the require statements and the include directive. I moved them to the actual spec file (as shown above) just to see if that was the issue.</p> <p>I'm not using Rails or Cucumber so, to my knowledge, there is no wider context in which I can, or should, be including the matchers.</p> <p>I have to assume I'm missing something fairly fundamental here but none of the RSpec documentation has been much of a roadmap about this particular issue.</p> http://ift.tt/2kLJyUa 0 ZulKaz http://ift.tt/2kvEZyK 2017-02-09T13:38:51Z 2017-02-09T13:58:30Z <p><strong>Context:</strong> My C++ application needs to know on which computer it is running in order to do specific behavior. So my application gets the IP address of the computer and then check that address in a configuration file with an IP list in order to determine the computer's role. All computers have a fixed IP address. I am using gethostname, getaddrinfo and inet_ntop in order to do that.</p> <p><strong>Problem:</strong> On some target platform's computers, getaddrinfo returns the old IP address (the address before I set the fixed value). But if I am doing "ipconfig" in the cmd, the expected fixed value is shown. It is also pingable by other computers. All computers have only 1 network card, IPv6 is disabled.</p> <p><strong>Platform:</strong> Windows 7 x64.</p> <p><strong>IDE:</strong> Visual Studio 2015.</p> <p>I would like to have the actual fixed IP address. Thank you for your help!</p> <p><strong>Code sample:</strong></p> <pre><code>// [Some stuff...] addrinfo hints; addrinfo *pResults; int returnedCode; char hostName[1024]; if (0 != (returnedCode = gethostname(hostName, sizeof hostName))) { // Error handling stuff. } memset(&amp;hints, 0, sizeof hints); hints.ai_family = AF_INET; // Only want IPv4. hints.ai_socktype = SOCK_DGRAM; // UDP stream sockets. hints.ai_flags = AI_PASSIVE; // Fill in my IP for me. if (0 != (returnedCode = getaddrinfo(hostName, NULL, &amp;hints, &amp;pResults))) { // Error handling. } struct addrinfo* res; char buffer[INET_ADDRSTRLEN]; std::string localIP; for (res = pResults; res != NULL; res = res-&gt;ai_next) { if (res-&gt;ai_family == AF_INET) { const char* ip = inet_ntop(AF_INET, &amp;((struct sockaddr_in *)res-&gt;ai_addr)-&gt;sin_addr, buffer, INET_ADDRSTRLEN); if ((NULL == ip) || (nullptr == ip)) { // Error handling. } else { localIP = std::string(ip); } } } freeaddrinfo(pResults); // free the linked-list WSACleanup(); // [More stuff...] </code></pre> http://ift.tt/2kLQ1yf 0 masum billah http://ift.tt/2kvDikO 2017-02-09T13:29:20Z 2017-02-09T13:59:05Z <p>In gmail when we conversation with others then at the end each email concatenate with previous conversation. by the help of python <strong>imaplib</strong> library i get the email body like below . Now i want to delete previous conversation and get only main message... </p> <p><strong>Input:</strong></p> <pre><code>--------------------Now i Have-------------------------- Dear vaia, Sale order fail to sync when it contain Generic Product. ....need to little investigate about it. This is a issue which is occurred if any product have salePrice of greated then 2 decimal value like 33.34500 etc. Now POS only use @ decimal values like 33.34 so please aware about this about configuring prism to have always 2 decimal digits. On Thu, Jan 26, 2017 at 9:23 PM, Abu Shaed Rimon &lt;rimon@divine-it.net&gt; wrote: &gt; &gt; Dear Concern, &gt; &gt; Observation after update:- &gt; &gt; -- "+" sign working for add customer and Product but this button also &gt; &gt; Thank You. &gt; &gt; &gt; *...Best Regards,* &gt; http://www.divineit.net &gt; &gt; &gt; On Thu, Jan 26, 2017 at 5:44 PM, Khirun Nahar Urmi &lt;urmi@divine-it.net&gt; &gt; wrote: &gt; &gt;&gt; Dear Rimon vaia, &gt;&gt; &gt;&gt; &gt;&gt; Please take an update from git &gt;&gt; &gt;&gt; On Thu, Jan 26, 2017 at 3:24 PM, Abu Shaed Rimon &lt;rimon@prismerp.net&gt; &gt;&gt; wrote: &gt;&gt; &gt;&gt;&gt; Dear Concern, &gt;&gt;&gt; &gt;&gt;&gt; Please take a review about the mentioned observation in following :- &gt;&gt;&gt; *Helpdesk:* http://ift.tt/1vdc15a &gt;&gt;&gt; </code></pre> <p><strong>Output:</strong></p> <pre><code>---------------------My Expectation------------------------- Dear vaia, Sale order fail to sync when it contain Generic Product. ....need to little investigate about it. This is a issue which is occurred if any product have salePrice of greated then 2 decimal value like 33.34500 etc. Now POS only use @ decimal values like 33.34 so please aware about this about configuring prism to have always 2 decimal digits. </code></pre> http://ift.tt/2kvDsbW 0 naveed Softdukan http://ift.tt/2kLIIXv 2017-02-09T13:20:28Z 2017-02-09T13:58:54Z <p>Hi I want to put rating stars on my webpage. Its is working fine. Rating is being added to database But a user can rate again and again. I want that stars should disable after rate once. Here is my code. Kindly help me Thank you.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;link href="http://ift.tt/2kvKj56" rel="stylesheet" type="text/css"&gt; &lt;script src="http://ift.tt/1LdO4RA"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://ift.tt/2kvF19Q"&gt;&lt;/script&gt; &lt;script language="javascript" type="text/javascript"&gt; $(function() { $("#rating_star").codexworld_rating_widget({ starLength: '5', initialValue: '', callbackFunctionName: 'processRating', imageDirectory: 'images/', inputAttr: 'postID' }); }); function processRating(val, attrVal){ $.ajax({ type: 'POST', url: 'rating.php', data: 'postID='+attrVal+'&amp;ratingPoints='+val, dataType: 'json', success : function(data) { if (data.status == 'ok') { alert('You have rated '+val+' to CodexWorld'); $('#avgrat').text(data.average_rating); $('#totalrat').text(data.rating_number); }else{ alert('Some problem occured, please try again.'); } } }); } &lt;/script&gt; &lt;style type="text/css"&gt; .overall-rating{font-size: 14px;margin-top: 5px;color: #8e8d8d;} &lt;/style&gt; &lt;/head&gt; &lt;body style="background-color:black"&gt; &lt;h1&gt;Give us star&lt;/h1&gt; &lt;input name="rating" value="0" id="rating_star" type="hidden" postID="1" /&gt; &lt;div class="overall-rating"&gt;(Average Rating &lt;span id="avgrat"&gt;&lt;?php echo $ratingRow['average_rating']; ?&gt;&lt;/span&gt; Based on &lt;span id="totalrat"&gt;&lt;?php echo $ratingRow['rating_number']; ?&gt;&lt;/span&gt; rating)&lt;/span&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Click and Hover funtion in javascript.</p> <pre><code>(function(a){ a.fn.codexworld_rating_widget = function(p){ var p = p||{}; var b = p&amp;&amp;p.starLength?p.starLength:"5"; var c = p&amp;&amp;p.callbackFunctionName?p.callbackFunctionName:""; var e = p&amp;&amp;p.initialValue?p.initialValue:"0"; var d = p&amp;&amp;p.imageDirectory?p.imageDirectory:"images"; var r = p&amp;&amp;p.inputAttr?p.inputAttr:""; var f = e; var g = a(this); b = parseInt(b); init(); g.next("ul").children("li").hover(function(){ $(this).parent().children("li").css('background-position','0px 0px'); var a = $(this).parent().children("li").index($(this)); $(this).parent().children("li").slice(0,a+1).css('background-position','0px -28px') },function(){}); g.next("ul").children("li").click(function(){ var a = $(this).parent().children("li").index($(this)); var attrVal = (r != '')?g.attr(r):''; f = a+1; g.val(f); if(c != ""){ eval(c+"("+g.val()+", "+attrVal+")") } }); g.next("ul").hover(function(){},function(){ if(f == ""){ $(this).children("li").slice(0,f).css('background-position','0px 0px') }else{ $(this).children("li").css('background-position','0px 0px'); $(this).children("li").slice(0,f).css('background-position','0px -28px') } }); function init(){ $('&lt;div style="clear:both;"&gt;&lt;/div&gt;').insertAfter(g); g.css("float","left"); var a = $("&lt;ul&gt;"); a.addClass("codexworld_rating_widget"); for(var i=1;i&lt;=b;i++){ a.append('&lt;li style="background-image:url('+d+'/widget_star.gif)"&gt;&lt;span&gt;'+i+'&lt;/span&gt;&lt;/li&gt;') } a.insertAfter(g); if(e != ""){ f = e; g.val(e); g.next("ul").children("li").slice(0,f).css('background-position','0px -28px') } } } })(jQuery); </code></pre> http://ift.tt/2kLLFai 2 rospotniuk http://ift.tt/2kvEBjO 2017-02-09T13:11:56Z 2017-02-09T13:58:58Z <p>The problem is the following:</p> <p>Suppose, I have a table of such view (it is a sub-sample of the table I'm working with):</p> <pre><code>| col1 | col2 | |------|------| | 1 | a2 | | 1 | b2 | | 2 | c2 | | 2 | d2 | | 2 | e2 | | 1 | f2 | | 1 | g2 | | 3 | h2 | | 1 | j2 | </code></pre> <p>I need to add two new columns </p> <ul> <li><code>prev</code> containing the previous value in <code>col1</code> not equal to the current </li> <li><code>next</code> containing the next value in <code>col1</code> not equal to the current </li> </ul> <p>If there is no previous value, <code>prev</code> should contain the current <code>col1</code>'s value as well as <code>next</code> should contain the current value if no next values exist.</p> <p>Result should have the following form: </p> <pre><code>| col1 | col2 | prev | next | |------|------|------|------| | 1 | a2 | 1 | 2 | | 1 | b2 | 1 | 2 | | 2 | c2 | 1 | 1 | | 2 | d2 | 1 | 1 | | 2 | e2 | 1 | 1 | | 1 | f2 | 2 | 3 | | 1 | g2 | 2 | 3 | | 3 | h2 | 1 | 1 | | 1 | j2 | 3 | 1 | </code></pre> <p>I will be grateful any help.</p> http://ift.tt/2kLGbfH 4 Axel Samyn http://ift.tt/2kvzPmq 2017-02-09T13:09:39Z 2017-02-09T13:58:31Z <p>I know the title may sound imprecise but that is because i'm not sure where my error comes from...</p> <p>First, here's my folder organization :</p> <ul> <li>Assets <ul> <li>Scenes</li> <li>Scripts <ul> <li>MemoryCard.cs</li> <li>SceneController.cs</li> </ul></li> <li>Sprites</li> </ul></li> </ul> <p>At start, the file "MemoryCard" was titled as "MemoryCards" (notice the "s" at the end). I use to edit my files with Unity's build-in text editor "Monodevelop" and while editing my file, I decided to rename it via Monodevelop... which appeared to be a bad idea since there now is a warning message : </p> <p>"A meta data file (.meta) exists but its asset 'Assets/Scripts/MemoryCards.cs' can't be found. When moving or deleting files outside of Unity, please ensure that the corresponding .meta file is moved or deleted along with it."</p> <p>I first deleted the .cs file and created a new one but the error remains...</p> <p>My problem is I don't know which meta file I should look for since the meta file "MemoryCards.cs.meta" has been deleted and replaced at the creation of the new script by its corresponding .meta file...</p> <p>I guess there's some kind of specific file referencing all the meta files like a tree or so... but I did not find any doc on the internet.</p> <p>I hope any of you will be able to help me :) </p> <p>Thank you in advance,</p> <p>Axel</p> http://ift.tt/2kLQeSh 0 vKashyap http://ift.tt/2kvGL2R 2017-02-09T12:56:47Z 2017-02-09T13:58:37Z <p>I have built the webrtc for android using the <a href="http://pristine.io" rel="nofollow noreferrer">Pristine IO</a> web srcipts from here <a href="http://ift.tt/1IMdSFU" rel="nofollow noreferrer">http://ift.tt/2kvQ4zN;. I have cloned the git repo of webrtc also, but don't see any tagged releases of it anywhere. In fact I don't see even a single tag and only 2-3 branches other than master.</p> <p>My question is how do people generally version their webrtc builds? Is it solely dependent on git commit sha only?</p> <hr> <p><b>Edit:</b> generated files are <a href="http://ift.tt/2kLMG2i" rel="nofollow noreferrer"><img src="http://ift.tt/2kLMG2i" alt="enter image description here"></a></p> http://ift.tt/2kvLyBf 0 EquipDev http://ift.tt/2kLOSqx 2017-02-09T12:41:44Z 2017-02-09T13:58:21Z <p>Having made as small <code>print('Hello')</code> in Windows Emacs, I try to run this from within Emacs, using first ^C^P to make Python interpreter, and then ^C^C to run then code. However this only says:</p> <blockquote> <p>send: print...</p> </blockquote> <p>But it does not run the code. How to make Windows Emacs run the code also ?</p> <p>Version info:</p> <ul> <li>GNU Emacs: 25.0.50.1 </li> <li>Python: 3.5.2</li> </ul> http://ift.tt/2kvFwAw 0 ThalesMiguel http://ift.tt/2kLFDGU 2017-02-09T12:34:08Z 2017-02-09T13:59:04Z <p>Is there a way to add a class to filtered columns using <a href="http://ift.tt/16sdS7U" rel="nofollow noreferrer">yadcf</a>?</p> <p>As for now, When I filter a column on my table using a select box provided by yadcf, I can't seem to show that the column is filtered.</p> <p>I want to add a class to the columns <code>&lt;th&gt;</code> so that I can style it to show my users that the corresponding column is filtered.</p> <p>Thanks in advance.</p> http://ift.tt/2kLE2kr 1 fox http://ift.tt/2kvBk3O 2017-02-09T12:33:28Z 2017-02-09T13:58:30Z <p>I want to add all images from the <code>List&lt;Image&gt;</code> but it adds only last image. I tried using <code>var</code> instead of <code>System.Drawing.Image</code> but it didn't help. Also, I tried changing the ordering of lines to make sure that it is not some logical mistake but it didn't help either. </p> <pre><code>SaveFileDialog svg = new SaveFileDialog(); svg.ShowDialog(); Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35); PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(svg.FileName + ".pdf", FileMode.Create)); doc.Open(); foreach (System.Drawing.Image image in images) { iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Tiff); if (im.Height &gt; im.Width) { float percentage = 0.0f; percentage = 700 / im.Height; im.ScalePercent(percentage * 100); } else { float percentage = 0.0f; percentage = 540 / im.Width; im.ScalePercent(percentage * 100); } im.Border = iTextSharp.text.Rectangle.BOX; im.BorderColor = iTextSharp.text.BaseColor.BLACK; im.BorderWidth = 3f; doc.Add(im); doc.NewPage(); } doc.Close(); </code></pre> <p>What is the problem? <code>foreach</code> works fine displaying those images in <code>pictureboxes</code>. I don't understand why it doesn't work with <code>iTextSharp</code>.</p> http://ift.tt/2kLB2nX 1 bjkpriyanka http://ift.tt/2kvDfFS 2017-02-09T09:15:03Z 2017-02-09T13:59:05Z <p>When route is called, a method "load" is called which fetches data to display details of user.(using "this.store.findRecord" to fetch the user)</p> <p>In that page, on button click am making an ajax call from controller, after success i am trying to bring updated values of user by calling the previous method "load". this time method is getting called but "this.store.findRecord" is not making call to the backend.</p> <p>current-user (service which contains load method)</p> <pre><code> user: null, load(){ window.u = this; if(this.get('session.isAuthenticated')){ console.log('reload user'); this.get('store').findRecord('user', 'me', {reload:true}).then(user =&gt; { this.set('user', user); }); } else { console.log('not reloading user'); } } </code></pre> <p>The above method will be called when the page loads for the first time and also in the success part of ajax call</p> <p>Ajax call </p> <pre><code>ajax: Ember.inject.service(), currentUser: Ember.inject.service('current-user'), init(){ this._super(...arguments); }, actions:{ recharge(amount){ console.log(amount); var user_id = this.get('currentUser').get('user').get('id'); var balance = this.get('currentUser').get('user').get('balance'); var that = this; console.log(this.get('currentUser').get('user')); this.get('ajax').post('/user/payments', {data: {user_id: user_id, amount:amount}}) .then(() =&gt; { console.log("successfully recharged"); this.get('currentUser').load(); }).catch(() =&gt; { console.log("Something went wrong"); }); } } </code></pre> http://ift.tt/2kLGd7j 0 Hamid Noori http://ift.tt/2kvGHjK 2017-02-09T07:01:44Z 2017-02-09T13:58:48Z <p>I am generating zip file using following angular and other javascript library.</p> <pre><code>$http.post("http://serverURL/downloadAttendanceReport",data,config).success(function(response){ var blob = new Blob([response], {type: "octet/stream"}); var fileName = "Report.zip"; saveAs(blob, fileName); }); </code></pre> <p>But above code not giving proper zip file.While openning downloaded zip i am getting error ::<strong>An error occurred while loading the archive.</strong> </p> <p>My Back-end(NodeJS) code is .</p> <pre><code>var zip = require('express-zip'); ..... res.zip(fileList,'report.zip'); </code></pre> <p>I am getting response from server:</p> <pre><code>PKQ6IJattendance-Next Education.pdf�ViTi=�MCDP(Z� K%�9Zihك��2V�" �� ���0�BC�":r�UAY\m��E1ꑀ � 0ttz������W��}��{_����ӑa�����&lt;�wucl f���+"��x�H�|���,C����hR�����'w�$�n�� �&lt;]R~-{�)[n��AS\����PR��G��S�a���M)��@R���A�Ǧ��"��9 /�+�.�vTF2�+�&lt;xԳ��٘o b+��b�-�+Ͼ�H� ;������C�`� �n�̾RE@�=��'*�}�g�_EM�}b k����K��M̚93;�� � ������U�#m�����1��(�r=!��4��e�����������_g`�4����ս��R��/mb,�4�t�!��������Wv�ER�~��Ɋ�ɺ�G3��{�{�i�uR�S��"{JC-S��rc��]R5,���λm�0&amp;�q�K��3u�vqϜ:=V��(P���(c�/{t�8a�gsj�g� �=S�n��w&amp;�4���B��/{���֩0j�,���q�X�̸�+^��-|XŃ����;�@���_���r��E����30�0�NC7�s�O6�η&lt;7�ai��sL]���ꓣ+��zέ ɸs��C��F��V���y�M/�N0��}׽�`�N�f��IT���'BZ���Bv��j.�M;�r��D�&amp;�6F׵ W�g7�ƽ�_P�k� �����n�M6��J�4�Z궔H�����:��&amp; K�{=��Z��:v9&amp;��o��/��5��ӾUɉ���`����^�!�p�漖/�&gt;�k�����79��(����k��%ػA˄�!����w����������Ch,��_?�u�(m��!I��w�@���?#�ѻw�l2�7P�rж���J�3��zm 3�ƾ�cq.r�i�OZ�#�Ӣ}}2"/�hJ��� ��x_,s&amp;B�t�����n\���Rk~�����ߊ��z���z��E��}p8���� ^O�ؑl��cm�o��cLu��|�F�\���NUGl�[=���LjT��x�?w�B�A�'�R\���TNJ�����+zU��A��ߐ�Uy��7��6��``[ �e#�Y� ��1Kߺ#Ε�}��w�P�^r8s��L����k���(�{&lt;�P���s_�� 㼬�,��Z�7$Eh�R!�G9id��ol�6����%���f���� jw7�_ќ@�l�l���?���[Cfʝl�ov�R�����S���$�%�����6`jl������X�&gt;��F�䄫���w�+�*�m+���y�&amp;|!���bv\_�q���W&amp;z��F��̏F�G�֜ʚ��&amp;��νl[8��u�����I��|��l�)�w��~�L+����c��]�Ue1���ߪ�)��=���n�dpk��ˊ��ኈ��a���l4�:�&amp;�E۫_��ew���^�M�x��9~�p2��N�o��v�lY�~��Ga,�\�x���z���E�I�&gt;�.z��nD�B�;�}q^�~��@\��j�&gt;��$�])���R�^v��2�y�b��j���P�|x�YLX~3��}`�n�@�a�����;�%ޟ�u�nQ8&amp;�2���~�|�&gt;ʸ��x�ȉ�W�Q��/G�����|�m��f�Fg���������{G�(���\;��Ӽ�n��w�,�gȽ�"���D���:�'t�`�v�r&lt;a "�D�� ��"�&amp;�;��AP��8T�F�����Dd���1�A�e�"Da�o���%d��h@K� (h��v�����J��(�oM��hJ�J�J8z�$�Q�&gt;|!"��a�'�KU'�$�".��mI�_ޙ�,�҉��+�RП;����W�'�/�I�dCє��&gt;G�L��?,�~�A�e�@�]J^�i2_U��`�9pBو�_d����XV ��\&gt;b����A71����:n�px2�Q��#-pD3����2�X�?Q_%�K� �`p_@" D �\ÓH�P�D_jT�5 ���8�F��^T���H��qԯ�2 � ��x��2@��7����R �c�f�)s` bA��bs�A��ڰ�L&amp;�a �!l�HFq0�E� 8��.� 1��7��G"�H*�%��� ��11q�``�PKM;ݍ�� PKQ6IJattendance-Craft Villa.pdf�VwTSyQ#� J]%y���'���Ko)/'ES��:XР(ed� �Ho���,��Q@� �.("�澨��̞�g����{��}߽��g�jK3Ǣ (�ǃw�P��=��%��HB,�ah\�ah&lt;���YB6lm-��`�񳏓���]=�5ܥ�@�Kʭ�����ԝ� ~YV1�1e�|��}�'�g��ȇ�܉����?-��_U��g�r�?���ѹ�@��^(8=��fN�ql�s䵍�������7�^k�{�����ڔ=��֞�WV���i�M���Xˀ3I[4v�f5No�%Uh�w�8�Oa��v��k�H׻��K#޾��C��cQne��+�����񵸇�8���-��r��-�Gɒ��)[�X�A ��C�^�����ҭ�Nj1X-�N�Y��s���=��ZW��M(���=�2�'d��1��"�L�I�"��m�r�)�%/ ���.���"&gt;�,٬6�MW" ='�����~�NS8�N`�����&lt;�Г����#��`�g�v���].I���z`regL�WYލg�ͤڕg�\C۬�Ћ���?.r!��8o��E���d?)wu�gW�k�����8��Q��^�:?lX�Lf��&lt;�Y��x�Ymf�p��w#��ͧ�����rǁe���D:��vޢm�n��{��5��ѢXdz���(GS�[����xk�}K��Ȫ���SzN��������S��r��2lw�"����Ȁ�TD*)S~t�F�j�S�w{D�*iʯ�k���z66LU��`\9]�e_�+�5�5��]����������Uz�R����Ǚ�&amp;�[���T��j۱��-�ͷ%W�G�M[9���{1�����Z��}E�u~�P��_&gt;�x��F��u�ۄA���3U�i�A]�{Ѧӧ3A��A��aU:�%0�K���=�Ȧk�b��ncw��:�:F��Y�HSD^������MĊ,W�%��\�z! �[���{��ܝN4�]���r/O[�x�b����d�?�Og-W�R�������\���J~/t=�'��̬��� �T�=�e���DZ?-�����@~�z�鷷��% &gt;����=��ݨ�3�&gt;i��jl�U�ʢ1 ���F$&amp;�ڏ��Q�X�܄������bY����*����k��1+�W��qb\�I�0mwQ����?:d�Pw��s�٠3�6��R?u-=�1�ӥ\u�=���}��r���&amp;Y7��əh%%�P��q]��8��y ��S��ϼ��S��U��y�U��zэo�b��a�3��� �1�؍# ��mY՝� �C)u�s�m�cV�����m�k8vƳ����ec5�4R�y���՛����CPi].�瘌��qܝN�&amp;ç�[���ª_�*���ɳ9��z�%�c!9Z�� �����������DwC㵌�g��ߝ����M�������d�_�����]�1���u���� ���&lt;5��Ԯ���EX^J��zSkt#����ζ��NV�+R0+��L�_�ܤ�䒣�K&lt;Q�Ȍ�c&gt;�TS�hT�n � �t�z�QO\�gXP�s:���'+�)FX�sqe�&gt;m�;��i��W�=��o&amp;c����T���(��������Q���T��֌q�aR�|�t��z���~ߨP��0&amp;�j՘��uoKvM����l�wK�FGb�8A+P���qq _ȦAa?ld�2D�@�C $�K�6��FB`�",VU��,wX�a�-`&lt;�p ���G�(o��{W�� "54,�{I�xՇ5r0N0�ˠ��@$D$�8�X4X[�H�����0İ ����bs����@�}�N�lH� ��|'s?�ݥL�J�J �3���ť�������'�Ĉ�R�e,Ɓ���ܧ�A"�� *C�� C�;/�Йϴ-&gt;�"}`KY�Ȕ��84��Sf��1B�0�%����a��l[���v;�Z�8����@&lt;q+H4��&amp;f*�O!� �3�3�p�A��?�D$��ÒH� �&gt;� &lt;"�O12�/c ��K-B�חy8���D�=O"bpy���](�*��]���%f�Xl2���x&lt;�D�@d���p Al��%�@�qp,�D�l�1 ��`6H�Z`v 8B@�:Ɲ �X�I�;���!���� �PK�h���� PK-Q6IJM;ݍ�� attendance-Next Education.pdfPK-Q6IJ�h���� �attendance-Craft Villa.pdfPK�� </code></pre> <p>How do i solve zipping problem in angular.</p> <p>i also reffered <a href="http://ift.tt/1NrdRqw">link</a></p> http://ift.tt/2kLIHCV 0 Shahid Sarwar http://ift.tt/2kvI0iq 2017-02-09T06:52:52Z 2017-02-09T13:59:07Z <p>I have a webview which needs to open a particular link. When I hit that link, it redirects me to another link... My problem is that I am able to open the first link but the second link doesn't get called... Please help me!</p> <p>Here is my code:</p> <pre><code>public class OnlinePayment extends AppCompatActivity { WebView online_payment_activity_web_view; String url; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.online_payment_activity); Bundle extras = getIntent().getExtras(); url = extras.getString("redirect_url"); final ProgressDialog pd = ProgressDialog.show(OnlinePayment.this, "", "Redirecting...", true); Log.e("Here redirect first", url); online_payment_activity_web_view=(WebView) findViewById(R.id.online_payment_web_view); online_payment_activity_web_view.getSettings().setJavaScriptEnabled(true); online_payment_activity_web_view.getSettings().setSupportZoom(true); online_payment_activity_web_view.getSettings().setBuiltInZoomControls(true); online_payment_activity_web_view.getSettings().setDisplayZoomControls(false); online_payment_activity_web_view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); online_payment_activity_web_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); online_payment_activity_web_view.setWebChromeClient(new WebChromeClient()); online_payment_activity_web_view.getSettings().setLoadWithOverviewMode(true); online_payment_activity_web_view.getSettings().setUseWideViewPort(true); online_payment_activity_web_view.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } /** * Notify the host application that an SSL error occurred while loading a * resource. The host application must call either handler.cancel() or * handler.proceed(). Note that the decision may be retained for use in * response to future SSL errors. The default behavior is to cancel the * load. * * @param view The WebView that is initiating the callback. * @param handler An SslErrorHandler object that will handle the user's * response. * @param error The SSL error object. */ @Override public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) { //final AlertDialog.Builder builder = new AlertDialog.Builder(OnlinePayment.this); String msg=""; if(error.getPrimaryError()==SslError.SSL_DATE_INVALID || error.getPrimaryError()== SslError.SSL_EXPIRED || error.getPrimaryError()== SslError.SSL_IDMISMATCH || error.getPrimaryError()== SslError.SSL_INVALID || error.getPrimaryError()== SslError.SSL_NOTYETVALID || error.getPrimaryError()==SslError.SSL_UNTRUSTED) { if(error.getPrimaryError()==SslError.SSL_DATE_INVALID) { msg="The date of the certificate is invalid"; } else if(error.getPrimaryError()==SslError.SSL_INVALID) { msg="A generic error occurred"; } else if(error.getPrimaryError()== SslError.SSL_EXPIRED) { msg="The certificate has expired"; } else if(error.getPrimaryError()== SslError.SSL_IDMISMATCH) { msg="Hostname mismatch"; } else if(error.getPrimaryError()== SslError.SSL_NOTYETVALID){ msg="The certificate is not yet valid"; } else if(error.getPrimaryError()==SslError.SSL_UNTRUSTED){ msg="The certificate authority is not trusted"; } } final AlertDialog.Builder builder = new AlertDialog.Builder(OnlinePayment.this); builder.setMessage(msg); builder.setPositiveButton("continue", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { handler.proceed(); } }); builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { handler.cancel(); } }); final AlertDialog dialog = builder.create(); dialog.show(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.e("---URL onPageStarted---", url); pd.show(); String [] restructured_url = url.split("\\?"); Log.d("URL NEW----", restructured_url[0]); if(restructured_url[0].equalsIgnoreCase(Utils.MAIN_URL+"/cgp_dashboard")){ Utils.dashBoardRefresh = true; pd.hide(); StoreSharePreference.SSP().putBoolean StoreSharePreference.SSP().putBoolean("payment_processed", true); Log.e("INSIDE SUCCESS", "------"); StoreSharePreference.SSP().putBoolean("isCGPCustomer", true); StoreSharePreference.SSP().putString("cgp_customer", "yes"); Intent intent = new Intent(OnlinePayment.this, CherishMain.class); intent.putExtra("fromPayment", true); intent.putExtra("paymentSucess", true); intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP |intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); // Move to dashboard } else if(restructured_url[0].equalsIgnoreCase(Utils.MAIN_URL+"/customermaster/paymentfail")) { StoreSharePreference.SSP().putBoolean("payment_processed", false); Log.e("OUTSIDE SUCCESS", "------"); if (StoreSharePreference.SSP().getBoolean("isCGPCustomer", false) == true || StoreSharePreference.SSP().getString("cgp_customer").equals("yes")) { Intent intent = new Intent(OnlinePayment.this, CherishMain.class); intent.putExtra("fromPayment", true); intent.putExtra("paymentSucess", false); intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP |intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); // Move to dashboard } else { Toast.makeText(getBaseContext(), "Payment failed", Toast.LENGTH_LONG).show(); onBackPressed(); } } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view,url); Log.e("---URL ORIGINAL---", url); String javascript="javascript:document.getElementsByName('viewport')[0].setAttribute('content', 'initial-scale=1.0,maximum-scale=10.0');"; view.loadUrl(javascript); if(pd.isShowing()){ pd.hide(); } } }); if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) { online_payment_activity_web_view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW ); } online_payment_activity_web_view.loadUrl(url); } </code></pre> http://ift.tt/2kLIzmM 1 Zhao Yi http://ift.tt/2kvzRuy 2017-02-08T04:43:00Z 2017-02-09T13:58:55Z <p>I am using a non-admin account to access to a Mongo instance. And the account I am using doesn't have the right to run <code>show dbs</code> command. And that account also doesn't have the permission to access <code>admin</code> database. See below output:</p> <pre><code>show dbs 2017-02-08T15:40:54.651+1100 E QUERY [main] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }", "code" : 13, "codeName" : "Unauthorized" } : _getErrorWithCode@src/mongo/shell/utils.js:25:13 Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1 shellHelper.show@src/mongo/shell/utils.js:755:19 shellHelper@src/mongo/shell/utils.js:645:15 @(shellhelp2):1:1 </code></pre> <p>I wander how to get the list of databases this account has access. I know that I can use admin account to get all roles information. But I don't have admin account password. I only have this account credential. How can I do that for the specific account in this case?</p> http://ift.tt/2kLEgb1 0 Philippe Dupont http://ift.tt/2kvNEBj 2016-09-29T16:10:39Z 2017-02-09T13:58:29Z <p>I'd like my GCP dataflow instances to reach a public ELB in AWS without having to manage manually the ACL in the ELB security group.</p> <p>I thought about redirecting my dataflow traffic through only one GCP public IP so I could restrict the AWS ELB to this IP.</p> <p>I know I can do something like this in AWS using a NAT Gateway, but I can't find anything similar in GCE. Am I wrong? </p> <p>I see how to deploy a logical NAT in GCE but I don't want to have a SPOF and have to manage the NAT service (which means making it HA mainly).</p> <p>We also already have a vpn connection between GCE and AWS, maybe it could help? </p> <p>Has someone a solution ?</p> <p>Thank you</p> http://ift.tt/2kLGbwd 6 amb http://ift.tt/2kvGLjn 2015-08-28T07:38:07Z 2017-02-09T13:59:09Z <p>I want to create a React Native component in pure JavaScript, composed of other components such as <code>TouchableOpacity</code> and <code>Text</code>. I have a couple of buttons in my app that are composed of that two components so I thought it would be nice to learn how to create my own components for better code reuse.</p> <p>The finished component should look more or less like this:</p> <pre><code>&lt;Button&gt; Tap me! &lt;/Button&gt; </code></pre> <p>And this is the code I made for the component so far:</p> <pre><code>class Button extends Component { render () { &lt;TouchableOpacity style={styles.button}&gt; &lt;Text style={styles.textButton}&gt; &lt;/Text&gt; &lt;/TouchableOpacity&gt; } }; </code></pre> <p>However, I don't know how I can use the <code>Tap me!</code> inner child text in my component and I don't really get how I can make my component to accept custom props and the <code>TouchableOpacity</code> and <code>Text</code> props.</p> <p><strong>PS:</strong> I know there are some React Native components like this out there, but I prefer to create my own in order to learn how I can build this kind of custom components. Also, React Native is awesome but I cannot find how to build things like this in their docs and I think it's a really interesting exercise for people starting in React.</p> http://ift.tt/2kLFbYY 6 user2972061 http://ift.tt/2kvLyRL 2013-11-09T14:08:31Z 2017-02-09T13:59:02Z <p>when i am trying to open the TinyMCE editor on popup dialog box and click on "Insert link" then popup dialogbox appear for "insert link" but i am unable to write on the text field for "insert link".</p> <p>as far i know, there might be the problem of dialog box open in another dialog box, but anyone has any way arround of it.</p> http://ift.tt/2kLLDPI 3 ORey http://ift.tt/2kvKlde 2013-09-13T18:23:51Z 2017-02-09T13:58:51Z <p>I would like to have a Stage set to "UNDECORATED" made draggable and minimizable. The problem is that I can't find a way to do so since the examples I come accross that do this do so via methods inserted inside the main method.</p> <p>I would like to have this done via a method declared in the controller class, like how I managed to do with the "WindowClose()" method below.</p> <p>This is my second day working with JavaFX, if this seems too much of a common knowledge question. Thank you all in advance.</p> <pre><code>// Main Class/ Method import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.stage.StageStyle; public class Fxmltableview extends Application { public static String pageSource = "fxml_tableview.fxml"; public static Scene scene; @Override public void start(Stage stage) throws Exception { stage.initStyle(StageStyle.UNDECORATED); stage.initStyle(StageStyle.TRANSPARENT); Parent root = FXMLLoader.load(getClass().getResource(pageSource)); scene = new Scene(root, Color.TRANSPARENT); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } } </code></pre> <p>..</p> <pre><code>// The Controller import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.TableView; import javafx.scene.control.TextField; public class FXMLTableViewController { @FXML private TableView&lt;Person&gt; tableView; @FXML private TextField firstNameField; @FXML private TextField lastNameField; @FXML private TextField emailField; @FXML protected void addPerson (ActionEvent event) { ObservableList&lt;Person&gt; data = tableView.getItems(); data.add(new Person( firstNameField.getText(), lastNameField.getText(), emailField.getText() )); firstNameField.setText(""); lastNameField.setText(""); emailField.setText(""); } public void WindowClose (ActionEvent event) { Platform.exit(); } } </code></pre> http://ift.tt/2kLBR00 0 chemila http://ift.tt/2kvNs57 2011-12-01T01:44:08Z 2017-02-09T13:58:56Z <p>This is a test file: </p> <pre><code>xxx hello hello others </code></pre> <p>I want to use sed:</p> <pre><code>sed -i '/hello/d' the_test_file </code></pre> <p>This will remove all lines contain "hello", so how to just remove the first line contains "hello"? </p> <p>I think sed cant do it, but with perl i can. it's like:</p> <pre><code>perl -00 -pe "s/hello//" the_test_file &gt; /tmp/file &amp;&amp; mv /tmp/file the_test_file </code></pre>

Let's block ads! (Why?)



Recent Questions - Stack Overflow

mercredi 9 avril 2014

Android 4.4, undefined reference to __printf_chk


Vote count:

0




I am moving some libraries from Android 4.3 to Android 4.4


The projects that used to compile in Android 4.3 now gives below error when compiled using Android 4.4 sources


/home/vishallocal/TI/android/kitkat/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6/sysroot/usr/include/bits/stdio2.h:105: error: undefined reference to '__printf_chk' /home/vishallocal/TI/android/kitkat/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6/sysroot/usr/include/bits/stdio2.h:105: error: undefined reference to '__printf_chk' /home/vishallocal/TI/android/kitkat/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6/sysroot/usr/include/bits/stdio2.h:105: error: undefined reference to '__printf_chk' /home/vishallocal/TI/android/kitkat/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6/sysroot/usr/include/bits/stdio2.h:105: error: undefined reference to '__printf_chk' collect2: error: ld returned 1 exit status


Any pointers on resolving this?



asked 2 mins ago






Group by a field in serializer data in django rest framework


Vote count:

0




I have this below code in models.py



class AffIoPrmsn(models.Model):
id = models.IntegerField(primary_key=True)
prmsn_nm = models.CharField(max_length=75)
class Meta:
db_table = u'aff_io_prmsn'
def __unicode__(self):
return unicode(self.prmsn_nm)

class AffIoObj(models.Model):
id = models.IntegerField(primary_key=True)
obj_nm = models.CharField(max_length=75)
class Meta:
db_table = u'aff_io_obj'
def __unicode__(self):
return unicode(self.obj_nm)


In serializer.py i have the below code



class AffIoAccessSerializer(serializers.ModelSerializer):
obj = serializers.RelatedField()
prmsn = serializers.RelatedField()
class Meta:
model = AffIoAccess
fields = ('obj', 'prmsn')
depth = 1


In Views.py



class AffIoAccessViewSet(viewsets.ModelViewSet):
model = AffIoAccess
queryset = AffIoAccess.objects.all()
serializer_class = AffIoAccessSerializer


The output i get when access api is


[{"obj": "Ticket", "prmsn": "Read"}, {"obj": "Ticket", "prmsn": "Create"}, {"obj": "Ticket", "prmsn": "Modify"}, {"obj": "Ticket", "prmsn": "Assign"}, {"obj": "Ticket", "prmsn": "Deliver"}, {"obj": "Ticket", "prmsn": "Track"}, {"obj": "Ticket", "prmsn": "Close"}, {"obj": "Ticket", "prmsn": "Disable"}, {"obj": "Ticket", "prmsn": "View Disabled Ticket"}, {"obj": "Internal Followups", "prmsn": "Read"}, {"obj": "Internal Followups", "prmsn": "Create"}, {"obj": "Ticket Views", "prmsn": "Read"}, {"obj": "Manual Delivery Queue", "prmsn": "Read"}, {"obj": "Manual Delivery Queue", "prmsn": "Delete"}, {"obj": "Manual Delivery Queue", "prmsn": "Inspect"}, {"obj": "Manual Delivery Queue", "prmsn": "Approve"}, {"obj": "Roles and Permissions", "prmsn": "Read"}, {"obj": "Roles and Permissions", "prmsn": "Create"}, {"obj": "Task", "prmsn": "Read"}, {"obj": "Task", "prmsn": "Create"}, {"obj": "SMS", "prmsn": "Send"}, {"obj": "Analysis Queue", "prmsn": "Read"}, {"obj": "Auto Tickets Queue", "prmsn": "Read"}, {"obj": "Customer Response", "prmsn": "Read"}, {"obj": "Email Approve", "prmsn": "Read"}, {"obj": "Report Schedule", "prmsn": "Read"}, {"obj": "Single Report", "prmsn": "View"}, {"obj": "Single Report", "prmsn": "Publish"}, {"obj": "Task Notes", "prmsn": "Create"}]


I want to get


[{"Ticket": ["Read","Create","Modify"]},....] likewise


Can someone please help on this


Thanks in advance



asked 2 mins ago






My Javascript code crashes in infinite loop?


Vote count:

0




Hello, I am just starting learning programming with javascript and i made a "game" where the computer generates a random number and you should guess it, however when i press the button to start playing the browser freezes like if there is an infinite loop. I tryed removing the loop "Do" and the game worked fine, however i can't get working the counter that registers the number of attempts made by the user before finding the correct number, because without loop every time i click the button "Go" in order to run the script the variable "counter" gets back to 0.., the text in the game is in Spanish, if you can't understand howthe program works because of it please tell me and i will translate it even further.



<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Prueba de Juego</title>
<script type="text/javascript">

//Selector de Modo
var modo=0;

function configuracion(){
var pregunta;
pregunta=confirm("[Seleccionar Modo] Would you like to use a custom range of values to generate the number?, if not we will proceed using standard mode.");

if (pregunta==true) {
modo=1;
var cambiar=document.getElementById('modo').innerHTML='<span id="modo" style="color: blue;">Modo Personalizado</span>';

}else{

modo=2;
var cambiar2=document.getElementById('modo').innerHTML='<span id="modo" style="color: green;">Modo Estandard</span>';

}
}





function juego(){
var contador,numero,ingresar,adivinar,aproximacion,minimo,maximo,mingen,maxgen;
contador=0;
numero=0;
minimo=100;
maximo=1000;
mingen=0;
maxgen=0;

//Verificar que modo se utiliza
if(modo=="0"){alert("[Atención] Modo no seleccionado.");return;}

//Modo Personalizado
if(modo=="1"){

mingen=document.getElementById("mingen").value;
maxgen=document.getElementById("maxgen").value;

if(mingen=="" || maxgen==""){
document.getElementById('status').innerHTML='<span id="status" style="color: #DBA901;">Please type in the maximum and minimum values..</span>';
return;
}

//Procesar a integer
mingen=parseInt(mingen);
maxgen=parseInt(maxgen);

if(mingen=="0" || maxgen=="0"){
document.getElementById('status').innerHTML='<span id="status" style="color: red;">Error. Imposible generar numero a partir de cero.</span>';
return;
}


//Continuar corriendo codigo
numero=Math.floor(Math.random() * (maxgen - mingen + 1)) + mingen;
//alert("Número generado exitosamente utilizando "+mingen+" y "+maxgen+" como valores máximos y minimos.");

//En caso de que no se desee utilizar un rango personalizado continuar en modo 2
}else if(modo=="2"){
//alert("[Cancelado] Utilizando modo estandard.")

//Pedir valor
adivinar=document.getElementById("adivinar").value;

//Cancelar codigo si el numero maximo esta vacio
if(adivinar==""){
document.getElementById('status').innerHTML='<span id="status" style="color: #DBA901;">Por favor ingresa el numero maximo posible de genrar.</span>';
return;
}

//Continuar corriendo codigo
adivinar=parseInt(adivinar);
if(adivinar>=100 && adivinar<=1000){
//alert("Numero máximo seleccionado: "+adivinar);
numero=Math.floor(Math.random()*adivinar)+1;
}else{
document.getElementById('status').innerHTML='<span id="status" style="color: #DBA901;">Por favor ingresa un numero maximo entre 100 y 1000.</span>';
return;
}
}


//Processing [PROBABLY WHERE THE ERROR IS AT]

do{

ingresar=document.getElementById("ingresar").value;

//Cancelar codigo si no se pone numero
if (ingresar==""){
document.getElementById('status').innerHTML='<span id="status" style="color: #DBA901;">Ingresa un numero a adivinar..</span>';
return;
}

ingresar=parseInt(ingresar);
contador++;

//¿Tenes la respuesta Maikol?
if(ingresar==numero){
document.getElementById('status').innerHTML='<span id="status" style="color: #DBA901;">El numero es: '+numero+ '¡Bien! ¡Lo Lograstes en '+contador+' veces!</span>';
//alert("¡Bien!, ¡lo lograstes!. el número era: "+numero);
}else{


//Algoritmo de de aproximación a número aleatorio
if(ingresar>numero)aproximacion=", es menor a lo que ingresastes.";else aproximacion=", es mayor a lo que ingresastes.";

//Algoritmo de aproximacion entre dos números
aviso=0;

if(ingresar>numero || ingresar<numero){
if(numero>1000 && numero>mingen && aviso==0) {document.getElementById('status').innerHTML='<span id="status" style="color: green;">El número es mayor de ' +mingen+',además'+aproximacion+'</span>'; aviso=1; }
if(numero<1000 && numero>700 && aviso==0) {document.getElementById('status').innerHTML='<span id="status" style="color: green;">El número está entre 700 y 1000, además'+aproximacion+'</span>'; aviso=1; }
if(numero<700 && numero>500 && aviso==0) {document.getElementById('status').innerHTML='<span id="status" style="color: green;">El número está entre 500 y 700, además'+aproximacion+'</span>'; aviso=1; }
if(numero<500 && numero>200 && aviso==0) {document.getElementById('status').innerHTML='<span id="status" style="color: green;">El número está entre 200 y 500, además'+aproximacion+'</span>'; aviso=1; }
if(numero<200 && numero>100 && aviso==0) {document.getElementById('status').innerHTML='<span id="status" style="color:green;">El número está entre 100 y 200, además'+aproximacion+'</span>'; aviso=1; }
if(numero<100 && numero>50 && aviso==0) {document.getElementById('status').innerHTML='<span id="status" style="color: green;">El número está entre 50 y 100, además'+aproximacion+'</span>'; aviso=1; }
if(numero<50 && numero<maximo && aviso==0) {document.getElementById('status').innerHTML='<span id="status" style="color: green;">El número es menor de '+maximo+' y tambien '+aproximacion+'</span>'; aviso=1; }
if(numero<50 && aviso==0) {document.getElementById('status').innerHTML='<span id="status" style="color: green;">El número es menor a 50'; aviso=1; }

}

}


}while(ingresar!=numero);

//Felicidades
//alert("¡Felicidades, lograstes descubrirlo en unas "+contador+" veces!");
}
</script>
</head>
<body>
<center>
<h1>Adivina tu Número V4.1 Box</h1>Versión mejorada, acepta generar rango de valores personalizados.
<p>¿Estás preparado para el reto?</p>
<img src="http://ift.tt/1i3mhqn" style="width:400px;eight:400px;" alt="Hola"/>
<br/><br/>

<p><h1><span id="status">You are not playing yet..</span></h1></p>
<form>
<h4>Custom Value Range</h3>
Minimum Value <input type="text" style="width:100px;" id="mingen"/><br><br>
Maximum Value <input type="text" style="width:100px;" id="maxgen"/>
</form>

<form>
<h4>Maximum number to generate in normal mode</h3>
Máximo <input type="text" style="width:100px;" id="adivinar"/><br><br>
</form>

<form>
<h3>Adivina tu Número!</h3>
<input type"text" id="ingresar"/>
</form>

<button style="height:40px; width:150px" onclick="configuracion()">Mode Selection</button>
<button style="height:40px; width:150px" onclick="juego()">Go</button>
<p>Modo Actual: <span id="modo" style="color: red;">N/A</span></p>
</center>


</body>
</html>


Thank you very much. Marcos MC



asked 2 mins ago






Auto-Layout UIScrollView and an animated UIView


Vote count:

0




Currently having an issue with using auto-layout and UIScrollView. The issue is when I scroll down on the scroll view, a previous UIView (that should be free roaming, and is animated to various positions) gets set back to its initial location where it is located in Storyboard.


What's the best way to make my single UIView not follow the behavior of auto-layout and let it do whatever it wants to do?



asked 51 secs ago

Brayden

1,592





Keeping text upper and lower case in MySql


Vote count:

0




I understand the title can be confusing, was having trouble wording it. If Someone can come up with a better phrasing, feel free to change it.


When I pass in values to the database in MySQL, the 'case' of the text is passed in all well and good, as well as when I retrieve it, So for example:



Stored in the Db, and when retrieved
Username: Ben
Password: PassWord


But when I query it, I can search for



SELECT * FROM TableName WHERE Username = 'ben' AND Password = 'password';


And there is no restriction on font case. Is there a way to set it so that if the above query is used, it will return nothing, but if I use



SELECT * FROM TableName WHERE Username = 'Ben' and Password = 'PassWord';


ONLY this will return the data?



asked 55 secs ago

Ben

367





Pig Manipulation in a relation


Vote count:

0




A = ( 1 2 3 4 1 2 4 5 1 2 5 6 1 5 2 3 1 5 3 4 1 5 6 8 1 7 1 1 1 7 2 1 1 7 2 1 )


I need B as 1 2 3 4 1 5 2 3 1 7 1 1 Basically any one distinct row from each group)



asked 1 min ago






using opencv backgroundSubtractorGMG to track moving and stationary objects


Vote count:

0




I am using backgroundSubtractorGMG from opencv 2.4.8 , using c++ in linux. I am also working only with grayscale images.


The specific subtractor is aimed to be used in variable light , video art installations, which is what I want to do too.


I am tweaking the values "decisionThreshold" and "learningRate" , in an attempt to find optimum settings for what I am trying to do.


What I try to implement is a human tracking mechanism. The human will not be moving all the time though. This affects me because the GMG seems to incorporate in the background , anything that is standing still in a frame for more than 3-4 seconds. How can I increase this time?Additionally, tweaking decisionThreshold and learningRate, does not have a significant effect on altering this bit.


What is more , once the tracked object (1 blob) has come to rest , after the 3-4 seconds, it starts to fade out , (dark spots appear and grow quickly). As these grow, the contour finder starts detecting more than just one object. This is also unwanted behaviour and I wonder if there are some settings I could use to fix this.


What can avoid



asked 31 secs ago

nass

166





Columns Not Centering (CSS Formatting Issue)


Vote count:

0




There is so much code going on here I'm not sure what to actually post, so I'm just going to post the link, even though I've been told it's not the best way to go.


The link is live here: http://ift.tt/R4eRtu


At the very bottom of the page those three boxes should be centered (The Problem, The Needs, The Solution.) Any help would be greatly appreciated, I can't figure anything out by centering the DIVs, it always seems to mess it up.


Thank you very much in advance.



asked 37 secs ago

Eric

26





todays date and future date dropdown list in a ComboBox


Vote count:

0




every time i start up the file and click the macro for the userform, the combobox should have the list of dates from today and future dates, it can not have past dates.


this is the code that I have, it only inputs the date in the combobox and formats the value of the list. but i don't know how to list down the future dates in it.



Public Sub UserForm_initialize()
ComboBox3.Value = Format(Date, "dd/mm/yyyy")
ComboBox3.Value = Format(ComboBox3.Value, "dd/mm/yyyy")
End Sub


asked 43 secs ago






Regular expression is not working right


Vote count:

0




I am trying to use the regular expression to target the time and add text to it. But my regular expression have problem when i have break. If i remove the break and test the expression it is working.


2)after i have scanned the matching expression how do i add text infront and behind of the targeted text ? TQ



var str = "00:00:01.120
In this lesson, we will learn how to determine the equation of a line, using the available information.

00:00:08.040
Let's look at the first example. Determine the equation of the line, that passes through the points (2, 5), and with the slope of 2.

00:00:19.000
To begin, we should know that the equation of a line can be written in the form of y = mx + b, where m is the slope, and b is the y-intercept.";


var patt1 = /(\d\d.\d\d.\d\d.\d\d\d)/gm;
var result = str.match(patt1);


asked 33 secs ago






Running a PowerShell script as a scheduled task produces different results


Vote count:

0




I am running Windows Server 2012 used as an admin server. Here I have it setup to run PowerShell scrips as scheduled tasks to do various tasks on remote servers using Windows Remote Management aka Remote PowerShell.


The following script is one of 4 scripts, where underneath ############# everything stays exactly the same. Above ############# is where I set the different variables to run against different servers.


I have a problem where if I run one of the 4 scripts as a scheduled task, it persists in telling me the opposite result to what the result should be. All other scheduled task scripts run perfectly giving expected results. This script runs perfectly with expected results if I run it from PowerShell ISE an email to say the adfssrv service is running. However when this exact script is run using a scheduled task, I get an email to say the adfssrv service isn't running and it waits for 15 minutes before telling me again in an email that the adfssrv service is not running.


The Scheduled task is setup exactly the same as the others, powershell.exe -command c:\Scripts\XA-US-FS-02_adfssrv.ps1 with all scripts locacted in the exact same local directory c:\Scripts



$FirstCheck = @()
$arrService = @()
$computername = @()
$MyHost = @()
$cred = @()
$password = @()
$cmdAutoAdmin = @()
$WinRMPort = @()
$password = ConvertTo-SecureString "some_password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("xa-us-fs-02\svc.tasks", $password )
$computername = "xa-us-fs-02.cloudapp.net"
$cmdAutoAdmin = {Get-Service -Name adfssrv}
$WinRMPort = 61573
$MyHost = "XA-US-FS-02"

$mytime = Get-Date -displayhint time
$SMTPServer = "smtp.sendgrid.net"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true

$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("User", "SendGridPassword");
$EmailFrom = "Email_Alerts@xyz.com"
$EmailTo = "receiver@xyz.com"

#########################################

$arrService = Invoke-Command -ComputerName $computername -Port $WinRMPort -Credential $cred -UseSSL -ScriptBlock $cmdAutoAdmin

if ($arrService.Status -eq "Running"){
$Subject = "$MyHost - ADFS service"
$Body = "Hi, I just checked the ADFS service (adfssrv) on $MyHost at $mytime and it is running :)"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
$FirstCheck = "Success"
}

elseif ($arrService.Status -ne "Running"){
Invoke-Command -ComputerName $computername -Port $WinRMPort -Credential $cred -UseSSL -ScriptBlock {Start-Service -Name adfssrv}
$Subject = "$MyHost - ADFS NOT RUNNING"
$Body = "This is an email to say that the ADFS service on $MyHost was checked at $mytime and it was not started. `
I have attempted to start the ADFS service just now. `
I will check again in 15 minutes"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Start-Sleep -Seconds 900
}
if ($arrService.Status -ne "Running" -and $FirstCheck -ne "Success"){
$Subject = "$MyHost - ADFS NOT RUNNING AGAIN!"
$Body = "This is the SECOND email to say that the ADFS service on $MyHost was checked at $mytime and it was not started. `
Manual human intervention required"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
elseif ($arrService.Status -eq "Running" -and $FirstCheck -ne "Success"){
$Subject = "$MyHost - ADFS service"
$Body = "Hi, I just checked the ADFS service (adfssrv) for a SECOND time on $MyHost at $mytime and it is now running :)"
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}


asked 34 secs ago






Am trying to plot the magnitude of a complex function in MATLAB


Vote count:

0




This is my code so far:



sigma = -8:0.1:0;
omega = -10:0.1:10;

[x,y] = meshgrid(sigma, omega);

s = x + y*j;

zz = (5^2)./(s.^2 + 2*0.4*5.*s + 5^2);
xx = real(s);
yy = imag(s);
surf(xx,yy,zz);


I am getting the error that I can not use a complex variable in the surf function. I know the issue is in the zz variable, but I do not know how to find the magnitude of a complex function.



asked 35 secs ago






Copy char array into array of character pointers


Vote count:

0




I am having problems trying to copy the contents of a char array into an array of char pointers in C. My code is listed below:



# include<stdio.h>
# include<stdlib.h>
# include<string.h>

# define RECORD_SIZE 300
# define BUFFER_SIZE 3

/* Structure for representing a single
* password entry */
typedef struct Record {
char * sitename;
char * username;
char * password;
struct Record * next;
} Record;

/* Declare function prototypes */
int isCorrectKey(char *,char *);
int isValidOperation(char);
int isValidSyntax(char *);
void getFields(char *,char * []);
void listEntries();
int updateEntries(char *);
int deleteEntries(char *);
int entryExists(char *);
void init(char *,char *,char *);
void readDB();
void writeToDB(char *);
void encrypt(char *,char * [],char *);
void decrypt(char *,char * [],char *);

/* Declare global variables */
char * database;
Record * records;

// Pre-condition: A character pointer to plaintext
// A character pointer to an empty buffer,
// A character pointer to the user input key
// Post-condition: The plaintext is encrypted and
// inserted into the buffer
void encrypt(char * text,char * buffer[BUFFER_SIZE],char * key) {
int i = 0;

for(;i < strlen(text);i++) {
buffer[i] = ((char *) (text[i]+3));
}
buffer[i] = 0;
}

// Pre-condition: A character pointer to ciphertext
// A character pointer to an empty buffer
// A character pointer tothe user input key
// Post-condition: The ciphertext is decrypted and
// inserted into the buffer
void decrypt(char * text,char * buffer[BUFFER_SIZE],char * key) {
int i = 0;

for(;i < strlen(text);i++) {
buffer[i] = ((char *) (text[i]-3));
}
buffer[i] = 0;
}

// Pre-condition: The database variable must be set
// The records variable must exist
// Post-condition: The value in database variable is
// used as filename to read the data. The data that
// is read and used to initialize the records variable
void readDB() {
// Open the file in read-only mode
FILE * f = fopen(database,"r");
char buffer[BUFFER_SIZE];
int index = 0;

if(f == NULL) {
// Print error if file is invalid
printf("Sorry. Unable to find password database.");
} else {
char c = 0;
// Read the file
while((c = fgetc(f)) != EOF) {
if(c != '\n') {
buffer[index++] = c;
} else {
buffer[index] = 0; // terminate each entry with null
index = 0;
}
}
fclose(f); // Close the file handle
}
}

// Pre-condition: The database variable must be set
// A character pointer to some text must be provided
// as input
// Post-condition: The value in database variable is
// used as filename to write the data.
void writeToDB(char * text) {
// Open the file in append mode
FILE * f = fopen(database,"a");
int index = 0;

if(f == NULL) {
// Print error if file is invalid
printf("Sorry. Unable to find password database.");
} else {
fputs(text,f); // Write to the file
fclose(f); // Close the file handle
}
}

// Pre-condition: A character pointer to the user input key
// A character pointer to the actual key
// The records variable must be set
// Post-condition: Returns 1 if the key value in the records variable
// has been properly decrypted.
// Returns 0 otherwise.
int isCorrectKey(char * uKey,char * mkey) {
return strcmp("ThisIsTheSecretKey",records->password);
}

// Pre-condition: A character indicating an operation value
// Post-condition: Returns 1 if the operation value is supported
// Returns 0 otherwise.
int isValidOperation(char operation) {
return operation == 'L' || operation == 'U' || operation == 'D';
}

// Pre-condition: A character pointer to a user input command string
// Post-condition: Returns 1 if the syntax of the command is correct
int isValidSyntax(char * command) {
return 0;
}

// Pre-condition: A character pointer to a comma delimited string
// Post-condition: The string is split into segments and stored into the buffer
void getFields(char * record,char * buffer[BUFFER_SIZE]) {
int i = 0;
int buffer_i = 0;
int record_len = strlen(record);
char tmp_buffer[RECORD_SIZE+1];
int tmp_i = 0;

for(;i < record_len;i++) {
if(record[i] != ',') {
tmp_buffer[tmp_i++] = record[i];
} else {
tmp_buffer[tmp_i] = 0;
strcpy(buffer[buffer_i++],tmp_buffer);
tmp_i = 0;
}
}
}

int main(int argc,char * argv[]) {
//database = "test.txt";
//readDB();
char * buffer[BUFFER_SIZE];
getFields("google,geek,pass123",buffer);

int i = 0;

for(;i<BUFFER_SIZE;i++) {
printf(buffer[i]);
printf("\n");
}

return 0;
}


From what I see, the offending line is in the getFields() function:



strcpy(buffer[buffer_i++],tmp_buffer);


I am trying to copy the contents of tmp_buffer into the indexes of buffer. My program just keeps crashing. I don't know why. Could someone please help me? Thanks.



asked 17 secs ago