input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Load preset directory in Maya with python/MEL? <p>I have a folder where I'm storing some maya presets (specifically nCloth presets) and I would like to make this directory available to all of the users on my current network. To do this, I would like to have this folder added to the MAYA_PRESET_PATH on startup. However, I am not able to create/modify the maya.env file (restricted permissions on network). So, is there a way to append a directory to maya's environment variables using python or MEL, so that I can call a script on startup to dynamically load all of my presets? </p>
<p>I tried the following in my startup MEL script, but to no avail...</p>
<pre><code>python("PRESET_DIR = os.environ.get('MAYA_CUSTOM_PRESET_DIR')"); //Path to my custom preset directory
python("PRESET_DIR = os.environ.get('MAYA_PRESET_PATH') + ':' + PRESET_DIR");
python("os.putenv('MAYA_PRESET_PATH', PRESET_DIR)");
</code></pre>
| <p>save the code as filename.bat file, running via double click. you have to refactor the paths to your own environment. its a simple example, if you have other artists out of your scope, you should check that the Paths are matching for example that everybody who start maya with this batch should have maya installed on C:\Program Files\Autodesk\Maya2016\bin .</p>
<pre><code>set "pluginsMaya=X:\100_Software\plugins_maya"
rem Pipeline
set "MAYA_MODULE_PATH=%MAYA_MODULE_PATH%;%pluginsMaya%\intern"
set "MAYA_SHELF_PATH=%MAYA_SHELF_PATH%;%pluginsMaya%\intern\shelves"
set "XBMLANGPATH=X:/100_Software/graphics/splashscreens";%XBMLANGPATH%
set "MAYA_PROJECT=%pluginsMaya%/fakeMayaRoot"
rem make maya Quicker?
set "MAYA_DISABLE_CIP=1"
set "MAYA_DISABLE_CER=1"
rem Start Maya
set "PATH=C:\Program Files\Autodesk\Maya2016\bin;%PATH%"
start maya -file %1 -script %pluginsMaya%\intern\startupScript.mel
</code></pre>
|
Python "list index out of range" other rule works <p>I have tried to make a script to read out a csv file and determine some information.</p>
<p>Now I receive an error: </p>
<pre><code>Traceback (most recent call last):
File "/home/pi/vullijst/vullijst.py", line 26, in <module>
startdate = datetime.datetime.strptime (row[0],"%d-%m-%Y")
IndexError: list index out of range
</code></pre>
<p>Part of Script:</p>
<pre><code>import csv
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#Variabelen
smtpserver = ''
smtplogin = ''
smtppassword = ''
sender = ''
csvfile = '/home/pi/vullijst/vullijst.csv'
#Inlezen CSV File
f = open(csvfile)
csv_f = csv.reader(f, delimiter=';')
today = datetime.datetime.now()
#Tijd bepalen en opstellen E-mail
for row in csv_f:
startdate = datetime.datetime.strptime (row[0],"%d-%m-%Y")
enddate = datetime.datetime.strptime (row[1],"%d-%m-%Y")
if today >= startdate and today <= enddate:
receiver = row[3]
</code></pre>
<p>The csv file has the following structure:</p>
<pre><code>1-10-2016;12-10-2016;Test 1;test0@email.com;06-123456789
12-10-2016;13-10-2016;Test 2;test1@email.com;06-123456789
13-10-2016;14-10-2016;Test 3;test2@email.com;06-123456789
14-10-2016;15-10-2016;Test 4;test3@email.com;06-123456790
15-10-2016;16-10-2016;Test 5;test4@email.com;06-123456791
16-10-2016;17-10-2016;Test 6;test5@email.com;06-123456792
17-10-2016;18-10-2016;Test 7;test6@email.com;06-123456793
</code></pre>
<p>If I comment out this rule then I don't receive the error on the rule below. Does somebody know what is wrong?</p>
| <p>Your csv file appears to have an empty line at the end, after the last row with real data. So your script reads all the real lines and processes them, but it breaks when the last line is parsed into an empty list. The <code>row[0]</code> you're trying to parse into a date isn't valid in that situation.</p>
<p>To avoid this issue, put a check at the top of your loop that skips the rest of the loop body if <code>row</code> is empty.</p>
<pre><code>for row in csv_f:
if not row: # skip empty rows
continue
startdate = datetime.datetime.strptime (row[0],"%d-%m-%Y")
# ...
</code></pre>
|
Python: Connecting list values with array values <p>I have created a tornado plot taking inspiration from <a href="http://stackoverflow.com/questions/32132773/a-tornado-chart-and-p10-p90-in-python-matplotlib">here</a>. It has input variables labelled on the y-axis (a1,b1,c1...) and their respective correlation coefficients plotted next to them. See pic below:</p>
<p><a href="https://i.stack.imgur.com/4NE3f.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/4NE3f.jpg" alt="enter image description here"></a></p>
<p>I then sorted the correlation coefficients in a way that the highest absolute value without loosing its sign gets plotted first, then the next highest and so on. using <code>sorted(values,key=abs, reverse=True)</code>. See the result below</p>
<p><a href="https://i.stack.imgur.com/xamYL.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/xamYL.jpg" alt="enter image description here"></a></p>
<p>If you notice, in the second pic even though the bars were sorted in the absolute descending order, the y-axis label still stay the same.</p>
<p>Question: How do I make the y-axis label(variable) connect to the correlation coefficient such that it always corresponds to its correlation coefficient.</p>
<p>Below is my code:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
#####Importing Data from csv file#####
dataset1 = np.genfromtxt('dataSet1.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
dataset2 = np.genfromtxt('dataSet2.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
dataset3 = np.genfromtxt('dataSet3.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
corr1 = np.corrcoef(dataset1['a'],dataset1['x0'])
corr2 = np.corrcoef(dataset1['b'],dataset1['x0'])
corr3 = np.corrcoef(dataset1['c'],dataset1['x0'])
corr4 = np.corrcoef(dataset2['a'],dataset2['x0'])
corr5 = np.corrcoef(dataset2['b'],dataset2['x0'])
corr6 = np.corrcoef(dataset2['c'],dataset2['x0'])
corr7 = np.corrcoef(dataset3['a'],dataset3['x0'])
corr8 = np.corrcoef(dataset3['b'],dataset3['x0'])
corr9 = np.corrcoef(dataset3['c'],dataset3['x0'])
np.set_printoptions(precision=4)
variables = ['a1','b1','c1','a2','b2','c2','a3','b3','c3']
base = 0
values = np.array([corr1[0,1],corr2[0,1],corr3[0,1],
corr4[0,1],corr5[0,1],corr6[0,1],
corr7[0,1],corr8[0,1],corr9[0,1]])
values = sorted(values,key=abs, reverse=True)
# The y position for each variable
ys = range(len(values))[::-1] # top to bottom
# Plot the bars, one by one
for y, value in zip(ys, values):
high_width = base + value
#print high_width
# Each bar is a "broken" horizontal bar chart
plt.broken_barh(
[(base, high_width)],
(y - 0.4, 0.8),
facecolors=['red', 'red'], # Try different colors if you like
edgecolors=['black', 'black'],
linewidth=1)
# Draw a vertical line down the middle
plt.axvline(base, color='black')
# Position the x-axis on the top/bottom, hide all the other spines (=axis lines)
axes = plt.gca() # (gca = get current axes)
axes.spines['left'].set_visible(False)
axes.spines['right'].set_visible(False)
axes.spines['top'].set_visible(False)
axes.xaxis.set_ticks_position('bottom')
# Make the y-axis display the variables
plt.yticks(ys, variables)
plt.ylim(-2, len(variables))
plt.show()
</code></pre>
<p>Many thanks in advance</p>
| <p>use build-in zip function - returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. But aware the returned list is truncated in length to the length of the shortest argument sequence.</p>
|
I can't integrate a Web Template purchased into Meteor <p>thanks for read</p>
<p>I have a problem, I hope some orientation because always I worked only with bootstrap. Never with css, js, or templates. But this case is diferent.</p>
<p>I bought a template in wrapbootstrap.com
As you know, this templates coming with a big set number files like a js, img, fonts, and of course html. Of course not always this packages are in NPM, and that is all a problem, because if only one missing file, for some reason many components dont work as well like I expect. So, the solution is, although no elegant but efective, is copy and paste these files that I bought in a correct directory in meteor. </p>
<p>I need integrate this template into meteor, I find in web tha <code>Meteor.startup()</code> help. This code help a little to solve, but no solve the problem.</p>
<p>I have the next issue:
Sometimes the template is good, works fine and very well, sometimes is very, very bad and infinite erros.
Next a img</p>
<p><a href="https://i.stack.imgur.com/s8evt.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/s8evt.jpg" alt="sometimes good, sometimes bad"></a></p>
<p>As you can see: Window on right is perfect, everithings well. The window on left is bad, and with errors. <strong>Why?</strong> sometimes good, sometimes bad</p>
<p>next my file structure:</p>
<p><a href="https://i.stack.imgur.com/kRzMs.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/kRzMs.jpg" alt="My file structure"></a></p>
<p>my file <strong>client/main.js</strong> has the next lines:</p>
<pre><code>import angular from 'angular';
import angularMeteor from 'angular-meteor';
import uiRouter from 'angular-ui-router';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap.js';
import {name as Inicio} from '../imports/ui/components/views/inicio/inicio';
class Main {} // EMPYT
Meteor.startup(function () {$.getScript('js/jquery-2.1.3.min.js', function () {});});
Meteor.startup(function () {$.getScript('bootstrap/js/bootstrap.min.js', function () {});});
Meteor.startup(function () {$.getScript('js/jquery.superslides.min.js', function () {});});
Meteor.startup(function () {$.getScript('js/jquery.mb.YTPlayer.min.js', function () {});});
Meteor.startup(function () {$.getScript('js/jquery.magnific-popup.min.js', function () {});});
Meteor.startup(function () {$.getScript('js/owl.carousel.min.js', function () {});});
Meteor.startup(function () {$.getScript('js/jquery.simple-text-rotator.min.js', function () {});});
Meteor.startup(function () {$.getScript('js/imagesloaded.pkgd.js', function () {});});
Meteor.startup(function () {$.getScript('js/isotope.pkgd.min.js', function () {});});
Meteor.startup(function () {$.getScript('js/packery-mode.pkgd.min.js', function () {});});
Meteor.startup(function () {$.getScript('js/appear.js', function () {});});
Meteor.startup(function () {$.getScript('js/jquery.easing.1.3.js', function () {});});
Meteor.startup(function () {$.getScript('js/wow.min.js', function () {});});
Meteor.startup(function () {$.getScript('js/jqBootstrapValidation.js', function () {});});
Meteor.startup(function () {$.getScript('js/jquery.fitvids.js', function () {});});
Meteor.startup(function () {$.getScript('js/jquery.parallax-1.1.3.js', function () {});});
Meteor.startup(function () {$.getScript('js/smoothscroll.js', function () {});});
Meteor.startup(function () {$.getScript('http://maps.google.com/maps/api/js?sensor=true', function () {});});
Meteor.startup(function () {$.getScript('js/gmaps.js', function () {});});
Meteor.startup(function () {$.getScript('js/contact.js', function () {});});
Meteor.startup(function () {$.getScript('js/custom.js', function () {});});
const name = 'main';
export default angular.module('myApp', [
angularMeteor,
uiRouter,
Inicio
])
.config(config);
function config($locationProvider, $urlRouterProvider, $stateProvider) {
'ngInject';
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/inicio');
}
</code></pre>
<p>My questions:</p>
<ul>
<li><strong>Is a good way to import files like this?</strong> </li>
<li><strong>Iam doing something wrong?</strong></li>
<li><strong>Exist other way?</strong></li>
</ul>
<p>Please need help, due I don't understand the File Structure documentation.
I need a example.
Thanks for your time and read</p>
<p>Aditional notes:</p>
<ul>
<li>My file <code>client/main.less</code> is empyt, no conflict with it </li>
<li><code>/lib</code> directory is empyt </li>
<li>Am working with Angular, AngularMeteor, UiRoute</li>
<li>For now, all html is in <code>imports\ui\components\views\inicio\inicio.html</code></li>
<li>Imposible rename the js files with a number before the name, like _1appear.js, the template don't works that way</li>
<li>The load order is like the template indicates, like as my <code>client/main.js</code> has.</li>
<li>If I put my js files into a <code>client/compatibility</code> appear more errors.</li>
<li>I new in Meteor but not in Tempaltes Web, I integrated more templates in fullstack with yeoman and grunt, no problems, but in meteor is very dificult.</li>
</ul>
| <p>You need to port those files to use modules (or find already-wrapped versions on npm), so that they can be bundled up in the correct order with the rest of your JS code.</p>
|
Resizing window always trigger a click event <p>I have a bootstrap sidebar that can be toggled into a narrow icon bar, and now I am required to show the sidebar when screen height is greater than 768, and to a narrow side bar when height is lower than 768. But my script appears to be triggering a click event when lower than 768, therefore if I resize the screen multiple times, and when height reaches lower than 768, it continuously toggles the sidebar multiple times. If the height reaches greater than 768, the toggling stops.</p>
<p>My code is:</p>
<pre><code>$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
$("span", this).toggleClass("fa fa-lock fa fa-unlock");
});
$("#menu-toggle-2").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled-2");
$("span", this).toggleClass("fa fa-lock fa fa-unlock");
});
$(document).ready(function() {
var $window = $(window);
// Function to handle changes to style classes based on window width
function checkWidth() {
if ($window.height() <= 768) {
$("#wrapper").toggleClass("toggled-2");
}
else if ($window.height() > 768) {
$("#wrapper").toggleClass("toggled");
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});
</code></pre>
<p>Any help is appreciated and thanks in advance.</p>
| <p>Are you sure the click event is triggering? (Try making a log inside the click function(s) to confirm using <code>console.log</code>)</p>
<p>Based on the code you posted it looks like <code>resize</code> may be firing multiple times as you resize the window.</p>
<p>Try using the following:</p>
<pre><code>$(window).resize($.throttle(checkWidth, 300));
</code></pre>
<p>Throttle returns a new function that executes no more than once every 300ms (or whatever delay you decide to set)</p>
<p>Note: This uses jQuery debounce/throttle plugin</p>
<p><a href="https://code.google.com/archive/p/jquery-debounce/" rel="nofollow">https://code.google.com/archive/p/jquery-debounce/</a></p>
|
excel VBA worksheet_activate method not working correctly <p>I have a spreadsheet with a small Subroutine in it that should do three things when the tab for the sheet "Template" is clicked:
1. make a copy of the "Template" sheet and place it before the original "Template" sheet
2. change the name of the copied sheet to be today's date (10-13-2016)
3. change the contents of cell B1 to be today's date (Thursday, Oct 13, 2016)</p>
<p>The code listed below does these things sort of. The two things I need help on is this:
1. to get the sheet to copy I have to click another sheet and then click back on the "Template" sheet. I'd like to be able to just click the "Template" tab and have it create the copy, even if the "Template" sheet is already the active sheet.
2. for some reason the VBA code prevents me from deleting the tab that is created when you click the "Template" tab.</p>
<pre><code>Private Sub Worksheet_Activate()
Application.EnableEvents = False
If ActiveSheet.Name = "Template" Then
Worksheets("Template").Copy before:=Worksheets("Template")
ActiveSheet.Range("B2").Select
ActiveCell.FormulaR1C1 = Format(Date, "dddd, mmm d, yyyy")
ActiveSheet.Name = Format(Date, "mm-dd-yyyy")
End If
Application.EnableEvents = True
End Sub
</code></pre>
<p>I know this is probably very simple but I haven't been able to find any reference to this behavior anywhere. Any and all help will be much appreciated. </p>
| <p>you wouldn't use <code>Worksheet_Activate()</code> because it would be copied along with the worksheets copies, thus having copied worksheets generate other worksheets</p>
<p>so you want to use <code>Workbook_SheetActivate()</code> event handler</p>
<p>even then, you must be aware that upon deleting a sheet just preceeding "Template", the active sheet becomes "Template" (i.e.the next one) thus activating the cloning procedure and making it seem as if <em>"VBA code prevents" you "from deleting the tab"</em></p>
<p>then type this code in ThisWorkBook code pane:</p>
<pre><code>Option Explicit
Dim nextShtName As String
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim newName As String
If nextShtName = "Template" Then
nextShtName = ""
Else
If Sh.Name = "Template" Then
newName = Format(Date, "mm-dd-yyyy")
If GetSheet(newName) Is Nothing Then
Application.EnableEvents = False
On Error GoTo exitsub
Sh.Copy before:=Worksheets("Template")
With ActiveSheet
.Range("B2").FormulaR1C1 = Format(Date, "dddd, mmm d, yyyy")
.Name = newName
End With
exitsub:
Application.EnableEvents = True
Else
MsgBox "sheet '" & newName & "' already in this workbook", vbInformation
End If
End If
End If
End Sub
Function GetSheet(shtName As String) As Worksheet
On Error Resume Next
Set GetSheet = Worksheets(shtName)
End Function
Private Sub Workbook_SheetBeforeDelete(ByVal Sh As Object)
Dim i As Long
For i = 1 To Worksheets.Count
If Worksheets(i).Name = Sh.Name Then Exit For
Next i
nextShtName = Worksheets(i + 1).Name
End Sub
</code></pre>
|
The database and links aren't working <p>I have been trying to use Javascript and jQuery to make a subdomain for my website that has only one page. I had it working perfectly when all of the code was completely on the one page. When I tried to make it so that the script pulled from outside pages, two of the functions stopped working. They just replace the targeted div with nothing. Here's the code:</p>
<pre><code><script>
function homeFunc() {
$("#main").load("oldhome.html #mainpage");
}
function rulesFunc() {
$("#main").load("rules.html #rulespage");
}
function databaseFunc() {
$("#main").load("database.html #databasepage");
}
function linksFunc() {
$("#main").load("links.html #linkspage");
}
$("#main").ready(homeFunc);
$("#home").click(homeFunc);
$("#rules").click(rulesFunc);
$("#database").click(databaseFunc);
$("#links").click(linksFunc);
</script>
</code></pre>
<p>Edit: This seems to work correctly on every browser but Chrome for Windows.</p>
| <p>Your code has to be execute after the DOM is ready.</p>
<pre><code>$( document ).ready(function() {
// your code here
});
</code></pre>
<p>or </p>
<pre><code>$(function() {
// code here
})
</code></pre>
|
Quickest way to implement a server side alarm with Firebase and Ionic <p>I'm currently developing an app with Ionic/AngularJS/Firebase, basically I store user's alarm clocks in a Firebase DB and I want to send a notification when the time elapses.</p>
<p>What is the most efficient way to achieve this? How do I run a job that constantly checks to see if there is an alarm that needs to be triggered?</p>
<p>I've looked into Firebase Queue but doesn't quite do what I want, NodeJS will probably work but I'd have to develop the logic from scratch. </p>
| <p>I would actually suggest giving <a href="https://syncano.io" rel="nofollow">Syncano</a> a try. With Syncano, you can set up a Schedule which, at a time selected by you, will run a NodeJS script that you wrote on a server you don't have to manage. It's the best way to get what you're looking for up and running as soon as possible. It's also a very similar service to Firebase, so it won't be much of a transition if you already use it.</p>
<p>This blog post will explain Schedules more: <a href="https://www.syncano.io/blog/build-hacker-news-clone-with-syncano-part-2/" rel="nofollow">https://www.syncano.io/blog/build-hacker-news-clone-with-syncano-part-2/</a></p>
<p><em>Disclaimer: I'm a developer at Syncano</em></p>
|
javascript getAllResponseHeaders() - how to view '[native code]'? <p>I am doing an AJAX call and attempting to retrieve the response headers. </p>
<p>MY code:</p>
<pre><code> var xmh = new XMLHttpRequest;
xmh.getAllResponseHeaders
</code></pre>
<p>I am trying to view the headers in the console and what I am getting back is '[native code]'. Please could someone advise me on how to view the headers? This question is specific and not a generalised one like the proposed solutions that someone has mentioned as a duplicate.</p>
| <p>This is because you are inspecting the function itself, whereas you want to first invoke the function, and then inspect it's return value.</p>
<p>Try updating to:</p>
<pre><code>xmh.getAllResponseHeaders();
</code></pre>
|
Redirect from image to script <p>please help me with redirect in .htaccess
Iam have simple link</p>
<p><a href="http://domain.com/" rel="nofollow">http://domain.com/</a><em>test123</em>/<em>image-123.gif</em></p>
<p>Iam need to redirect from this image to script.</p>
<p><a href="http://domain.com/test.php?company=" rel="nofollow">http://domain.com/test.php?company=</a><em>test123</em>?image=<em>image-123.gif</em></p>
<p>My example doesnt work =(</p>
<pre><code>RewriteEngine On
RewriteRule ^(.+)/(.+).\gif$ tracking.php?company=$1&email=$2 [L,QSA]
</code></pre>
| <p>Assuming this is literally what you have in a .htaccess file, the problem is that you have .\g rather than .g -- that is, you've escaped the 'g' character, rather than the . character.</p>
<p>That is, what you want is:</p>
<pre><code> RewriteRule ^(.+)/(.+)\.gif$ tracking.php?company=$1&email=$2 [PT,L,QSA]
</code></pre>
<p>Also, note that this does not <em>redirect</em>, as you say in your question, but it does a transparent rewrite. If you want it to <em>redirect</em>, replace the PT with a R in the flag.</p>
|
Listen to the click event with id/class or use the onclick in the link? <p>To run javaScript/jQuery I can do it with click event with id/class/data like this and get the values to use in the function with <code>$(this).data("id");</code></p>
<pre><code><div data-id="@item.PostId" data-vote="up" id="vote-up " class="vote-arrow glyphicon glyphicon-chevron-up"></div>
$(".vote-arrow").click(function () {
var postId = $(this).data("id");
var vote = $(this).data("vote");
....
...
}
</code></pre>
<p>or add <code>onclick</code> and in the html code and pass the values as parameter like this</p>
<pre><code><input type="button" title="Up" class="up" onClick="addVote(1, 1)" />
function addVote(id,vote_rank) {
$.ajax({
....
}
</code></pre>
<p>The results will be the same but what is best and when to use what? Using OnClick in the html code and send values as parameter or listen to when the user clicks on the ID/class and retrieve the values with <code>$(this).data("id");</code>?</p>
| <blockquote>
<p>It's generally considered âbadâ to use <code>onclick</code> for a number of reasons:</p>
<ul>
<li>you're mixing small pieces of JavaScript syntax inline with HTML syntax:
<ul>
<li>when you have lots of these, especially when you have lots of elements that all > contain essentially the same bit of code, it's harder to read and maintain the code;</li>
<li>you get nested-escaping horrors when you need to use special-to-HTML characters in your code:</li>
</ul></li>
</ul>
</blockquote>
<p>See <a href="http://stackoverflow.com/a/6888785/4575054">this answer</a>.</p>
|
Redgate DLM Automation - deploy database to multiple environments <p>I am using Redgare DLM Automation for database CI in a SQL Server and Visual Studio Team Services environment. I can easily deploy to multiple databases in a single environment, but apparently DLM Automation does not support multiple environments out of the box. Redgate support suggested using VSTS post-scripts in PowerShell, sqlcmd or something called "account_y" (I'm not sure what this refers to) to potentially add multiple environments.</p>
<p>Has anyone tried using DLM Automation for multiple environments? I have explored the PowerShell CmdLets, looked at SQL Compare options and filters, thought about using VSTS's Tokenizer for script alterations, but am still struggling with how to put all of this together to deploy to more than one environment.</p>
<p>Any experience or guidance would be greatly appreciated.</p>
<p>Thank you!</p>
| <p>You definitely can deploy to multiple environments, however the issue of needing different user accounts for different environments is not a trivial problem to solve. Ultimately whatever you source control will be deployed to each environment, so if you need different user accounts then you will need to take care of it yourself by using some sort of post-deployment script.</p>
<p>I would suggest not source controlling user accounts and then adding a custom step after deployment to add the users - either command line using sqlcmd or the equivalent powershell cmdlets.</p>
<p>There are some blog posts that go into detail regarding this problem and their answers are probably more detailed than anything I can provide. I'd suggest that you have a read of them.</p>
<ul>
<li><a href="https://www.red-gate.com/blog/building/source-controlling-database-permissions" rel="nofollow">https://www.red-gate.com/blog/building/source-controlling-database-permissions</a></li>
<li><a href="http://workingwithdevs.com/source-controlling-database-users/" rel="nofollow">http://workingwithdevs.com/source-controlling-database-users/</a></li>
</ul>
<p>I hope this helps.</p>
|
Android viewpager fragment <p>I need to create an app with one activity and 3 fragments in it. Pages don't need to be dynamically created but its a plus. My question is: do I need a separate fragment for every view or I can reuse one with different view?I've read the android tutorial here <a href="https://developer.android.com/training/animation/screen-slide.html#viewpager" rel="nofollow">https://developer.android.com/training/animation/screen-slide.html#viewpager</a>
for view pager and it left me with that impression. Its an important project. I am a noob so pls explain for such.</p>
| <p>I'm assuming you want 3 full screen fragments. Use a <code>ViewPager</code> with a <code>FragmentPagerAdapter</code>.</p>
<pre><code>public class MyFragment extends Fragment {
@BindView(R.id.view_pager)
ViewPager viewPager;
MyPagerAdapter pagerAdapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
pagerAdapter = new MyPagerAdapter(getFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
</code></pre>
<p><code>my_fragment.xml</code>:</p>
<pre><code><android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</code></pre>
<p><code>MyPagerAdapter.java</code>:</p>
<pre><code>public class MyPagerAdapter extends FragmentPagerAdapter {
static final int NUM_PAGES = 3;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
}
}
@Override
public int getCount() {
return NUM_PAGES;
}
}
</code></pre>
<p>This will allow swiping right or left to switch between the fragments. You will have to use a <code>TabLayout</code>, bottom navigation, buttons, or some other way to switch between them besides swiping. I'll leave that for you to figure out ;)</p>
|
iOS - how to write this objective-C into Swift? <p>How can i exactly do this in swift for iOS?</p>
<pre><code>- (IBAction)skypeMe:(id)sender
{
BOOL installed = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"skype:"]];
if(installed)
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"skype:echo123?call"]];
}
else
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.com/apps/skype/skype"]];
}
}
</code></pre>
| <p>In Swift you'd use the same framework calls with a different syntax. To write this in Swift,</p>
<ol>
<li>Look over the code for things that might be class names and/or method names</li>
<li>Look up those names in Apple's documentation</li>
<li>Apple's documentation will describe both Objective-C and Swift syntax</li>
</ol>
<p>For example, <code>UIApplication</code> exists regardless of which language you're using. It also has exactly the same methods in each language, though you use different coding syntax to call them.</p>
<p>You then write code that makes the same framework calls, but using Swift syntax instead of Objective-C.</p>
|
C# Manually Sorting Parent/Child tree elements in a list <p>I am attempting to generate a list of elements that would generate a tree structure if visualized.</p>
<p><strong>Example:</strong></p>
<pre><code>Element 1 -> 1, 0 //ID is 1 & Parent ID is 0 (0 = root)
Element 2 -> 2, 0 //ID is 2 & Parent ID is 0 (0 = root)
Element 3 -> 3, 1 //ID is 3 & Parent ID is 1
Element 4 -> 4, 3
Element 5 -> 5, 2
</code></pre>
<p>If a tree is to be visualized with this structure:</p>
<p><a href="https://i.stack.imgur.com/MFqPj.png" rel="nofollow"><img src="https://i.stack.imgur.com/MFqPj.png" alt="enter image description here"></a></p>
<p>To make this work, here's the Node Class:</p>
<pre><code>public class Node
{
public string id;
public string parentId;
public List<Node> children = new List<Node>();
}
</code></pre>
<blockquote>
<p>Similar to a tree, a node may contain a parent and it also may contain multiple other
children nodes</p>
</blockquote>
<p>The task is to sort the elements to their proper hierarchy & add child elements to their respective parent's children collection. There are 2 methods in my mind:</p>
<p><strong>1) The Loop Method</strong></p>
<p>i) Loop & find the Base/root nodes (nodes with parent as 0)</p>
<p>ii) Loop & find the nodes with the base nodes as their parent</p>
<p>iii) Add them to the base node's children collection</p>
<p>However the above method is best applicable for a tree of depth 2, meaning the root & their immediate child levels. Imagine a tree with multiple complex levels. This method won't work for that.</p>
<p>That's what I've tried so far.</p>
<p><strong>2) The 'Recursion' method</strong></p>
<p>The second method would be the 'Recursion' method. That's what I can't seem to figure out yet. Can anyone help me with this problem?</p>
<p>Has anyone attempted to solve this problem before? How can I arrange a list containing 'n' number of elements with their Parent ID & ID defined?</p>
| <p>If I understand correctly, you have a flat <code>List<Node></code> and you want to populate <code>children</code> property and end up with a list of the root nodes.</p>
<p>This can be achieved efficiently by building a fast lookup structure by <code>id</code> (like <code>Dictionary</code>) and single iteration over the source list. For each node you'll find the parent node and add the node to the parent <code>children</code> list (or to root list if there is no parent). The time complexity of the algorithm will be O(N).</p>
<pre><code>static List<Node> BuildTree(List<Node> nodes)
{
var nodeMap = nodes.ToDictionary(node => node.id);
var rootNodes = new List<Node>();
foreach (var node in nodes)
{
Node parent;
if (nodeMap.TryGetValue(node.parentId, out parent))
parent.children.Add(node);
else
rootNodes.Add(node);
}
return rootNodes;
}
</code></pre>
|
'CookieAuthenticationProvider' does not contain a definition for 'SlidingExpiration. Claims expiration time <p>So, I was trying to set expiration time on claims in mvc. That is the code:</p>
<pre><code>public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Main/LogIn"),
Provider = new CookieAuthenticationProvider
{
ExpireTimeSpan = TimeSpan.FromDays(5),
SlidingExpiration = true
}
});
}
}
</code></pre>
<p>And both, <code>ExpireTimeSpan</code> and <code>SlidingExpiration</code> are underlined with red saying that:<code>'CookieAuthenticationProvider' does not contain a definition for 'SlidingExpiration/ExpireTimeSpan'</code>. Claims expiration time.</p>
<p>I'm new to it and was wondering what am I doing wrong here or what should I do to fix this problem.</p>
| <p>They belong to <code>CookieAuthenticationOptions</code> instead of the provider. That should resolve it.
<a href="https://msdn.microsoft.com/en-us/library/microsoft.owin.security.cookies.cookieauthenticationoptions(v=vs.113).aspx" rel="nofollow">CookieAuthenticationOptions</a></p>
<pre><code>app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Main/LogIn"),
Provider = new CookieAuthenticationProvider(),
ExpireTimeSpan = TimeSpan.FromDays(5),
SlidingExpiration = true
});
</code></pre>
|
Moving reusable components outside project folder using Webpack React <p>I am building an application using Webpack and React.</p>
<p>my package.json is :</p>
<pre><code>{
"name": "v1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.17.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.16.0",
"babel-preset-react": "^6.16.0",
"react": "^15.3.2",
"react-dom": "^15.3.2",
"webpack": "^1.13.2"
}
}
</code></pre>
<p>webpack.config.js:</p>
<pre><code>var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, '');
var APP_DIR = path.resolve(__dirname, 'core');
var config = {
entry: APP_DIR + '/main.jsx',
output: {
path: BUILD_DIR,
filename: 'main.js'
},
module : {
loaders : [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
}
]
}
};
module.exports = config;
</code></pre>
<p>.babelrc:</p>
<pre><code>{"presets" : ["es2015", "react"]}
</code></pre>
<p>These files are in a folder that is nested, something like:</p>
<pre><code>root
| components
| | react
| | ember
| pages
| | | home
| | | about
</code></pre>
<p>The files I talked about are inside home. Basically home and about are 2 different npm projects and they have their own package.json as well as webpack.config.js and so on. But they need access to a react component called SearchBox in the file Searchbox.jsx the folder root/components/react.</p>
<p>When I try to access it from home , it shows an error saying:</p>
<blockquote>
<p>Module build failed: Error: Couldn't find preset "es2015" relative to
directory root/components/react</p>
</blockquote>
<p>So how do I solve this issue, or you may suggest any other ways I may use to make reusable components that are outside the project folder</p>
| <p>I solved this.
What I did was install the node modules in the react folder as well through npm install and put the .babelrc file there as well. It was trying to load the node_modules from the react directory, not home directory for SearchBox.jsx.</p>
<p>So if someone else encounter this issue, the way to solve it is to install all the node dependencies of your external file in either the file's own directory, or in some parent directory of the file. Thats where it fetches it from. </p>
|
If I copy a Folder with .git repo will it work independently of original? <p>If I copy a folder under git VC (with the appropriate .git subfolder) will this copy then "behave" independently of the original?</p>
<p>What if, instead, I MOVED the folder to a new location? Would it behave as it did previously? (I.e., the move doesn't affect anything)</p>
| <p>Yes. The folder with the .git directory is what makes it a git repository. If you copy the folder, you're making a copy of the local repository and it is completely independent of the original repository.</p>
<p>If you move a repository and do a <code>git status</code>, you'll notice that nothing is seen as having changed. Git does track if you move files or folders within the repository, but not the repository itself.</p>
|
Javascript - fetch elements from array dynamically <p>I have an array and i need to fetch elements from the array inside a loop. Let me explain,</p>
<pre><code>var globalArray = ['apple','orange','melon','banana'],
loopLimit = 5,
fruitsPerLoop = 3;
for (var i=1; i<=loopLimit; i++) {
// when the loop runs for the first time i need to grab the first 3 elements from the array since fruitsPerLoop is 3 and for the second time the next 3 (out of bound should be taken care) and for third time etc...
//Pseudo with fruitsPerLoop as 3
when i = 1 ==> globalArray should be ['apple','orange','melon']
i = 2 ==> globalArray should be ['banana', 'apple','orange']
i = 3 ==> globalArray should be ['melon','banana', 'apple']
i = 4 ==> globalArray should be ['orange','melon','banana']
i = 5 ==> globalArray should be ['apple','orange','melon']
}
</code></pre>
<p>I was referring underscore.js and trying to use some native methods as well but it breaks at some point. </p>
| <p>How about creating a recursive function to determine the index:-</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 globalArray = ['apple', 'orange', 'melon', 'banana'],
loopLimit = 5,
fruitsPerLoop = 3;
function getIndex(i, minus) {
var index = i - minus;
if (index < 0)
return getIndex(globalArray.length, minus - i)
return globalArray[index];
}
for (var i = 1; i <= loopLimit; i++) {
console.log([getIndex(1, i), getIndex(2, i), getIndex(3, i)])
}</code></pre>
</div>
</div>
</p>
|
Bi-directional association <p>The concept with association and also how it relates to the UML design. I would appreciate if some expert could give me an idea or code design relate to the UML picture attached.</p>
<p><a href="https://i.stack.imgur.com/L02ly.png" rel="nofollow"><img src="https://i.stack.imgur.com/L02ly.png" alt="There are 3 differently designed UML as seen below"></a></p>
<p>Thanks in adv!!!</p>
<pre class="lang-java prettyprint-override"><code>public class Borrower {
private String name;
public Borrower() {
Equipment[] tester = new Equipment[5];
tester[0] = new Equipment(this);
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>public class Equipment {
Borrower[] person = new Borrower[10];
public Equipment(Borrower b) {
person[0] = b;
}
}
</code></pre>
| <p>One possible solution is</p>
<pre><code>public class Loan {
private final Date date;
private final Borrower borrower;
private final Equipment equipment;
Loan(Borrower borrower, Equipment equipment, Date date) {
this.borrower = borrower;
this.equipment = equipment;
this.date = date;
}
}
public class Borrower {
private String name;
private final List<Loan> loans = new ArrayList<>();
public Borrower(String name, Equipment equipment, Date date) {
this.name = name;
borrow(equipment, date);
}
public void borrow(Equipment equipment, Date date) {
Loan loan = new Loan(this, equipment, date);
loans.add(loan);
equipment.addLoan(loan);
}
}
public class Equipment {
private final List<Loan> loans = new ArrayList<>();
void addLoan(Loan loan) {
loans.add(loan);
}
}
</code></pre>
|
R Add rows while reshaping a data frame <p>I have a similar data frame as <code>df</code> that looks like a registry of entries and exits in a system. </p>
<pre><code>df = data.frame(id = c("A", "B"), entry = c(2011, 2014), exit = c(2013, 2015))
> df
id entry exit
1 A 2011 2013
2 B 2014 2015
</code></pre>
<p>My aim is to represent my <code>df</code> in long format. <code>gather()</code> from <code>tidyr</code> enables to do something like this. </p>
<pre><code>df_long = df %>% gather(registry, time, entry:exit) %>% arrange(id)
> df_long
id registry time
1 A entry 2011
2 A exit 2013
3 B entry 2014
4 B exit 2015
</code></pre>
<p>Yet, I am stuck on how I could incorporate additional rows that would represent the time that my observations (<code>id</code>) are effectively in the system. My desired <code>data.frame</code> then would look something like this:</p>
<pre><code> id time
1 A 2011
2 A 2012
3 A 2013
4 B 2013
5 B 2014
6 B 2015
</code></pre>
<p>Any idea of how I could do this is more than welcome and really appreciated.</p>
| <p>Here's a way to get toward your desired solution:</p>
<pre><code>df1 <- data.frame(id = c("A", "B"), entry = c(2011, 2014), exit = c(2013, 2015))
setNames(stack(by(df1, df1$id, function(x) x$entry : x$exit))[,c(2,1)],
c('id','time'))
id time
1 A 2011
2 A 2012
3 A 2013
4 B 2014
5 B 2015
</code></pre>
|
How to force a subclass to have a specific subclass of superclass property? <p>Starting off, I'm working with EF, since I'm building an MVC application on C#. I want different types of exams to have different types of questions. Here are my abstract classes:</p>
<pre><code>public abstract class Exam
{
public int Id { get; set; }
public string Description { set; get; }
public abstract ICollection<Question> GetQuestions();
public abstract void SetQuestions(ICollection<Question> questions);
}
public abstract class Question
{
public int Id { get; set; }
public string Description { set; get; }
public abstract Exam getExam();
public abstract void setExam(Exam exam);
}
</code></pre>
<p>Notice that instead of the typical <code>public virtual ICollection<Question></code> in the Exam class declaration, I created an abstract setter and getter. So is the case for the Exam property in the Question class.</p>
<p>Here are my concrete Exam classes:</p>
<pre><code>[Table("SingleExam")]
public class SingleExam : Exam
{
public virtual ICollection<SingleQuestion> Questions { get; set; }
public override ICollection<Question> GetQuestions() { return Questions as ICollection<Question>; }
public override void SetQuestions(ICollection<Question> questions)
{
if (!(questions is ICollection<SingleQuestion>))
throw new ArgumentException("You must set single questions.");
Questions = questions as ICollection<SingleQuestion>;
}
}
[Table("MultipleExam")]
public class MultipleExam : Exam
{
public virtual ICollection<MultipleQuestion> Questions { get; set; }
public override ICollection<Question> GetQuestions() { return Questions as ICollection<Question>; }
public override void SetQuestions(ICollection<Question> questions)
{
if (!(questions is ICollection<MultipleQuestion>))
throw new ArgumentException("You must set multiple questions.");
Questions = questions as ICollection<MultipleQuestion>;
}
}
</code></pre>
<p>...And my concrete Question classes:</p>
<pre><code>[Table("SingleQuestion")]
public class SingleQuestion : Question
{
public int ExamId { get; set; }
public virtual SingleExam Exam { get; set; }
public override Exam getExam() { return Exam; }
public override void setExam(Exam exam)
{
if (!(exam is SingleExam))
throw new ArgumentException("You must set a SingleExam");
Exam = exam as SingleExam;
}
}
[Table("MultipleQuestion")]
public class MultipleQuestion : Question
{
public int ExamId { get; set; }
public virtual MultipleExam Exam { get; set; }
public override Exam getExam() { return Exam; }
public override void setExam(Exam exam)
{
if (!(exam is MultipleExam))
throw new ArgumentException("You must set a MultipleExam");
Exam = exam as MultipleExam;
}
}
</code></pre>
<p>I did all this because a MultipleExam should only have MultipleQuestions, and a SingleExam should only have SingleQuestions, the same way that MultipleQuestion should have a MultipleExam and Single question should have a SingleExam.</p>
<p>Is there a better way to ensure that a subclass of a class 'A' contains or has a specific subclass of class 'B' (As is the case with my Exams and Questions), and having access to it through the abstract class without the abstract getters and setters?</p>
| <p>As other have mentioned I think you are over complicating your problem.
However; your question is about type guarantees and I will try to answer that.</p>
<p>First the code:</p>
<pre><code>public interface IExam<out T> where T:IQuestion {
int Id { get; set; }
string Description { set; get; }
IEnumerable<T> GetQuestions();
}
public interface IQuestion{
int Id { get; set; }
string Description { set; get; }
IExam<IQuestion> Exam { get; }
}
public class SingleQuestion:IQuestion {
public string Description { get; set; }
public int Id { get; set; }
IExam<IQuestion> IQuestion.Exam {
get { return Exam; }
}
public SingleExam Exam { get; set; }
}
public class SingleExam:IExam<SingleQuestion> {
public int Id { get; set; }
public string Description { get; set; }
private IEnumerable<SingleQuestion> _questions;
public IEnumerable<SingleQuestion> GetQuestions() {
return _questions;
}
public void SetQuestions(IEnumerable<SingleQuestion> questions) {
_questions = questions;
}
}
</code></pre>
<p>First of all we have replaced the abstract classes with interfaces.
This is required because we want to make IExam covariant on IQuestion and covariance can only be defined in an interface. This is also why we change to an IEnumerable for the collection.</p>
<p>Note we do not define the SetQuestions method in IExam in short this is because we can't. In long it is because that would make T contravarient as well as contravarient which would in turn lead to circumstances where type guarantees could not be made.</p>
<p>IQuestions is fairly straight forward no real changes here. You could, I suppose, leave it as an abstract type though.</p>
<p>Now the implementations:
In SingleQuestion we must explicitly implement Exam which expects an IExam then shadow it with a property that returns a SingleExam.
This allows us to return the most exact type of exam possible.</p>
<pre><code>SingleQuestion sq = new SingleQuestion();
IQuestion q = sq; //Upcast
sq.Exam; //returns a SingleExam
q.Exam; //returns a IExam<IQuestion>
</code></pre>
<p>In SingleExam you can now set the questions and restrict it so that only SingleQuestions may be added.</p>
<p>As an aside it is now easier to see why SetQuestions cannot be defined in IExam. Consider the following:</p>
<pre><code>SingleExam se = new SingleExam();
IExam<IQuestion> singleUpcast = se;
//What type of question can we set on singleUpcast?
</code></pre>
<p>All we know is that singleUpcast contains IQuestions but we can't just add IQuestions because singleUpcast is ultimately an instance of SingleExam which promised that only SingleQuestions could be set so it. In short it is not possible to know what types can be added to IExam without potentially breaking type guarantees</p>
|
Removing mime type icon from image using CSS, possible? <p>I'm currently using some CSS to append font-awesome icons as mime types for uploaded files and or links that end in .pdf, .xls, .docx, etc.</p>
<p>I should have prefaced this entire post with this comment I made:</p>
<p><strong>Ok, I should have mentioned that this is a WordPress site where users are able to upload and link images via the Media Uploader. Trying to automate this process so that (once delivered) the editor won't have to add HTML code to the visual editor. That being said, all WP images have a class assigned to them that's ".wp-image-*", would it be possible to use that WP class to filter the icons?</strong></p>
<p>My CSS looks like this:</p>
<pre><code>a[href$=".pdf"]::after {
font-family: "fontawesome";
content: "\0020\f1c1";
color: inherit;
font-weight: 400
}
</code></pre>
<p>This solution works exactly as I want it to with one exception... it appends the mime type icon to <strong>images that LINK to</strong> a .pdf not just text links.</p>
<p>How to remove or not display the font-awesome icon on images only? That is the question. I have tried a number of different CSS solutions and have come up with either removing the entire image that is linked to the .pdf, or nothing at all.</p>
<p>Looking for some guidance here, would prefer the solution to be CSS <strong>but am open to whatever will work the best</strong>(php, js, jquery, etc).</p>
<p>HERES AN EXAMPLE:</p>
<p>(text link)</p>
<pre><code><a href="example.pdf">Example PDF</a>
</code></pre>
<p>This works as expected.</p>
<p>This is the problem...</p>
<p>(image link below)</p>
<pre><code> <a href="example.pdf">
<img src="example.jpg" alt="example pdf" />
</a>
</code></pre>
<p>When the link wraps an image, it appends the font awesome icon to the image. How to stop the font awesome icon on images wrapped in links only?</p>
<p>My page code looks like this (not verbatim), also, using BootStrap Library:</p>
<pre><code><div class="container">
<div id="main_content">
<!-- Then there are the usual basic tags found in WordPress content such as <p><h1><blockquote> etc but the containing div is "main_content", no <div>'s before image -->
<p>
<a href="http://example-document.pdf">
<img class="alignright size-medium wp-image-639 img-responsive" src="http://example-image.jpg" alt="Alt Title" srcset="http://example-image.jpg 232w, http://example-image.jpg 613w" sizes="(max-width: 232px) 100vw, 232px">
</a>
</p>
</div>
</div>
</code></pre>
| <p>To solve it with the existing markup you'll need a parent selector, and those does not exist (yet).</p>
<p>A workaround could be to wrap the text in the text only links with a <code>span</code> and update the CSS rule with the <code>:not(img)</code> selector</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>a[href$=".pdf"] :not(img)::after {
content: " X";
color: red;
font-weight: 400
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="example.pdf"><span>Example PDF</span></a>
<br>
<a href="example.pdf">
<img src="http://placehold.it/100" alt="example pdf" />
</a></code></pre>
</div>
</div>
</p>
<p>Or add a <code>data-*</code> attribute on the links that contain an image</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>a[href$=".pdf"]:not([data-hasimg])::after {
content: " X";
color: red;
font-weight: 400
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="example.pdf">Example PDF</a>
<br>
<a href="example.pdf" data-hasimg>
<img src="http://placehold.it/100" alt="example pdf" />
</a></code></pre>
</div>
</div>
</p>
<p>If you can't change markup, here is a script sample</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 links = document.querySelectorAll('a[href$=".pdf"]');
for (var i = 0; i < links.length; i++) {
if (links[i].children.length == 0) {
links[i].classList.add('icon');
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>a[href$=".pdf"].icon::after {
content: " X";
color: red;
font-weight: 400
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="example.pdf">Example PDF</a>
<br>
<a href="example.pdf">
<img src="http://placehold.it/100" alt="example pdf" />
</a></code></pre>
</div>
</div>
</p>
|
subprocess.Popen process stdout returning empty? <p>I have this python code</p>
<pre><code>input()
print('spam')
</code></pre>
<p>saved as <code>ex1.py</code></p>
<p>in interactive shell</p>
<pre><code>>>>from subprocess import Popen ,PIPE
>>>a=Popen(['python.exe','ex1.py'],stdout=PIPE,stdin=PIPE)
>>> a.communicate()
(b'', None)
>>>
</code></pre>
<p>why it is not printing the <code>spam</code></p>
| <p>Input expects a whole line, but your input is empty. So there is only an exception written to <code>stderr</code> and nothing to <code>stdout</code>. At least provide a newline as input:</p>
<pre><code>>>> a = Popen(['python3', 'ex1.py'], stdout=PIPE, stdin=PIPE)
>>> a.communicate(b'\n')
(b'spam\n', None)
>>>
</code></pre>
|
Finding model predictor values that maximize the outcome <p>How do you find the set of values for model predictors (a mixture of linear and non-linear) that yield the highest value for the response.</p>
<p>Example Model:</p>
<pre><code>library(lme4); library(splines)
summary(lmer(formula = Solar.R ~ 1 + bs(Ozone) + Wind + Temp + (1 | Month), data = airquality, REML = F))
</code></pre>
<p>Here I am interested in what conditions (predictors) produce the highest solar radation (outcome).</p>
<p>This question seems simple, but I've failed to find a good answer using Google.</p>
<p>If the model was simple, I could take the derivatives to find the maximum or minimum. Someone has suggested that if the model function can be extracted, the <code>stats::optim()</code> function might be used. As a last resort, I could simulate all the reasonable variations of input values and plug it into the <code>predict()</code> function and look for the maximum value.</p>
<p>The last approach mentioned doesn't seem very efficient and I imagine that this is a common enough task (e.g., finding optimal customers for advertising) that someone has built some tools for handling it. Any help is appreciated.</p>
| <p>There are some conceptual issues here.</p>
<ul>
<li><p>for the simple terms (<code>Wind</code> and <code>Temp</code>), the response is a linear (and hence both monotonic and unbounded) function of the predictors. Thus if these terms have positive parameter estimates, increasing their values to infinity (<code>Inf</code>) will give you an infinite response (<code>Solar.R</code>); values should be as small as possible (negative infinite) if the coefficients are negative. Practically speaking, then, you want to set these predictors to the minimum or maximum <em>reasonable</em> value if the parameter estimates are respectively negative or positive.</p></li>
<li><p>for the <code>bs</code> term, I'm not sure what the properties of the B-spline are beyond the boundary knots, but I'm pretty sure that the curves go off to positive or negative infinity, so you've got the same issue. However, for the case of <code>bs</code>, it's also possible that there are one or more <em>interior</em> maxima. For this case I would probably try to extract the basis terms and evaluate the spline over the range of the data ...</p></li>
</ul>
<p>Alternatively, your mentioning <code>optim</code> makes me think that this is a possibility:</p>
<pre><code>data(airquality)
library(lme4)
library(splines)
m1 <- lmer(formula = Solar.R ~ 1 + bs(Ozone) + Wind + Temp + (1 | Month),
data = airquality, REML = FALSE)
predval <- function(x) {
newdata <- data.frame(Ozone=x[1],Wind=x[2],Temp=x[3])
## return population-averaged prediction (no Month effect)
return(predict(m1, newdata=newdata, re.form=~0))
}
aq <- na.omit(airquality)
sval <- with(aq,c(mean(Ozone),mean(Wind),mean(Temp)))
predval(sval)
opt1 <- optim(fn=predval,
par=sval,
lower=with(aq,c(min(Ozone),min(Wind),min(Temp))),
upper=with(aq,c(max(Ozone),max(Wind),max(Temp))),
method="L-BFGS-B", ## for constrained opt.
control=list(fnscale=-1)) ## for maximization
## opt1
## $par
## [1] 70.33851 20.70000 97.00000
##
## $value
## [1] 282.9784
</code></pre>
<p>As expected, this is intermediate in the range of Ozone(1-168), and min/max for Wind (2.3-20.7) and Temp (57-97).</p>
<p>This brute force solution could be made much more efficient by automatically selecting the min/max values for the simple terms and optimizing only over the complex (polynomial/spline/etc.) terms.</p>
|
Show YouTube Videos URLs and thumbnails in listview <p>I want to show multiple YouTube videos URLs (that are in arraylist) in the listview. This listview should show both URL and thumbnail of that video and if the user select any video, it should play in next full screen.</p>
<p>How can I do that in both Java and XML?</p>
| <p>Assuming that the URLs & Video data is provided by a Backend of yours, the steps would be as follows:</p>
<p><strong>1) Create a Java class named 'Video'</strong></p>
<pre><code>public class Video
{
String Thumbnail;
String Url;
String Title;
//GET & SET Methods
}
</code></pre>
<p>For more information about Java Classes, <a href="https://docs.oracle.com/javase/tutorial/java/concepts/class.html" rel="nofollow">refer this</a>.</p>
<p>Add all your video objects to an ArrayList of type Video</p>
<p>Example: <code>ArrayList<Video> videos = new ArrayList<~>();</code></p>
<p><strong>2) Create a new android layout named 'single_video_item.xml' in the R.layout directory</strong></p>
<p>In order to display a list of videos in your ListView, we first need to define how a single row looks like. The file would be as follows:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Video Title"
android:textSize="18sp" />
<ImageView
android:id="@+id/thumbnail"
android:layout_below="@+id/title"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="300dp" />
</RelativeLayout>
</code></pre>
<p><strong>3) Create a custom ListView adapter of type Video</strong></p>
<p>In order to display all the videos, you need a custom ListView adapter that iterates through your ArrayList objects. <a href="https://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView" rel="nofollow">Refer this</a> for more information about ListView adapters.</p>
<p>Name the file as 'FeedAdapter.java' & use the following code</p>
<pre><code>public class FeedAdapter extends ArrayAdapter<Video> {
public FeedAdapter (Context context, ArrayList<Video> videos) {
super(context, 0, users);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Video currentVideo = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.single_video_item, parent, false);
}
// Lookup view for data population
TextView title = (TextView) convertView.findViewById(R.id.title);
ImageView thumbnail = (TextView) convertView.findViewById(R.id.thumbnail);
// Populate the data into the template view using the data object
title.setText(currentVideo.Title);
//And similarly set your imageview data, etc
// Return the completed view to render on screen
return convertView;
}
}
</code></pre>
<p>Read a bit about <a href="https://www.sitepoint.com/custom-data-layouts-with-your-own-android-arrayadapter/" rel="nofollow">Custom adapters</a> to gain a bit more exposure on the subject.</p>
<p>Now that we've arranged the basic setup of the Adapters, let's set the Custom adapter we've created to the ListView & pass the list of videos.</p>
<p>In your Activity's onCreate, define the ListView & initialize the FeedAdapter:</p>
<pre><code>//This is the listview in your main activity's xml
ListView listView = (ListView) findViewById(R.id.feedListView);
FeedAdapter<Video> adapter = new FeedAdapter(this, videos);
listView.setAdapter(adapter);
</code></pre>
<p>This would be the main structure of your code. Please read more about Custom ListView adapters to get a clearer idea about the procedure. Goodluck!</p>
<p>P.S: I wrote the entire code by memory, let me know if there are any syntax errors! ;)</p>
<p><strong>EDIT</strong></p>
<p>If you receive the Thumbnail as an image Url, checkout <a href="http://frescolib.org/" rel="nofollow">Fresco</a> by Facebook. It allows you to pass an Image URL & set that as an Image in your ListView. If you choose this method, you won't be needing the android ImageView.</p>
|
Get time Android <p>I use Time Picker and i Want take value of hour and minute after push a button, i've make this code but the app shutdown after I push it.. I don't know where is the error.</p>
<pre><code>final TimePicker tp = (TimePicker)findViewById(R.id.tp);
Button b3 =(Button)findViewById(R.id.b3);
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int hour = tp.getCurrentHour();
int minute = tp.getCurrentMinute();
String a =Integer.toString(hour);
String b = Integer.toString(minute);
Toast.makeText(MainActivity.this, a, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, b, Toast.LENGTH_SHORT).show();
}
});
</code></pre>
| <p>Consider using a <code>TimePickerDialog</code> with a <code>DialogFragment</code> For a working example you can check out a test app I have here:
<a href="https://github.com/agramian/android-test-app/blob/master/AndroidTest/app/src/main/java/com/abtingramian/android/androidtest/feature/calendar/CalendarLayout.java" rel="nofollow">https://github.com/agramian/android-test-app/blob/master/AndroidTest/app/src/main/java/com/abtingramian/android/androidtest/feature/calendar/CalendarLayout.java</a></p>
|
OpenGL rotation issues <p>So I've managed to build a complex shape consisting of multiple parts in OpenGL and I need to make it rotate via keyboard input. I have implemented keyboard inputs and they work although when I call glRotatef inside the key event handler the shapes do not rotate which I believe is because it is out of the scope of the method that builds the shapes. Any way to rotate all my shapes outside of the method in which they are built? </p>
| <p>You can rotate using glRotatef() then after you can call the function which is creating that object provided your function which is drawing is not creating its own modelview matrix.
If your function is using its own matrix i.e using loadIdentity then it might be not possible.
Grv10India </p>
|
Input field freezes on adding new row at Enter key press <p>I have a table with input fields. If a user presses <code>Enter</code> key inside an <code>input</code> field then it will add a <code>new row</code> to the table. Here is the code for it:</p>
<pre><code>// Detecting keycode
if $event.keyCode == 13
$event.preventDefault()
// add new row
// setting default values
</code></pre>
<p>If i'm correct, <code>$event.preventDefault()</code> freezes the <code>input</code> field from where key press has been done. Refer the image:</p>
<p><a href="https://i.stack.imgur.com/thUJT.png" rel="nofollow"><img src="https://i.stack.imgur.com/thUJT.png" alt="enter image description here"></a></p>
<p>The blue bordered input fields(Twitter Bootstrap) stays as like this after the key press which doesn't let the user to type anything.</p>
<p>I need to know how to unbind this <code>$event.preventDefault()</code>. </p>
| <p><code>preventDefault()</code> just do what it names points (i.e. prevents the default action to be triggered) It means, if it's a click event on, let's say, <code><a href="whatever">MyLink</a></code> the link will no be triggered and no navigation will occur. </p>
<p>Keep in mind that <code>preventDefault()</code> and <code>bind()</code> are to different concepts. </p>
<p>Hope it helps!</p>
<p><strong>EDIT</strong>:
Definitley a jsFiddle will be very useful to clarify your question.</p>
<p><strong>EDIT2</strong>:
Don't know but maybe something like this can help <a href="https://jsfiddle.net/asw866yh/" rel="nofollow">https://jsfiddle.net/asw866yh/</a> as you can see nothing freezes and only hitting enter in the last field creates a new one. Obviously you should improve this code in a real life app. </p>
<p>BTW, not sure if this is the answer you are looking for.</p>
|
why regex getting stackOverFlow <p>When I trying to match for above regex using scala lib (working with re2), code goes into below path and times out 1 minute:</p>
<p>Regex:</p>
<pre><code>(([a-z0-9!#$%&'*+?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])))
</code></pre>
<p>Stack Trace:</p>
<pre><code>at java.util.regex.Pattern$CharProperty.match(Pattern.java:3693)
at java.util.regex.Pattern$Curly.match(Pattern.java:4125)
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3694)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4556)
at java.util.regex.Pattern$Loop.match(Pattern.java:4683)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4615)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4170)
at java.util.regex.Pattern$Curly.match(Pattern.java:4132)
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3694)
</code></pre>
<p>I am not sure if its infinite loop as It might work after long time duration.
I need to help to understand what exactly in this expression is causing this to happen and how to improve this expression.</p>
| <p>Your regular expression has nested quantifiers (e.g. <code>(a+)*</code>). This <a href="https://swtch.com/~rsc/regexp/regexp1.html" rel="nofollow">works well with re2</a> but <a href="http://www.regular-expressions.info/catastrophic.html" rel="nofollow">not with most other regular expression engines</a>.</p>
|
How can I elegantly write class templates that use a value implied by the template argument? <p>I am writing a source file library with a series of declarations and macros that are related in a one-to-one relationship. The first is a list of categories, as an enumeration:</p>
<pre><code>typedef enum {
CID_SYS, // Highest-priority devices. Reserved.
CID_CTRL, // Controlling unit, only one per segment
CID_SENSOR, // Data providers (temperature, speed, clock)
CID_BROADCAST, // Broadcast messages (system messages extension)
...
} category_id_t;
</code></pre>
<p>I'm using this enumeration to define 16-bit message identifiers with the category bits as the most significant 3 bits. Those identifiers are segmented in two variable-size bit blocks in the less significant bits. One of these blocks depends on the above category. So I've also defined a list of sizes as macros, one per category like this:</p>
<pre><code>#define SYS_MESSAGES_MAX 256
#define CTRL_MESSAGES_MAX 64
#define SENSOR_MESSAGES_MAX 8
#define BROADCAST_MESSAGES_MAX 64
...
</code></pre>
<p>It's then easy to mask out the category and retrieve the relevant bits, i.e. the function ID, which lies in the least significant bits of the message ID. With <code>CID_SYS</code> for instance:</p>
<pre><code>unsigned short function_id = message_id & (SYS_MESSAGES_MAX-1)
</code></pre>
<p>I need a class template with the category as an argument. The number of messages in the category, which is implied by the latter should somehow be deduced by the template class at compile-time without resorting to arrays. The class template might look like something similar:</p>
<pre><code>template <category_id_t CAT>
class Manager
{
...
unsigned message_count() const { return /* a number depending on CAT */ }
};
</code></pre>
<p>With <code>-Os</code> the compiler resolves as much as it can at compile-time without adding code or variables when it can. So I'd like to make the most of it. My current attempt is using a function template and specialization:</p>
<pre><code>template<category_id_t CAT>
unsigned cat_size();
template<category_id_t CAT>
class Manager
{
public:
unsigned size() const { return cat_size<CAT>(); }
};
template<> unsigned cat_size<CID_SYS>() { return SYS_MESSAGES_MAX; }
template<> unsigned cat_size<CID_CTRL>() { return CTRL_MESSAGES_MAX; }
</code></pre>
<p>The above example would then be:</p>
<pre><code>unsigned short function_id = message_id & (size()-1) /* This should be a constant resolved at compile-time */
</code></pre>
<p>The generic template function is intentionally left without its definition to have a linker error generated in the case I forget a specialization when I add a category. However I find this inelegant and convoluted.</p>
<p>How could I make this more elegant?</p>
<p>I definitely don't want to pass the message count as a template argument because I still need the C-style macros: my library is supposed to be used by C <em>and</em> C++ applications.</p>
| <p>This may not be neat or elegant but I had some search meta-function to find a type in a type-list as follows:</p>
<pre><code>#include <type_traits>
template<typename ...Ts>
struct TypeList; //Represent a list of types to be queried
struct Nil; //empty type, a placeholder type if we cannot find what we need
//Searches given 'Item' in types ('Ts...') where equality check is done by 'Equals'
template<typename Item, template<class,class> class Equals, typename ...Ts>
struct Find;
//Specializes the 'Find' with 'TypeList' provides syntactic sugar
template<typename Item, template<class,class> class Equals, typename ...Ts>
struct Find<Item, Equals, TypeList<Ts...>> : Find<Item, Equals, Ts...>
{};
//recursive 'Find' metafunction. If 'T' is equal to 'Item' then return 'T'
// Else recurse to the rest of the type list
template<typename Item, template<class,class> class Equals, typename T, typename ...Ts>
struct Find<Item, Equals, T, Ts...> {
using type = typename std::conditional<
Equals<Item, T>::value, //Evaluate T
T, //if predicate returns true than T is the type we are looking for
Find<Item, Equals, Ts...> //else recurse into the list
>::type;
};
//specialization for one type 'T', that is the last element of the original type-list
template<typename Item, template<class,class> class Equals, typename T>
struct Find<Item, Equals, T> {
using type = typename std::conditional<
Equals<Item, T>::value, //Evaluate T
T, //if predicate returns true than T is the type we are looking for
Nil //else return Nil for meaningful compile messages
>::type;
};
</code></pre>
<p>You can have this in a utility header and use it for various purposes. <a href="http://www.boost.org" rel="nofollow">Boost</a> has two different libraries for such classes (meta-programming) one of them is <a href="http://www.boost.org/doc/libs/1_62_0/libs/mpl/doc/index.html" rel="nofollow">MPL</a> and the other modern version is <a href="http://www.boost.org/doc/libs/1_62_0/libs/hana/doc/html/index.html" rel="nofollow">Hana</a>. You may want to check one of those libraries.</p>
<p>With such type-searching mechanism we can define a type for your category and hold category related information.</p>
<pre><code>//A special structure to define your compile-time attributes for each category
template<category_id_t CatId, int CatMask>
struct Category
{
static const category_id_t id = CatId;
static const int mask = CatMask;
};
//define a set of categories with their attributes (ie. id and mask)
using Categories = TypeList<
Category<CID_SYS, SYS_MESSAGES_MAX-1>,
Category<CID_CTRL, CTRL_MESSAGES_MAX-1>,
Category<CID_SENSOR, SENSOR_MESSAGES_MAX-1>,
Category<CID_BROADCAST, BROADCAST_MESSAGES_MAX-1>
>;
</code></pre>
<p>Then we define a predicate and a specialized search function to find related category with given id as follows:</p>
<pre><code>//
template<typename Item, typename Category_>
using CategoryEquals = std::integral_constant<
bool,
Item::value == Category_::id
>;
template<category_id_t CatId>
using FindCategory = Find<
std::integral_constant<category_id_t, CatId>, //Item
CategoryEquals, //Equals
Categories
>;
</code></pre>
<p>Finally, we can find and use categories like this:</p>
<pre><code>template<category_id_t CatId>
unsigned short GetFunctionId(unsigned short messageId)
{
using FoundCat = typename FindCategory<CatId>::type; //search for category
return messageId & FoundCat::mask;
}
</code></pre>
<p>Sample usage:</p>
<pre><code>int main()
{
unsigned short msg = 259;
unsigned short functionId = GetFunctionId<CID_SYS>(msg);
std::cout << functionId; //prints 3
}
</code></pre>
|
Sublime 3 Plugin Storing Quick Panel Return Val <p>I'm trying to write a simple plugin that generates a quick panel based on some list, waits for the user to select an item, and then performs an action based on the value the user selected. Basically, I'd like to do the following:</p>
<pre><code>class ExampleCommand(sublime_plugin.TextCommand):
def __init__(self):
self._return_val = None
self._list = ['a', 'b', 'c']
def callback(self, idx)
self._return_val = self._list[idx]
def run(self):
sublime.active_window().show_quick_panel(
options, self.callback)
if self._return_val == 'a'
// do something
</code></pre>
<p>However, show_quick_panel returns before anything is selected and therefore self._return_val won't be assigned to the index selected until after the if statement runs.</p>
<p>How can I solve this problem? With an event listener? I'm very new to Python and Sublime plugin development.</p>
| <p>Showing the quickpanel obviously does not block the program execution. I recommend to create and pass a continuation:</p>
<pre class="lang-py prettyprint-override"><code>import sublime
import sublime_plugin
class ExampleQuickpanelCommand(sublime_plugin.WindowCommand):
def run(self):
# create your items
items = ["a", "b", "c"]
def on_select(index):
if index == -1: # canceled
return
item = items[index]
# process the selected item...
sublime.error_message("You selected '{0}'".format(item))
self.window.show_quick_panel(items, on_select)
</code></pre>
|
android studio error: transformClassesWithJarMergingForDebug <p>I'm currently testing a game. But when I try to run the app on my device, it gives me this error:</p>
<p><img src="https://i.stack.imgur.com/oYxKq.png" alt="enter image description here"></p>
<p>I already tried cleaning the project, but the error stays.</p>
<p>Project: </p>
<pre><code>buildscript {
repositories {
mavenLocal()
mavenCentral()
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
}
}
allprojects {
apply plugin: "eclipse"
apply plugin: "idea"
version = '1.0'
ext {
appName = "RocketHedgehog"
gdxVersion = '1.9.3'
roboVMVersion = '2.1.0'
box2DLightsVersion = '1.4'
ashleyVersion = '1.7.0'
aiVersion = '1.8.0'
}
repositories {
mavenLocal()
mavenCentral()
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url "https://oss.sonatype.org/content/repositories/releases/" }
}
}
project(":android") {
apply plugin: "android"
configurations {
natives
all*.exclude group: 'com.android.support', module: 'support-v4'
}
dependencies {
compile project(":core")
compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a"
natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86_64"
compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-arm64-v8a"
natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86_64"
compile "com.google.android.gms:play-services-ads:9.4.0"
compile "com.google.android.gms:play-services-games:9.6.1"
compile project(':BaseGameUtils')
compile 'com.android.support:multidex:1.0.1'
}
}
project(":core") {
apply plugin: "java"
dependencies {
compile "com.badlogicgames.gdx:gdx:$gdxVersion"
compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
}
}
project(":desktop") {
apply plugin: "java"
dependencies {
compile project(":core")
compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
}
}
tasks.eclipse.doLast {
delete ".project"
}
</code></pre>
<p>BaseGameUtils: (Library) I needed this for implementing GPS</p>
<pre><code>apply plugin: 'com.android.library'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
dependencies {
// Set defaults so that BaseGameUtils can be used outside of BasicSamples
if (!project.hasProperty('appcompat_library_version')) {
ext.appcompat_library_version = '20.0.+'
}
if (!project.hasProperty('support_library_version')) {
ext.support_library_version = '20.0.+'
}
if (!project.hasProperty('gms_library_version')) {
ext.gms_library_version = '8.4.0'
}
compile "com.android.support:appcompat-v7:${appcompat_library_version}"
compile "com.android.support:support-v4:${support_library_version}"
compile "com.google.android.gms:play-services-games:${gms_library_version}"
compile "com.google.android.gms:play-services-plus:${gms_library_version}"
}
android {
// Set defaults so that BaseGameUtils can be used outside of BasicSamples
if (!project.hasProperty('android_compile_version')) {
ext.android_compile_version = 23
}
if (!project.hasProperty('android_min_version')) {
ext.android_min_version = 9
}
if (!project.hasProperty('android_version')) {
ext.build_tools_version = "23.0.2"
}
compileSdkVersion android_compile_version
buildToolsVersion build_tools_version
defaultConfig {
minSdkVersion android_min_version
targetSdkVersion android_compile_version
}
}
</code></pre>
| <p>I would recommend you set a variable for the google services and make them all the same version. </p>
<p>For example, your <code>BaseGameUtils</code> uses <code>8.4.0</code> consistently, but your project is using various other versions (<code>9.6.1</code> and <code>9.4.0</code>)</p>
<pre><code>ext {
appName = "RocketHedgehog"
gms_library_version = "8.4.0" // For consistency with library
</code></pre>
<p>Then, update these lines to use that variable. </p>
<pre><code> compile "com.google.android.gms:play-services-ads:${gms_library_version}"
compile "com.google.android.gms:play-services-games:${gms_library_version}"
</code></pre>
|
How to pass value to a viewController embedded in NavigationController <p>There are similar questions but they are either in swift or are not solving my problem.<br />I've a view controller which is presenting navigation view controller when cell did select button is pressed as:</p>
<pre><code>patientBillNavigationViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PatientBillVC"];
//soem value assignment
[self presentViewController:viewController animated:YES completion:nil];
</code></pre>
<p>You can say billing opens up a whole new view independent of the main app flow to handle billing process.
<br />The view this navigation View Controller automatically loads is the bill view and now if I want to pass a value from this viewcontroller to the other viewController embedded in navigation view I can't do that. How to pass a value? </p>
<pre><code>UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
PatientBillViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"PBVC"];
vc.superBillToAddEdit = sb;
//then display the view embedded in navigation view
</code></pre>
<p>But this is not working.</p>
| <p>One way I know is to Subclass <code>UINavigationViewController</code> and in its <code>viewDidLoad</code>, you can do:</p>
<pre><code> YourEmbeddedVc *svc =self.viewControllers[0]; //get the controller reference
svc.name= @"Hello";
</code></pre>
<p>I'm assuming you are only having one controller in your navigation stack, if not you need to find out the proper match of the required VC.</p>
|
Can I use Hamcrest's Matchers.containsInRelativeOrder? <p>I'm a little confused. I see function <code>containsInRelativeOrder</code> in <a href="https://github.com/hamcrest/JavaHamcrest/blob/master/hamcrest-library/src/main/java/org/hamcrest/Matchers.java#L1021" rel="nofollow">the code</a>:</p>
<pre><code>@SafeVarargs
public static <E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> containsInRelativeOrder(E... items) {
return org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder(items);
}
</code></pre>
<p>but I'm getting a method-not-found error when I try to use that method (with Hamcrest 1.3) and I don't see it in <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html" rel="nofollow">the javadoc</a>.</p>
<p>Is this a version issue? Is the method not present in 1.3?</p>
| <p><strong>Corrected</strong> thanks to @Tom.</p>
<p>Yes, it is a version issue! <a href="https://github.com/hamcrest/JavaHamcrest/commit/36d525e1e425006939a77aec5183aecd7c775b05" rel="nofollow">1.3</a> is from 2012. The function was added in Dec. 2014 by <a href="https://github.com/hamcrest/JavaHamcrest/commit/99bc9421a719782c6357f991c891af48d6e9de4a" rel="nofollow">commit 99bc9421a719782c6357f991c891af48d6e9de4a</a>.</p>
<p>The first version of this function was added in Nov. 2014 by <a href="https://github.com/hamcrest/JavaHamcrest/commit/5ed2d06688f9d3b445b98b13056223b79318a614" rel="nofollow">commit 5ed2d06688f9d3b445b98b13056223b79318a614</a>. At that time, it lived in a separate file, <a href="https://github.com/hamcrest/JavaHamcrest/blob/5ed2d06688f9d3b445b98b13056223b79318a614/hamcrest-library/src/main/java/org/hamcrest/collection/IsIterableContainingInRelativeOrder.java" rel="nofollow"><code>collection/IsIterableContainingInRelativeOrder.java</code></a>. </p>
|
Laravel 5.3 Upload an image with Auth user::create <p>I am trying to add an image to the user. To create the user I use
system make:Auth but I don't know how can I get the file name because on
<code>create(array $data)</code> I don't receive the file name.</p>
<pre><code>protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'img' =>
]);
}
</code></pre>
<p>I can't put <code>'img' = $data['img']</code> because I need the file name.</p>
<p>How can i get the file name?</p>
| <p>use the <code>getClientOriginalName</code> method because it's symfony <a href="http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html" rel="nofollow">UploadedFile</a> instance try this :</p>
<p><code>data['img']->getClientOriginalName();</code></p>
|
vertical align inside divs contained in a div that represents a row <p>I've tried just about every vertical-align for div trick I can find and still not getting the results. This is inside of an established responsive framework, so I've stripped it down to some inline CSS to show the issue.</p>
<p><a href="https://i.stack.imgur.com/hRyqX.png" rel="nofollow"><img src="https://i.stack.imgur.com/hRyqX.png" alt="enter image description here"></a></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><div class="row uniform">
<div style="clear:none;width:25%;float:left;background:#CCC;box-sizing:border-box;">
box 1<br />
line 2
</div>
<div style="clear:none;width:25%;float:left;background:#a43c69;color:#FFF;box-sizing:border-box;">
box 2
</div>
<div style="clear:none;width:25%;float:left;background:#CCC;box-sizing:border-box;">
box 3
</div>
<div style="clear:none;width:25%;float:left;background:#a43c69;color:#FFF;box-sizing:border-box;">
box 4
</div>
</div> </code></pre>
</div>
</div>
</p>
<p>Ideally boxes 2,3 and 4 go to the same height as box 1, and text in all boxes is vertically aligned in the middle.</p>
<p>row.uniform sets some margins, padding and a default vertical-align of baseline, but that's not effecting anything here.</p>
| <p>Note that I removed your <code>float: left;</code> on all <code>div</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row {
display: table;
width: 100%;
}
.row div {
display: table-cell;
float: none;
vertical-align: top;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row uniform">
<div style="clear:none;width:25%;background:#CCC;box-sizing:border-box;">
box 1<br />
line 2
</div>
<div style="clear:none;width:25%;background:#a43c69;color:#FFF;box-sizing:border-box;">
box 2
</div>
<div style="clear:none;width:25%;background:#CCC;box-sizing:border-box;">
box 3
</div>
<div style="clear:none;width:25%;background:#a43c69;color:#FFF;box-sizing:border-box;">
box 4
</div>
</div></code></pre>
</div>
</div>
</p>
<p>For those wondering about browser support, <a href="http://caniuse.com/#feat=css-table">it is supported on all major browsers</a>.</p>
|
Generate X random integers between Y and Z? <p>Is there a function in Python (I'm working with SageMath) to get 10 random integers between 0 and 30, for instance, without repeating them?</p>
| <pre><code>import random
random.sample(range(31), 10)
</code></pre>
|
Searching Multi-Dimensional Array <p>I've created a multi-dimensional array in C++, but it doesn't return anything when I search it. Just wondering if I messed something up in the code? Full disclosure: This was originally a class assignment, but I turned it in 2 weeks ago. I'm asking for clarification for future programs.</p>
<p>I've put the main body (minus some of the list since it's 1000 entries) below</p>
<pre><code>#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
std::string name;
std::string age;
//declare 1000*2 Array
std::string array[1000][2] =
{
{ "Karen Rose","25" },
{ "Cora Faison","11" },
{ "Donna Jones","49" },
{ "Robert Lowe","31" },
{ "Patricia Johnston","17" },
{ "Maryanne Hicks","40" },
{ "James Mcmurray","53" },
};
cout << "Enter a name to search for " << endl;
cin >> name;
for(int i = 0; i > 1000; i++)
{
if(name == array[i][0])
{
age = array[i][1];
cout << name << "'s age is" << age << endl;
}
else
{
cout << "we found nothing" << endl;
}
}
return 0;
}
</code></pre>
| <p>Beyond having your loop test backward, using <code>cin >> name</code> will only get the first name. You test first and last. Thus your tests will never succeed.</p>
<p>Use <code>std::getline</code>.</p>
<p>Doing a modicum of debugging work would have turned up both errors.</p>
|
Django: Filtering query to a specific id <p>I have a podcast management website where a user is able to setup his account and after that will be able to create multiple episode from that specific user. After an episode is done, a button will appear where he can see some links that is created automatically for the user to use. The problem I am having is that for every episode, I am trying to show the links for that specific one but it always keeps showing the links from the one I recently created and other episodes that were previously created.</p>
<p>This is the button where the user click when the episode has created the links:</p>
<pre><code><a class="btn btn-info box-shadow--6dp" href="{% url 'pf:episodereview' production_id=instance.id %}" role="button"><i class="fa fa-link" aria-hidden="true"></i>&nbsp Review Links</a>
</code></pre>
<p>The URL pattern in <code>urls.py</code>:</p>
<pre><code>url(r'^episodereview/(?P<production_id>[0-9]+)/$', views.EpisodeReview.as_view(), name="episodereview"),
</code></pre>
<p>This is what happens in <code>views.py</code>:</p>
<pre><code>class EpisodeReview(LoginRequiredMixin, ProductionRequiredMixin, ListView):
template_name = 'pf/forms_episode_review.html'
podcast = None
def get(self, request, *args, **kwargs):
production_id = kwargs.get('production_id', None)
if production_id:
production = Production.objects.filter(id=production_id).first()
if not production:
return self.handle_no_permission()
return super(EpisodeReview, self).get(request, *args, **kwargs)
def get_queryset(self):
return Production.objects.filter(podcast=self.podcast)
def get_success_url(self):
return reverse('pf:dashboard')
</code></pre>
<p>And the template where everything is displayed:</p>
<pre><code>{% extends "pf/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<br>
<br>
<div class="panel panel-default box-shadow--16dp col-sm-6 col-sm-offset-3">
<div class="panel-body">
<div class='row'>
<div class='col-sm-12'>
<h3><i class="fa fa-wpforms pull-right" aria-hidden="true"></i>Episode Review&nbsp</h3>
<h5>Following links are generated automatically with your accounts and can be used immediately.</h5>
<hr/>
{% if object_list %}
<table class='table'>
<tbody>
{% for instance in object_list %}
<ul>
<li><b>Wordpress URL:</b> {{ instance.wordpress_url }}</li>
<li><b>Wordpress Short URL:</b> {{ instance.wordpress_short_url }}</li>
<li><b>Soundcloud Result URL:</b>{{ instance.soundcloud_result_url }}</li>
<li><b>Youtube Result URL:</b>{{ instance.youtube_result_url }}</li>
<li><b>Libsyn Result URL:</b>{{ instance.libsyn_result_url }}</li>
</ul>
{% endfor %}
</tbody>
</table>
{% endif %}
<hr/>
<button type="submit" class="btn btn-info box-shadow--6dp"><i class="fa fa-floppy-o" aria-hidden="true"></i> &nbspSave
</button>
</div>
</div>
</div>
</div>
{% endblock %}
</code></pre>
<p>Welcome any suggestion!</p>
| <p>You filter by the id in the get method, but then don't do anything with the result. When it comes to construct the template context, Django calls get_queryset, which only filters by self.podcast - which is None.</p>
<p>You should move that filter logic into get_queryset. And if you also want to filter by podcast, you should find a way to define that parameter too.</p>
|
Storage of structure elements in C <p>Consider the following code:</p>
<pre><code>struct employee
{
int id;
char name[30];
};
main()
{
struct employee e1;
printf("%d %d %d", sizeof(e1.id), sizeof(e1.name), sizeof(e1));
}
</code></pre>
<p>where the Structure elements are saved in memory and how?
And what is the size of structure?</p>
| <p>In this case, the memory is stored on the program stack. Obviously, that means you don't want to store structures that are too large this way.</p>
<p>The size of the memory is the total bytes used by the structure. Assuming your platform uses 1 byte per <code>char</code>, that would be 30 bytes plus the size of an <code>int</code> (whatever) it is on your platform.</p>
<p>Also note that compilers can inject a few padding bytes between members in some cases. Use <code>sizeof(e1)</code> to get the true size. It looks like you've done this so why are you asking us the size?</p>
|
Doxygen project version number in XML <p>I would like my project version number to appear the the Doxygen XML output so I can programmatically retrieve it. I have set up PROJECT_NUMBER, and the value I used there appears in the HTML output for the same build, but not for the XML output. I grepped the XML output folder for the raw text of the value I put in PROJECT_NUMBER and it appears nowhere. Searching through the Doxygen configuration options I couldn't find anything that would control this besides PROJECT_NUMBER itself, so I don't think it's only a configuration issue.</p>
<p>Is this simply not a feature for Doxygen? If so is there a workaround to get that value in the XML output? The version number is generated during the documentation build process and I would strongly prefer not to store it in any source file directly.</p>
<p>I am using Doxygen 1.8.11</p>
| <p>No definitive answer, but this is the solution I will be using if nothing else pops up.</p>
<p>Create an alias:</p>
<pre><code>ALIASES = "myversion=\anchor version \xmlonly a.b.c \endxmlonly"
</code></pre>
<p>Where 'a.b.c' is the version number that was also placed in PROJECT_NUMBER.</p>
<p>Then place the <code>\myversion</code> tag in a comment block marked as a <code>\page</code> or <code>\mainpage</code>, since <code>\anchor</code> needs to be in one of those (<a href="http://www.stack.nl/~dimitri/doxygen/manual/commands.html#cmdanchor" rel="nofollow">source</a>).</p>
<p>It's not ideal, but you can then use the anchor to easily locate the version in the xml. In my case the xml output was:</p>
<pre><code><para><anchor id="index_1version"/> a.b.c </para>
</code></pre>
<p>within the page's detailed description, so you can just grab the textual contents of the enclosing 'para' tag.</p>
<p>I don't necessarily need the <code>\xmlonly</code> tag, but since the PROJECT_NUMBER shows up in the html already, having the version number randomly printed out elsewhere isn't necessary.</p>
|
Allowing the user to undo a "don't ask again"? <p>In Android if you ask for permissions, second requests onward allow the user to check "Don't ask me again" so the failure state will always be reached in the future.</p>
<p>What if the user changes their mind and wants to allow permission, but can't now because the feature defaults to the permission-fail state? How can the user undo their "don't ask again" setting?</p>
| <p>The user cannot undo the "don't ask again" setting itself directly. The user can:</p>
<ul>
<li><p>Grant rights to the permission group through the Settings app (Settings > Apps > (your app) > Permissions), or</p></li>
<li><p>Clear the data associated with your app, which AFAIK will clear the "don't ask again" status (along with everything else related to permissions), or</p></li>
<li><p>Uninstall and reinstall the app (which definitely resets all state related to permissions)</p></li>
</ul>
|
How to get the x and y intercept in matplotlib? <p>I have scoured the internet and can't find a python command to find the x and y intercepts of a curve on matplotlib. Is there a command that exists? or is there a much easier way that is going over my head? Any help would be appreciated. Thanks, </p>
<p>Nimrodian.</p>
| <p>Use this. Much faster:</p>
<pre><code>slope, intercept = np.polyfit(x, y, 1)
</code></pre>
|
DropShadow with static source is faster when using "cached:true" <p>I'll begin with my testcase. It creates 21 unchanging shadowed blue rectangles. It also creates a 1x1px Canvas3D repainted constantly, so I can check how often it manages to get repainted with all the other stuff going on (<code>Canvas3D</code> has a built-in <code>fps</code> property). When <code>cached: true</code> is set on the DropShadow items, I get 60 FPS. When not, I get 30 FPS. But what I expect is to get the same FPS in both cases, since I don't expect the shadows' blur to ever get recalculated, considering that the source rects never get updated.</p>
<p><em>main.cpp</em>: (trivial)</p>
<pre><code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
</code></pre>
<p><em>main.qml</em>:</p>
<pre><code>import QtQuick 2.5
import QtQuick.Window 2.2
import QtCanvas3D 1.1
Window {
visible: true
width: 800
height: 600
id: window
Column {
Text {
text: canvas3d.fps + " FPS"
font.pointSize: 18
}
Flow {
width: window.width
spacing: 10
Repeater {
model: 21
ShadowedItem {
}
}
}
Canvas3D {
id: canvas3d
width: 1; height: 1 // nonzero size so it can be redrawn
property var gl;
onInitializeGL: {
// should get and save context, otherwise FPS isn't measured for some reason
gl = canvas3d.getContext("canvas3d", {depth:true, antialias:true, alpha:true});
}
}
}
}
</code></pre>
<p><em>ShadowedItem.qml:</em></p>
<pre><code>import QtQuick 2.0
import QtGraphicalEffects 1.0
Item {
width: 100
height: 100
Rectangle {
anchors.fill: parent
id: rect
visible: false
color: "blue"
}
DropShadow {
source: rect
anchors.fill: rect
cached: true // !
radius: 8
}
}
</code></pre>
<p>Any idea on the difference in performance?</p>
| <p>I posted a <a href="http://stackoverflow.com/q/40040954/122687">follow-up question</a> about this. In the comments to it, I learned that when 1 item in the scene (e.g. the Canvas3D in this case) needs to be redrawn, the entire scene gets redrawn. Which means that every time my Canvas3D is redrawn (which is constantly), all the shadows get redrawn. This, if <code>cached</code> is <code>false</code>, means that the blur gets recalculated, hence the slowdown.</p>
|
need jquery datepicker to fire again for changing a date <p>When i click in an empty textbox, the datepicker fires and the calendar dialog shows nicely. But if click again on a date in the textbox in order to change to a new date, I cannot cause the same datepicker dialog to pop up. </p>
<p>Markup after page is loaded follows:</p>
<pre><code><div id="panelVacationMode" class="row">
<span class="labelCell" title="Skip reminder emails until I return">
<input id="CheckBox1" type="checkbox" name="ctl00$MainContentPlaceHolder$CheckBox1"
checked="checked"><label for="CheckBox1">Vacation Mode</label></span>
<div id="vacationModeBox" class="vacationRangeCell">
<label for="txtFromDate" id="lblStart">Start:</label>
<input name="ctl00$MainContentPlaceHolder$txtFromDate" type="text"
value="11/1/2016" maxlength="10"
id="txtFromDate" class="dateTextBox" size="8">
<label for="txtToDate" id="lblReturn">Return:</label>
<input name="ctl00$MainContentPlaceHolder$txtToDate" type="text"
value="12/31/2016" maxlength="10"
id="txtToDate" class="dateTextBox" size="8">
<br>
</div>
<br>
<br>
</div>
</code></pre>
<p>Here is the code at the bottom of the .aspx page:</p>
<pre><code> <script>
$(function () {
// check if checkbox is unchecked
if ($("#CheckBox1").is(':checked'))
$('#vacationModeBox').show();
else
$('#vacationModeBox').hide();
// check if any checkbox has changed state
$("input[type='checkbox']").click(function () {
$('#txtFromDate').focus();
$("input[type='checkbox']").on('change', function () {
if ($(this).not(":checked")) {
$('.dateTextBox').val("");
$('#vacationModeBox').toggle(this.checked);
}
else
$('#txtFromDate').focus();
});
$(function () {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$("#txtFromDate").datepicker({
numberOfMonths: 2,
minDate: new Date(currentYear, currentMonth, currentDate),
onSelect: function (selected) {
$("#txtToDate").datepicker("option", "minDate", selected)
}
});
$('#txtToDate').focus();
$("#txtToDate").datepicker({
numberOfMonths: 2,
onSelect: function (selected) {
$("#txtFromDate").datepicker("option", "maxDate", selected)
}
});
});
});
});
</script>
</code></pre>
<p><strong>Update added 14-Oct-2016:</strong></p>
<p>Perhaps I need some changes to these references below to make <strong>datepicker</strong> work for me as described in the original post? :</p>
<pre><code><html>
<head runat="server">
<title></title>
<link type="text/css" rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<link type="text/css" rel="stylesheet" href="//cdn.jsdelivr.net/qtip2/2.2.0/jquery.qtip.min.css" />
<link type="text/css" rel="stylesheet" href="~/IEStyles.css" />
<link type="text/css" rel="stylesheet" href="~/StyleSheet1.css" />
<link type="text/css" rel="stylesheet" href="~/css/app.css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/qtip2/2.2.0/jquery.qtip.min.js"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/js/sitewide.js") %>"></script>
<asp:ContentPlaceHolder ID="ExtraStyles" runat="server" />
</head>
</code></pre>
<p>Striving to be clear: when I click on a textbox without a date already stored, the datepicker UI "pops up" nicely with the calendar exposed for choosing; yet when I click in a textbox already with a date with the intention of picking a new date, nothing happens. Even if I clear the mm/dd/yyyy value out and then try to click for datepicker, nothing happens. Here is a sample of where I cannot interact with datepicker:
<a href="https://i.stack.imgur.com/qGtNh.png" rel="nofollow"><img src="https://i.stack.imgur.com/qGtNh.png" alt="once set to a date, I cannot change"></a></p>
<p><strong>Update 15 Oct:</strong> (no change after use of newest frameworks)
The following screen snippet shows use of the newer resources yet datepicker behaves the same for me as in the OP:
<a href="https://i.stack.imgur.com/jmVJn.png" rel="nofollow"><img src="https://i.stack.imgur.com/jmVJn.png" alt="no response from datepicker if date already present"></a></p>
| <p>i updated your whole source code...
now it seems that it will work...</p>
<pre><code> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="panelVacationMode" class="row">
<span class="labelCell" title="Skip reminder emails until I return">
<input id="CheckBox1" type="checkbox" name="ctl00$MainContentPlaceHolder$CheckBox1"
checked='checked'><label for="CheckBox1">Vacation Mode</label></span>
<div id="vacationModeBox" class="vacationRangeCell">
<label for="txtFromDate" id="lblStart">Start:</label>
<input name="ctl00$MainContentPlaceHolder$txtFromDate" type="text"
value="11/1/2016" maxlength="10"
id="txtFromDate" class="dateTextBox" size="8">
<label for="txtToDate" id="lblReturn">Return:</label>
<input name="ctl00$MainContentPlaceHolder$txtToDate" type="text"
value="12/31/2016" maxlength="10"
id="txtToDate" class="dateTextBox" size="8">
<br>
</div>
<br>
<br>
</div>
<script>
$(function () {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$("#txtFromDate").datepicker({
numberOfMonths: 2,
minDate: new Date(currentYear, currentMonth, currentDate),
onSelect: function (selected) {
$("#txtToDate").datepicker("option", "minDate", selected)
}
});
$("#txtToDate").datepicker({
numberOfMonths: 2,
onSelect: function (selected) {
$("#txtFromDate").datepicker("option", "maxDate", selected)
}
});
});
$(function () {
// check if checkbox is unchecked
if ($("#CheckBox1").is(':checked')){
$('#vacationModeBox').show();
$('#txtFromDate').focus();
}
else
$('#vacationModeBox').hide();
// check if any checkbox has changed state
$("input[type='checkbox']").on('change', function () {
if ($(this).not(":checked")) {
$('.dateTextBox').val("");
$('#vacationModeBox').toggle(this.checked);
}
if ($(this).is(":checked")){
$('#txtFromDate').focus();
}
});
});
</script>
</code></pre>
|
Random comma inserted at character 8192 in python "json" result called from node.js <p>I'm a JS developer just learning python. This is my first time trying to use node (v6.7.0) and python (v2.7.1) together. I'm using restify with python-runner as a bridge to my python virtualenv. My python script uses a RAKE NLP keyword-extraction package.</p>
<p>I can't figure out for the life of me why my return data in <strong>server.js</strong> inserts a random comma at character 8192 and roughly multiples of. There's no pattern except the location; Sometimes it's in the middle of the object key string other times in the value, othertimes after the comma separating the object pairs. This completely breaks the JSON.parse() on the return data. Example outputs below. When I run the script from a python shell, this doesn't happen.</p>
<p>I seriously can't figure out why this is happening, any experienced devs have any ideas?</p>
<p><em>Sample output in browser</em></p>
<pre><code>[..., {...ate': 1.0, 'intended recipient': 4.,0, 'correc...}, ...]
</code></pre>
<p><em>Sample output in python shell</em></p>
<pre><code>[..., {...ate': 1.0, 'intended recipient': 4.0, 'correc...}, ...]
</code></pre>
<p><strong>DISREGARD ANY DISCREPANCIES REGARDING OBJECT CONVERSION AND HANDLING IN THE FILES BELOW. THE CODE HAS BEEN SIMPLIFIED TO SHOWCASE THE ISSUE</strong></p>
<p><strong>server.js</strong></p>
<pre><code>var restify = require('restify');
var py = require('python-runner');
var server = restify.createServer({...});
server.get('/keyword-extraction', function( req, res, next ) {
py.execScript(__dirname + '/keyword-extraction.py', {
bin: '.py/bin/python'
})
.then( function( data ) {
fData = JSON.parse(data); <---- ERROR
res.json(fData);
})
.catch( function( err ) {...});
return next();
});
server.listen(8001, 'localhost', function() {...});
</code></pre>
<p><strong>keyword-extraction.py</strong></p>
<pre><code>import csv
import json
import RAKE
f = open( 'emails.csv', 'rb' )
f.readline() # skip line containing col names
outputData = []
try:
reader = csv.reader(f)
for row in reader:
email = {}
emailBody = row[7]
Rake = RAKE.Rake('SmartStoplist.txt')
rakeOutput = Rake.run(emailBody)
for tuple in rakeOutput:
email[tuple[0]] = tuple[1]
outputData.append(email)
finally:
file.close()
print( json.dumps(outputData))
</code></pre>
| <p>This looks suspiciously like a bug related to size of some buffer, since 8192 is a power of two.</p>
<p>The main thing here is to isolate exactly where the failure is occurring. If I were debugging this, I would </p>
<ol>
<li><p>Take a closer look at the output from <code>json.dumps</code>, by printing several characters on either side of position 8191, ideally the integer character code (unicode, ASCII, or whatever). </p></li>
<li><p>If that looks OK, I would try capturing the output from the python script as a file and read that directly in the node server (i.e. don't run a python script). </p></li>
<li><p>If that works, then create a python script that takes that file and outputs it without manipulation and have your node server execute that python script instead of the one it is using now.</p></li>
</ol>
<p>That should help you figure out where the problem is occurring. From comments, I suspect that this is essentially a bug that you cannot control, unless you can increase the python buffer size enough to guarantee your data will never blow the buffer. 8K is pretty small, so that might be a realistic solution.</p>
<p>If that is inadequate, then you might consider processing the data on the the node server, to remove every character at <code>n * 8192</code>, if you can consistently rely on that. Good luck. </p>
|
Hibernate: custom entity name <p>Let's say I have an entity with a very long name:</p>
<pre><code>@Entity
public class SupercalifragilisticexpialidociousPanda
{
...
}
</code></pre>
<p>Using Hibernate to persist it to a Postgres DB works flawlessly. Oracle, however, doesn't allow for table/column/index names longer than 30 characters.
That should be easy to fix, since i can just specify the table name manually, like this:</p>
<pre><code>@Entity
@Table(name="SuperPanda")
public class SupercalifragilisticexpialidociousPanda
{
...
}
</code></pre>
<p>Now everything is back to working perfectly... except that any references I have to the entity in other tables still use the long class name ("SupercalifragilisticexpialidociousPanda") instead of the short table name ("SuperPanda"). </p>
<p>For instance, if the entity has an embedded ElementCollection, like this:</p>
<pre><code>@ElementCollection
private Set<String> nicknames;
</code></pre>
<p>Hibernate will try to create a DB like this: <code>create table SupercalifragilisticexpialidociousPanda_nicknames</code>, which will naturally cause an <code>ORA-00972: identifier is too long</code> error.</p>
<p>The same thing also happens for <code>@OneToOne</code> associations, where the lookup column would be called something like <code>supercalifragilisticexpialidociousPanda_uuid</code>, which also fails with oracle.</p>
<p>Now, one option would be to add a <code>@CollectionTable(name="SuperPanda_nicknames")</code> and <code>@Column(name="...")</code> annotation manually to every field that references this entity, but that's a lot of work and really error-prone.</p>
<p>Is there a way to just tell Hibernate <strong>once</strong> to use the short name everywhere a reference to the entity is required?</p>
<p>I also tried setting the entity name, like this:</p>
<pre><code>@Entity(name="SuperPanda")
@Table(name="SuperPanda")
public class SupercalifragilisticexpialidociousPanda
{
...
}
</code></pre>
<p>... but it doesn't fix the issue.</p>
<p>What does one normally do in such a case?</p>
| <p>Usually people give names for each database thing (table, column, index) by themselves. Letting Hibernate decide for you can lead to problem in future when you decide to refactor something.</p>
<p>All reference can be configured one way or another to use names you decide to use.</p>
<p>Ask specific question in case you can figure out the way to do it yourself.</p>
|
Different layout for different modules <p>Something really weird is happening. I have two modules, one called <code>Application</code> and the other one called <code>Dashboard</code> they are different and have nothing to do with each other. I wanted to use a phtml layout to each one of them, and that is what I did:</p>
<p><code>module/Application/config/module.config.php</code>:</p>
<pre><code>// ...
'view_manager' => [
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
</code></pre>
<p><code>module/Dashboard/config/module.config.php</code>:</p>
<pre><code>// ...
'view_manager' => [
'doctype' => 'HTML5',
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'dashboard/index/index' => __DIR__ . '/../view/dashboard/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
</code></pre>
<p>I created the two separated layouts, one in <code>module/Application/view/layout/layout.phtml</code> and the other one in <code>module/Dashboard/view/layout/layout.phtml</code>, logically it had to work, but it doesn't, it always call the <code>Dashboard</code> layout even for the <code>Application</code>.
I was wondering, how to use separated layouts for each module?</p>
| <p>I had the same issue on a previous ZF2 project. The problem is that you use the same 'layout/layout' identifier for both modules and during config merging, one is lost.</p>
<p>The idea is to give different names for identifiers, and to use an abstract controller which will permits to change the layout. And on the <code>dispatch</code> event, you attach a function wich will set the layout for your module:</p>
<p><strong><code>Module.php</code></strong> (of your main module)</p>
<pre><code>public function onBootstrap($e)
{
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controllerClass = get_class($controller);
$moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
$controller->layout($moduleNamespace . '/layout');
}, 100);
}
</code></pre>
<p>And in <strong><code>module.config.php</code></strong> of all modules using a different layout (for example <em>Dashboard</em>):</p>
<pre><code>'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'Dashboard/layout' => __DIR__ . '/../view/layout/layout.phtml',
'Dashboard/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
</code></pre>
<p>And it should be OK. Else you can also use other party code, like <a href="https://github.com/EvanDotPro/EdpModuleLayouts" rel="nofollow">EdpModuleLayouts</a>, but it is no more maintained... The good point of my solution is that you should understand what you do.</p>
|
When testing an ExpressJS route using mocha+sinon, how do you "stub" a function that's local to the route? <p>So in one file, I have this route defined:</p>
<pre><code>router.post('/', security.authenticate, function(req, res, next) {
//Doing prep stuff
//Do database work (<< this is what im really testing for)
//Calling another work function.
createFormUser(req.body, (ret) => {
return res.json(ret.createdUser);
});
});
</code></pre>
<p>followed by this function:</p>
<pre><code>var createFormUser = (ourUser, call) => {
// does a bunch of misc work and creation for another database
// unrelated to current tests.
}
</code></pre>
<p>I want to to test this route. Normally, I would just create a sandbox instance of the database so that it can do whatever it wants, make an http request to the route in the test, and finally do expects() in the return from that http call. </p>
<p>However, I don't want the "createFormUser" function to be called, because 1) it does some fancy shit that's really hard to contain for this test 2) I will be testing it elsewhere. </p>
<p>In a normal test I would at this point use sinon to stub the function. But in this case I don't actually have an object reference, since this is all done through HTTP requests to server that mocha spools up when testing. </p>
<p>So my question is the same as the title, how can stub/replace/ignore/etc this method so it doesn't get called during the test?</p>
| <p>As stated by @DavidKnipe, all I had to do was export the methods via:</p>
<pre><code>module.exports.createFormUser = (ourUser, call) => { ... }
</code></pre>
<p>And was able to both test the method individually and prevent it's execution via a sinon.stub. </p>
|
Filtering syntax for pandas dataframe groupby with logic condition <p>I have a pandas dataframe containing indices that have a one-to-many relationship. A very simplified and shortened example of my data is shown in the <a href="https://i.stack.imgur.com/7z1ih.jpg" rel="nofollow">DataFrame Example</a> link. I want to get a list or Series or ndarray of the unique namIdx values in which nCldLayers <= 1. The final result should show indices of 601 and 603.</p>
<ol>
<li><p>I am able to accomplish this with the 3 statements below, but I am wondering if there is a much better, more succinct way with perhaps 'filter', 'select', or 'where'.</p>
<pre><code>grouped=(namToViirs['nCldLayers']<=1).groupby(namToViirs.index).all(axis=0)
grouped = grouped[grouped==True]
filterIndex = grouped.index
</code></pre></li>
<li><p>Is there a better approach in accomplishing this result by applying the logical condition (namToViirs['nCldLayers >= 1) in a subsequent part of the chain, i.e., first group then apply logical condition, and then retrieve only the namIdx where the logical result is true for each member of the group?</p></li>
</ol>
| <p>I think your code works nice, only you can add use small changes:</p>
<p>In <code>all</code> can be omit <code>axis=0</code><br>
<code>grouped==True</code> can be omit <code>==True</code> </p>
<pre><code>grouped=(namToViirs['nCldLayers']<=1).groupby(level='namldx').all()
grouped = grouped[grouped]
filterIndex = grouped.index
print (filterIndex)
Int64Index([601, 603], dtype='int64', name='namldx')
</code></pre>
<p>I think better is first filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> and then <code>groupby</code>, because less loops -> better performance.</p>
|
jQuery refer to wrapper set from .each() <p>I'm rather new to jQuery and couldn't find an answer to this on SO. On form submit, I have the following script to validate fields before sending the data.</p>
<pre><code>jQuery('#contact_form input, #contact_form textarea').attr('disabled', true).each(function(index, element){
//test for empty values, incorrect format, etc.
if(error){
this.end().attr('disabled', false); //this doesn't work
}
});
</code></pre>
<p>I'm disabling the form fields when the user clicks Submit, but I want to enable <strong>all</strong> the fields if there's an error so the user can correct their input. How can I do this from within the <code>.each()</code> loop?</p>
| <p>You could store all the fields in a variable before applying the each loop</p>
<pre><code>var form_fields = jQuery('#contact_form input, #contact_form textarea');
form_fields.each(function(index, element){
// Disable current input
jQuery(this).prop('disabled', true);
//test for empty values, incorrect format, etc.
if(error){
// Target all input fields
form_fields.prop('disabled', false);
// Break out of each loop
return false;
}
});
</code></pre>
<p>Then you call the prop function on all fields if there is an error</p>
|
displaying jtable in another panel and remove one row <p>i have one <code>jtable</code> and it is displayed to 1st <code>jpanel</code> but at the same it has to be displayed again in 2nd <code>jpanel</code>. but i should remove the last row of the <code>jtable</code> before i'll display it to 2nd <code>jpanel</code>. and if i go back to the 1st <code>jpanel</code>, the removed row will go back, and remove again in 2nd <code>jpanel</code>, vice versa.</p>
<p>is this possible? i can't seem to find answers when i tried researching it. thank you for any help :)</p>
| <p>So, let me see if I have this correct: table 1 and table 2 will be exactly alike except that table 1 will have one more row than table 2, right?</p>
<p>If so, have them share the same TableModel, but have table 2 not display the last row of the model by using a row filter as per the <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting" rel="nofollow">JTable tutorial</a>.</p>
<p>Here's my attempt to do this, but understand that this is my first time doing this sort of thing, and so "caveat emptor":</p>
<pre><code>import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
@SuppressWarnings("serial")
public class ShareTableModel extends JPanel {
private static final Integer[][] DATA = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } ,
{10, 11, 12},
{13, 14, 15}};
private static final String[] COLS = { "A", "B", "C" };
private static final int SPINNER_COUNT = 3;
private DefaultTableModel tblModel = new DefaultTableModel(DATA, COLS);
private JTable table1 = new JTable(tblModel);
private JTable table2 = new JTable(tblModel);
private JSpinner[] spinners = new JSpinner[SPINNER_COUNT];
private MySorter2 sorter = new MySorter2(tblModel);
public ShareTableModel() {
JPanel addRowPanel = new JPanel();
for (int i = 0; i < spinners.length; i++) {
JSpinner spinner = new JSpinner(new SpinnerNumberModel(10, 0, 100, 1));
addRowPanel.add(spinner);
spinners[i] = spinner;
}
addRowPanel.add(new JButton(new AddRowAction("Add Row", KeyEvent.VK_A)));
table2.setRowSorter(sorter);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Table 1", new JScrollPane(table1));
tabbedPane.add("Table 2", new JScrollPane(table2));
setLayout(new BorderLayout());
add(tabbedPane);
add(addRowPanel, BorderLayout.PAGE_END);
}
private class MySorter2 extends TableRowSorter<DefaultTableModel> {
public MySorter2(DefaultTableModel tableModel) {
super(tableModel);
setRowFilter(new RowFilter<DefaultTableModel, Integer>() {
@Override
public boolean include(RowFilter.Entry<? extends DefaultTableModel, ? extends Integer> entry) {
int modelRow = entry.getIdentifier();
return modelRow < getModelRowCount() - 1;
}
});
}
}
private class AddRowAction extends AbstractAction {
public AddRowAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
@Override
public void actionPerformed(ActionEvent e) {
Integer[] row = new Integer[spinners.length];
for (int i = 0; i < row.length; i++) {
row[i] = (Integer) spinners[i].getValue();
}
tblModel.addRow(row);
sorter.sort();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ShareTableModel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ShareTableModel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
</code></pre>
|
How to distinguish a negative binary number? <p>Suppose I am dealing with 4 bit operations. So if I encounter an binary digit say </p>
<pre><code>1111
</code></pre>
<p>then what should I infer ? Is it -1 or 15 ?</p>
| <p>"That depends".</p>
<p>The bits are (in this case) encoding a number, but you have to know which kind of number (signed or unsigned, integer, fixed-point or float) in order to interpret the encoded bits.</p>
<p>If the number is supposed to be signed in two's complement, then the proper interpretation is -1, if it's unsigned then it's 15.</p>
<p>It's not possible to decide from those four bits alone, it's simply not enough information.</p>
<p>This of course is true for a "full-sized" value too, it could be an <code>int</code> or an <code>unsigned int</code> and you have to know that in order to correctly interpret the bits.</p>
<p><em>Update:</em> If you <em>know</em> that your number is supposed to be signed, the easiest way to deal with it (assuming C, which generally doesn't have a signed 4-bit integer type) is to <em>sign-extend</em> it into a usable form.</p>
<p>Sign-extending merely involves taking the most significant bit of the fewer-bits number, and repeating it to the left up to (and including) the most significant bit of the target one.</p>
<p>So in your case, you have <code>0xf</code>, whose top bit is 1. Extending to an <code>int8_t</code>, we get:</p>
<pre><code>const int8_t number = 0xff;
</code></pre>
<p>Which is -1.</p>
<p>There is no built-in way to do this sign-extension from an arbitrary few-bits number, since C can't natively deal with those.</p>
<p>Here's a naive approach:</p>
<pre><code>// Sign-extend a n-bit number into 32 bits.
int32_t extend(uint32_t bits, size_t n)
{
const bool top = bits & ((uint32_t) 1 << (n - 1));
if (top)
{
for (size_t i = n; i < 32; ++i)
bits |= 1 << i;
}
return bits;
}
</code></pre>
<p>If you call the above with your number:</p>
<pre><code>printf("%d\n", (int) extend(0xf, 4));
</code></pre>
<p>it prints <code>-1</code>.</p>
|
Comparing two large text files column by column in Python <p>I have two large tab separated text files with dimensions : 36000 rows x 3000 columns. The structure of the columns is same in both files but they may not be sorted.</p>
<p>I need to <em>compare only the numeric columns</em> between these two files(apprx 2970 columns) and export out those rows where there is a difference in the value between any two respective columns.</p>
<p>Problem: Memory issue</p>
<p>Things I tried:</p>
<p>1) Transposing data: Making the data from wide to long and reading the data chunk by chunk.
Problem: Data bloats to a more than few million rows and python throws me a memory error</p>
<p>2) Difflib: Difflib along with generators and without transposing did provide me an output which was efficient but it compares the two files row by row. It doesn't differentiate the columns in the tab separated file.(I need them to be differentiated into columns since I will be performing some column operations between the difference rows.</p>
<p>3) Chunk and join: This is third approach I am trying wherein I will divide one file into chunks and merge it on the common keys with the other file repeatedly and find the difference in those chunks. This is going to be a shitty approach and its going to take a lot of time but I am unable to think of any thing else.</p>
<p>Also:
These type of questions have been answered in the past but they only dealt with one huge file and processing the same. </p>
<p>Any suggestions for a better approach in <strong>Python</strong> will be greatly appreciated. Thank you.</p>
| <p>First of all, if files are that big, they should be read row by row.</p>
<p>Reading one file row by row is simple:</p>
<pre><code>with open(...) as f:
for row in f:
...
</code></pre>
<p>To iterate two files row by row, zip them:</p>
<pre><code>with open(...) as f1, open(...) as f2:
for row1, row2 in itertools.izip(f1, f2):
# compare rows, decide what to do with them
</code></pre>
<p>I used <code>izip</code>, as it won't zip everything at once, like <code>zip</code> would in Python 2.
In Python 3, use <code>zip</code>. It does the right thing there.
It will go row by row and yield the pairs.</p>
<p>The next question is comparing by column. Separate the columns:</p>
<pre><code>columns = row.split('\t') # they are separated by tabs, therefore \t
</code></pre>
<p>Now pick the relevant columns and compare them. Then discard irrelevant rows and write the relevant ones to the output.</p>
|
how to implement notification in php when row update in data base without refresh just like facebook <p>i am working on my final year project which is about to share images videos,text messages and i want that on my website when user send a text images videos its should be display like "rana send u a message"but its should be without refresh page just like in Facebook thanks
i have concept about how to devolve a notification system in php but i want that just notification like Facebook .</p>
<p>please help me
i will be very great-full to you if u will give me an example according to my question</p>
| <p>What you are looking for is <a href="http://www.w3schools.com/xml/ajax_intro.asp" rel="nofollow">AJAX</a> and it JavaScript not PHP although they do work together a lot.</p>
<p>Facebook actually made their own JavaScript framework for Facebook. It's called React and there is a tutorial to do pretty much what you want <a href="https://facebook.github.io/react/docs/tutorial.html" rel="nofollow">here</a> </p>
|
retrieve from array for input parameter doesn't work <p>I want to do something like..</p>
<pre><code>position := [100, 200]
Click, position[1], position[2]
</code></pre>
<p>but the above doesn't work, no error, but doesn't do click</p>
<pre><code>Click, %position[1]%, %position[2]%
</code></pre>
<p>above gives error, variable name contains an invalid character</p>
<pre><code>position := [100, 200]
p1 := position[1]
p2 := position[2]
Click, %p1%, %p2%
</code></pre>
<p>above works, but I don't want to assign dummy variables each time I need to click..</p>
<p>any help?
thanks!</p>
| <p>This will do what you want:</p>
<pre><code>click % position[1] . "," . position[2]
</code></pre>
<p>The % must be followed by a space or tab. It causes the command to use <em>expression mode</em>.</p>
<p>More information on "expression mode" can be found under <strong>Help > Variables and Expressions > Variables > Retrieving the contents of variables</strong>.</p>
|
Is there a shortcut to do JS imports in WebStorm? <p>I spend a lot of time writing JS imports. Seems like WebStorm should be able to help me, but I can't find any shortcut for it. Perhaps there is a plugin somewhere...</p>
| <p>There is a "Missing import statement" inspection that has a quickfix (available on <code>Alt+Enter</code>). Similar inspection is available for <code>require()</code>. See <a href="http://blog.jetbrains.com/webstorm/2015/11/node-js-coding-assistance-in-webstorm-11/" rel="nofollow">http://blog.jetbrains.com/webstorm/2015/11/node-js-coding-assistance-in-webstorm-11/</a>)</p>
|
Python string assignment error occurs on second loop, but not first <p>The first run-through of the while loop goes fine:</p>
<pre><code>hour_count = list('00/')
hours = 0
while hours < 24: #loop while hours < 24
hour_count[1] = hours #<- error occurs on this line
hour_count = ''.join(hour_count) #convert to string
...
hours += 1
</code></pre>
<p>However, upon the second loop, it gives a TypeError: 'str' object does not support item assignment. The purpose is to set a file path.</p>
| <p>When you run this line <code>hour_count = ''.join(hour_count)</code>, you're changing the data type of <code>hour_count</code> from a list to a string.</p>
<p>Because strings are immutable, you can't modify one character via the index notation (the line before this line attempts to do that).</p>
<p>I'm not totally sure what your goal is, but perhaps you're looking to append to the list. These docs will help with that.</p>
<p><a href="https://docs.python.org/3.4/tutorial/datastructures.html" rel="nofollow">https://docs.python.org/3.4/tutorial/datastructures.html</a></p>
|
google charts no data (blank page) <p>i have a web page contain 8 google charts </p>
<p>when i have all data for the charts it work fine </p>
<p>but sometimes there is some charts has no data (2 or 3 out of the 8 )</p>
<p>so i get a blank page cause this charts </p>
<p>how to skip the script of the blank data charts</p>
<p>here is the script of one of them (all the similar script)</p>
<pre><code><script type="text/javascript">
google.charts.setOnLoadCallback(drawCostCharts);
function drawCostCharts() {
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } , 'Budget objectif' ],
<? foreach($***THEBlankDATAHERE***->getRows() as $row) {
$DBcostmonth = DB::table('budget_objectif')
->select('value')
->where('cam_id', 2)
->where('year', $row[1])
->where('month', $row[0])
->get();
$test = $DBcostmonth[0]->value; ?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo floor($row[2]); ?>, <? echo $test; ?>],
<? }?>
]);
var options = {
// title: 'Google Analytics Revenue',
vAxis: {minValue:0},
curveType: "function",width: 720, height: 400,
chartArea:{left:60,top:40,width:"90%",height:"70%"},
legend: {position: 'none'},
seriesType: 'bars',
series: {0:{color: 'purple'}},
isStacked:'true',
series: {1: {type: 'line', color:'red' , curveType: 'straight' }}
};
var chart = new google.visualization.ComboChart(document.getElementById('div1_3'));
chart.draw(data, options);
}
</code></pre>
<p></p>
<p><strong><em>Edited</em></strong> : this data source is from parent view in laravel 4.1 and it is a google analytics data </p>
<p>so some users have access to all data for the charts and some dont have access to data in some charts </p>
<p><strong><em>Edited2 :</em></strong></p>
<p>i change the script in the code and i get the page but without any charts the new code is :</p>
<pre><code><?php if ($tristanweekdata) { ?>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawCostCharts);
function drawCostCharts() {
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } , 'Budget objectif'],
<? foreach($tristanweekdata->getRows() as $row) {
$DBcostweek = DB::table('budget_objectif')
->select('value')
->where('cam_id', 2)
->where('year', $row[1])
->where('month', wtm($row[0]))
->get();
$test = $DBcostweek[0]->value/4.33;
?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo floor($row[2]); ?> ,<? echo $test;?> ],
<? }?>
]);
var options = {
// title: 'Google Analytics Revenue',
vAxis: {minValue:0},
curveType: "function",width: 720, height: 400,
chartArea:{left:60,top:40,width:"90%",height:"70%"},
legend: {position: 'none'},
seriesType: 'bars',
series: {0:{color: 'purple'}},
isStacked:'true',
series: {1: {type: 'line', color:'red' , curveType: 'straight' }}
};
var chart = new google.visualization.ComboChart(document.getElementById('tristancostweek'));
chart.draw(data, options);
}
</code></pre>
<p> </p>
<pre><code> <?php } ?>
</code></pre>
<p>now i get different error in the console of the browser :</p>
<p>""Uncaught TypeError: Cannot read property 'arrayToDataTable' of undefined""</p>
<p>thanks </p>
| <p>i figured the right way to make it work :)</p>
<p>the answer to this question is in the <strong><em>edited2</em></strong> in the question but there is a 1 change</p>
<p>what you need is to to put the google chart load out the of the script and make it alone like that:</p>
<pre><code> <script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
</script>
</code></pre>
<p>then you can put the condition that you want in mine like that :</p>
<pre><code><?php if ($tristanweekdata) { ?>
<script type="text/javascript">
google.charts.setOnLoadCallback(drawCostCharts);
function drawCostCharts() {
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } , 'Budget objectif'],
<? foreach($tristanweekdata->getRows() as $row) {
$DBcostweek = DB::table('budget_objectif')
->select('value')
->where('cam_id', 2)
->where('year', $row[1])
->where('month', wtm($row[0]))
->get();
$test = $DBcostweek[0]->value/4.33;
?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo floor($row[2]); ?> ,<? echo $test;?> ],
<? }?>
]);
var options = {
// title: 'Google Analytics Revenue',
vAxis: {minValue:0},
curveType: "function",width: 720, height: 400,
chartArea:{left:60,top:40,width:"90%",height:"70%"},
legend: {position: 'none'},
seriesType: 'bars',
series: {0:{color: 'purple'}},
isStacked:'true',
series: {1: {type: 'line', color:'red' , curveType: 'straight' }}
};
var chart = new google.visualization.ComboChart(document.getElementById('tristancostweek'));
chart.draw(data, options);
}
</script>
<?php } ?>
</code></pre>
<p>then all the charts is working if the user have the right access ;)</p>
<p>Thanks to @WhiteHat for his help</p>
|
Customize Paypal checkout page <p>using PHP REST API SDK, is there a way to customize the first PayPal page that appears (login page) when doing a Payment. Specifically, we would like to move "Pay with Debit or Credit Card" above and make larger than "Pay with Paypal".</p>
| <p>It is not possible to edit any portion of the hosted secure checkout page of PayPal standard or PayPal Express Checkout. The only change you 'can' make is add a logo or header image that populates and replaces the business name or email to the account.</p>
<p>Hope this helps</p>
|
Catching exception when retrieving data from sqlite database Android <p>I have this on my DBHelper</p>
<pre><code>public Cursor selectUser(String username){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * FROM user_tbl WHERE username = '" +
username+"'", null);
return res;
}
</code></pre>
<p>And i also have this try-catch block on my Activity.</p>
<pre><code>DBHelper mydb;
Cursor res;
user = LoginActivity.usernamee;
try{
res = mydb.selectUser(user);
if(res.getCount() > 0){
String fullnamee = res.getString(res.getColumnIndex(DBHelper.USER_NAME));
fullname.setText(fullnamee);
fullname.setFocusable(false);
fullname.setClickable(false);
}
}catch(Exception e){
System.out.println("Error retrieving database record.");
}
</code></pre>
<p>However, I am getting the catch exception. What I am trying to do is that, I would like to check my database where username is equal to <code>LoginActivity.usernamee</code>. Then display the full name of the user from my database table to my Android text view.</p>
<p>I would like to ask for assistance. Thank you!</p>
| <p>i think you are missing "moveToFirst"</p>
<pre><code>SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * FROM user_tbl WHERE username = '" + username + "'", null);
if(res.getCount() > 0){
res.moveToFirst();
String fullnamee = res.getString(res.getColumnIndex(DBHelper.USER_NAME));
// do what you want
}
</code></pre>
|
building basic calculator (cant get user input for the operator) <p>so I'm brand new to programming, trying to build my 5th program, a basic calculator.</p>
<p>so far i can ask for users to input an integer correctly;</p>
<pre><code>public static void main(String[] args) {
// CALCULATOR
Scanner keyboard = new Scanner(System.in);
int value1;
System.out.print("Enter 1st value: ");
value1 = keyboard.nextInt();
int value2;
System.out.print("Enter 2st value: ");
value2 = keyboard.nextInt();
char op;
System.out.print("Enter operator (/*-+): ");
op = keyboard.next();
int result = (value1 value2);
System.out.println(result);
</code></pre>
<p>then I tried the same for the operator, and messing around with it i have this.</p>
<p>However this doesn't work and i get "erroneous sym type" as the error.
I have looked around and tried some other people code but it usually contains IF functions and lots of lines of code and I'm trying to keep it simple, unless that is the only way to do it?</p>
<p>Thanks in advance</p>
<p>Edit - full error message
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.util.Scanner.nextChar
at calculator.Calculator.main(Calculator.java:30)
Enter operator (/*-+): C:\Users\shott_000\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1</p>
| <p>Surprisingly(?), <code>Scanner</code> does not have a <code>nextChar</code> method. Just read the operator into a <code>String</code> and you should be OK:</p>
<pre><code>String operator;
System.out.print("Enter operator (/*-+): ");
operator = keyboard.next();
</code></pre>
<p>You should also probably validate that the inputted string is a valid operator. E.g.:</p>
<pre><code>Set<String> validOpeators = new HashSet<>(Arrays.asList("/", "*", "-", "+"));
if (!validOperators.contains(operator)) {
throw new IllegalArgumentException
("Operator must be one of " + validOperators);
}
</code></pre>
|
Step In with native code leads to garbage in Android Studio <p>I have native code I've built using Gradle in Android Studio. Most of the debugging seems to work fine in C++, but I just added a new class and when I try to step in to the function call it takes me to an absolutely bizarre location in a completely unrelated area of code.</p>
<p>For example, I have the following line of code with a breakpoint:</p>
<p><code>SemVer ver_cl = PlatformHelper::getAppVersion();</code></p>
<p>I run "Step In", and I end up in <code>gnu-libstdc++</code> implementation of hashtable.h on a seemingly-arbitrary line of code.</p>
<p>I'm running in a simulator. I've made sure to sync my project to the Gradle files, but I'm not sure what could be causing this kind of behaviour.</p>
| <p>Implementation of <code>PlatformHelper::getAppVersion();</code> can give insight to the problem. In this particular case it occurred that the method had no return value. For <a href="https://www.quora.com/Why-dont-I-receive-a-compile-error-when-I-dont-return-a-value-from-int-main" rel="nofollow">historical reasons</a>, it is not an error in C++, but modern compilers usually trigger a warning in such situations and by adding <code>-Werror</code> compilation flag for GCC you can force it to treat warnings as errors. When non-void method does not return a value, the stack gets corrupted and control is returned to a random place. aardvarkk was "lucky" that the address occurred to be a valid one.</p>
<p>Another situation when similar behaviour can be seen is when when you compile your code with optimization (anything other then -O0). One of the strongest optimization techniques is inlining: function bodies are inserted directly in-to the place where they are called. This works especially good for templates. Downside of this process is that some functions are completely eliminated and they are not visible in stacktrace. So it is possible that when you step into <code>PlatformHelper::getAppVersion();</code> you directly drop somewhere in-to it's internals where hashmap is used because all the code between invocation of <code>getAppVersion</code> and usage of the hashmap has been optimized away. But in this case your program will function correctly, only debugging will be cumbered a bit.</p>
|
Using session variables in a partial rendered in realtime with ActionCable <p>I'm making a realtime chat application in Rails and I'm having trouble differentiating between the messages sent by each user. In my message partial I use the current_user session to apply either .current-user or .other-user to each message.</p>
<pre><code>_message.html.erb
<% if msg.text.present? %>
<% if msg.user_id == current_user.id %>
<p class="current-user msg"><%= msg.text %></p>
<% else %>
<p class="other-user msg"><%= msg.text %></p>
<% end %>
<% end %>
</code></pre>
<p>New messages are broadcast from the messages controller</p>
<pre><code>class MessagesController < ApplicationController
...
def create
@chat = Chat.find(params[:chat_id])
@message = @chat.messages.build(message_params)
if @message.save
ActionCable.server.broadcast "chat_channel",
message: render_message(@message)
end
end
...
private
def render_message(msg)
render(partial: 'message', locals: { msg: msg })
end
</code></pre>
<p>And appended to the message list with javascript</p>
<pre><code>chats.coffee
received: (data) ->
$('#messages').append data.message
$('#message_text').val('')
messages_to_bottom()
</code></pre>
<p>I've almost got it working but it looks like current_user = msg.user_id all the time. So even messages from the other user are being rendered with the current-user class. Is there any way to render these messages correctly?</p>
| <p>I ended up rendering the message on the client side from the chat.coffee file, first getting the user id from the message form</p>
<pre><code>user_id = parseInt($('#message_user_id').val())
</code></pre>
<p>and then</p>
<pre><code>received: (data) ->
if user_id == data.user_id
$('#messages').append "<div class='current-user msg'>" + data.text + "</div>"
else
$('#messages').append "<div class='other-user msg'>" + data.text + "</div>"
$('#message_text').val('')
messages_to_bottom()
</code></pre>
<p>I don't really like it because I've already written the message partial. If anyone has a better way, I'd really like to hear it.</p>
|
Wait for promise to return <p>I want to asynchronously load some data when my app starts and use the loaded data from a view controller that's presented later on in the apps' flow.</p>
<p>How do I determine if the data has loaded and, if it hasn't, how do I wait for it to load?</p>
<p>So if in AppDelegate the code is... <code>_ = service.LoadData()</code> and this returns a promise, how would the view controller know if the promise has returned or not?</p>
<p>Adding a new <code>.then</code> call onto the end of the promise would surely not work if the promise has already returned.</p>
| <p>Calling <code>.then</code> on a resolved promise seems to result in the closure being called immediately. So I just store the promise from the initial query, and then append a new <code>.then</code> to it whenever. If the data is loaded, its returned immediately, otherwise, hopefully, it will wait.</p>
|
Unwind Segue Navigation Bar Button Xcode 8.0 Swift 3.0 <p>I want to create an app in Xcode 8.0 that lets the user press a bar button item in the navigation bar. Once this button has been clicked an unwind segue will take place whilst also printing, "helloWorld" to the output section at the bottom of Xcode. I have successfully created an unwind segue using:</p>
<pre><code>@IBAction func unwindToViewController (sender: UIStoryboardSegue){
}
</code></pre>
<p>I then linked this to the bar button item on the navigation bar so that when I tap the bar button item on the navigation bar the view disappears downwards. </p>
<p>I am trying to simply <code>print("helloWorld")</code> onto the output section at the bottom of Xcode when I press the done button but nothing appears on the output section. So far I have:</p>
<pre><code>@IBAction func add(_ sender: AnyObject) {
print("helloWorld")
}
</code></pre>
<p>in the View Controller Swift File for that View Controller.</p>
| <p>Try the following link will fix your problem and help you to get better understanding about unwind segue...</p>
<p><a href="https://www.andrewcbancroft.com/2015/12/18/working-with-unwind-segues-programmatically-in-swift/#identifier" rel="nofollow">https://www.andrewcbancroft.com/2015/12/18/working-with-unwind-segues-programmatically-in-swift/#identifier</a></p>
<p><a href="http://ashishkakkad.com/tag/uistoryboardsegue/" rel="nofollow">http://ashishkakkad.com/tag/uistoryboardsegue/</a></p>
<p>Hope this helps...</p>
|
How to give index items different background images <p>I have an index view displaying multiple items with background images. The url is a string product.image. Here is my index view.</p>
<pre><code><div class="products">
<% @products.each do |product| %>
<style>
.product-image-index {
background-image: url('<%= product.image %>');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
</style>
<div class="product-con">
<div class="product-image-index">
</div>
<div class="product-text">
<div class="title"><%= product.name %></div>
<div class="button-con">
<span class="button"><%= link_to 'More Info', product, class: "buton" %></span>
</div>
</div>
</div>
<% end %>
</div>
</code></pre>
<p>The problem is the background images have the same image, and I understand, but what is the solution to this problem so that each item shows their respective background image.</p>
| <p>You are defining a CSS class where the background image will most likely be the last image in the loop. You will want to remove the line that sets the image:</p>
<pre><code>.product-image-index {
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
</code></pre>
<p>Also, move the style definition to an external stylesheet, or at least out of the loop because you are re-defining that class N times inside of the loop.</p>
<p>And add an inline style to the element like so:</p>
<p><code><div class="product-image-index" style="background-image: url('<%= product.image %>');"></code></p>
|
Query a mongodb record comparing values in an array to the array passed in the query <p>I have a document in the format </p>
<pre><code>{
"history": [
{
"plugin": [
1,
2,
3,
4
]
},
{
"plugin": [
2,
3,
4,
6
]
},
{
"plugin": [
1,
4
]
}
]
}
</code></pre>
<p>and i have an array x =[2,7],</p>
<p>I want query in such a way that if there is atleast one element in x which match with any of the element in the the plugin array, it should be return</p>
<p>thus for this case the expected result is</p>
<pre><code>{
"history": [
{
"plugin": [
1,
2,
3,
4
]
},
{
"plugin": [
2,
3,
4,
6
]
}
]
}
</code></pre>
| <p>Run the following pipeline which uses the <strong><a href="https://docs.mongodb.com/v3.2/reference/operator/aggregation/filter/" rel="nofollow"><code>$filter</code></a></strong> operator to return a subset of the <code>history</code> array that passes a given specified condition. This condition makes use of the <strong><a href="https://docs.mongodb.com/v3.2/reference/operator/aggregation/setIntersection/#exp._S_setIntersection" rel="nofollow"><code>$setIntersection</code></a></strong> set operator to check the embedded <code>plugin</code> array if it intersects with the given input comparison array.</p>
<p>So for instance, the expression</p>
<pre><code>{ $setIntersection: [ [ 1, 4 ], [ 2, 7 ] ] }
</code></pre>
<p>will return an empty set (array <code>[]</code>) since the two arrays do not intersect. Use this as basis to compare the result with the <strong><a href="https://docs.mongodb.com/v3.2/reference/operator/aggregation/ne/#exp._S_ne" rel="nofollow"><code>$ne</code></a></strong> comparison operator. This will return <code>true</code> when the compared two values are not equivalent and <code>false</code> when they are equivalent. Use this result to feed the "cond" expression so that it will filter the appropriate elements.</p>
<p>The following pipeline demonstrates this:</p>
<pre><code>var arr = [2,7];
db.collection.aggregate([
{ "$match": { "_id": ObjectId("57ffe28591f567293497d924") } }, // <-- filter here
{
"$project": {
"history": {
"$filter": {
"input": "$history",
"as": "item",
"cond": {
"$ne": [
{ "$setIntersection": ["$$item.plugin", arr] },
[]
]
}
}
}
}
}
])
</code></pre>
<p><strong>Sample Output</strong></p>
<pre><code>{
"_id" : ObjectId("57ffe28591f567293497d924"),
"history" : [
{
"plugin" : [
1,
2,
3,
4
]
},
{
"plugin" : [
2,
3,
4,
6
]
}
]
}
</code></pre>
<hr>
<p>As an alternative solution (if your MongoDB version does not support the <strong><a href="https://docs.mongodb.com/v3.2/reference/operator/aggregation/filter/" rel="nofollow"><code>$filter</code></a></strong> operator), consider using a combination of the <strong><a href="https://docs.mongodb.com/v3.2/reference/operator/aggregation/setDifference/#exp._S_setDifference" rel="nofollow"><code>$setDifference</code></a></strong> and <strong><a href="https://docs.mongodb.com/v3.2/reference/operator/aggregation/map/#exp._S_map" rel="nofollow"><code>$map</code></a></strong> operators to return the filtered array:</p>
<pre><code>var arr = [2,7];
db.collection.aggregate([
{ "$match": { "_id": ObjectId("57ffe28591f567293497d924") } }, // <-- filter here
{
"$project": {
"history": {
"$setDifference": [
{
"$map": {
"input": "$history",
"as": "item",
"in": {
"$cond": [
{
"$ne": [
{ "$setIntersection": ["$$item.plugin", arr] },
[]
]
},
"$$item",
false
]
}
}
},
[false]
]
}
}
}
])
</code></pre>
|
C++ - How to write back JSON into file <p>I'm using library from <a href="https://github.com/nlohmann/json" rel="nofollow">https://github.com/nlohmann/json</a><br>
I need to write my JSON into file but I can't find anythink about that in doc.<br>
Anyone can help?</p>
| <p>You can dump the json object into a string with the <code>dump()</code> method and then write that into a file.</p>
|
Create inverse Kaplan Meier curve with response percents and time <p>I am trying to create an inverse KM plot of the time it takes for patients to respond to drug therapy. </p>
<pre><code>Time response
3 57
4 35
4 85
4 90
5 55
6 65
6 89
6 72
9 97
9 89
9 98
10 99
10 92
13 99
14 50
15 97
18 60
21 70
25 76
28 77
40 82
48 86
</code></pre>
<p>Time is in days and response is percentage. At first I thought I could try this using survival analysis but figured a hazard plot would work better. I'm not sure how to go about this.</p>
<p>Here is a link to a published article where the third figure shows this. I'm not an expert on KMplots yet, but any help and criticism would be highly appreciated! </p>
<p><a href="https://www.researchgate.net/publication/7789803_Bortezomib_therapy_alone_and_in_combination_with_dexamethasone_for_previously_untreated_symptomatic_multiple_myeloma" rel="nofollow">https://www.researchgate.net/publication/7789803_Bortezomib_therapy_alone_and_in_combination_with_dexamethasone_for_previously_untreated_symptomatic_multiple_myeloma</a></p>
| <p>For your question to solve I first reorganized your data into survival data I am used to. That is one row per event/censor. Then I fit a survival model and plot the KM.</p>
<pre><code>dt <- as.data.frame(matrix(c(3,57
,4,35
,4,85
,4,90
,5,55
,6,65
,6,89
,6,72
,9,97
,9,89
,9,98
,10,99
,10,92
,13,99
,14,50
,15,97
,18,60
,21,70
,25,76
,28,77
,40,82
,48,86),ncol=2,byrow = TRUE))
colnames(dt) <- c("time","response")
#translate percentage of responders at each time to number of responders if we start with a population of 10000
dt$individuals <- round(10000*sapply((1:nrow(dt)),function(x){prod(dt[1:x,"response"]/100)}))
s <- data.frame(time = with(dt,rep(time, individuals))
,event = 1)
library(survival)
sobj <- Surv(s$time, s$event)
fit <- survfit(sobj ~ 1)
plot(fit, fun="event")
</code></pre>
<p><a href="https://i.stack.imgur.com/RqhzN.png" rel="nofollow"><img src="https://i.stack.imgur.com/RqhzN.png" alt="enter image description here"></a></p>
|
How do I get the total offset of one display object between an ancestor display object? <p>How would I get the distance from a display object in a nested container and a root container like the stage or spark Application? </p>
<p>For example: </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
applicationComplete="applicationCompleteHandler(event)"
>
<fx:Script>
<![CDATA[
protected function applicationCompleteHandler(event:FlexEvent):void {
var point:Point = new Point(nestedButton.x, nestedButton.y);
var localToGlobalPoint:Point = this.localToGlobal(point);
var globalToLocalPoint:Point = this.globalToLocal(point);
var localToContentPoint:Point = this.localToContent(point);
trace("Button x: " + nestedButton.x);
trace("Button layout bounds x: " + nestedButton.getLayoutBoundsX());
trace("Button to main container localToGlobal x: " + localToGlobalPoint.x);
trace("Button to main container globalToLocal x: " + globalToLocalPoint.x);
trace("Button to main container localToContent x: " + localToContentPoint.x);
}
]]>
</fx:Script>
<mx:Canvas id="mainCanvas" top="10" left="10">
<mx:Canvas top="10" left="10">
<s:Group x="10" y="10">
<s:Button id="sparkButton2" label="spark button" x=10 y="10"/>
</s:Group>
</mx:Canvas>
</mx:Canvas>
</s:WindowedApplication>
</code></pre>
<p>If the button is nested in 3 containers and each container is <code>10</code> pixels from the edge of the previous and the button is <code>10</code> pixels from it's edge the total <code>x</code> value should be <code>40</code>. That's not the value I'm getting. The <code>x</code> value in each call is tracing out to <code>0</code>. </p>
| <p>There doesn't seem to be Flash API for this. So it looks like you take the two display objects and get their position globally and then subtract the difference. </p>
<p>Here's a function and it seems like it's working: </p>
<pre><code>public function distanceBetweenDisplayObjects(source:Object, target:Object):Point {
var sourceRelativePoint:Point;
var sourceLocalToGlobalPoint:Point;
var containerLocalToGlobalPoint:Point;
var x:Number;
var y:Number;
var zeroPoint:Point = new Point(0, 0);
sourceLocalToGlobalPoint = source.localToGlobal(zeroPoint);
containerLocalToGlobalPoint = target.localToGlobal(zeroPoint);
var sourceDifference:Point = sourceLocalToGlobalPoint.subtract(containerLocalToGlobalPoint);
var containerDifference:Point = containerLocalToGlobalPoint.subtract(sourceLocalToGlobalPoint);
return sourceDifference;
}
</code></pre>
<p>Usage: </p>
<pre><code>var sourceDifference:Point = distanceBetweenDisplayObjects(nestedButton, mainContainer);
</code></pre>
|
How to count the number of rows updated, on each day/date, for a given range of dates <p>My Oracle table has columns which contain the date (timestamp) on which each row was last updated. Column is defined as timestamp(6).</p>
<p>I need to count the number of rows updated on every day/date, for a given date range.
Example: For every day in September 2016, how many rows were updated?</p>
<p>Example output:</p>
<pre><code>Date Count My Remarks
================= ======= ====================
September 1, 2016 20 20 rows updated on 9/1/16
September 2, 2016 31 31 rows updated on 9/2/16
September 3, 2016 14 14 rows updated on 9/3/16
September 4, 2016 43 43 rows updated on 9/4/16
September 5, 2016 89 89 rows updated on 9/5/16
....
September 30, 2016 74 74 rows updated on 9/30/16
</code></pre>
<p>Can anyone help me with the query?</p>
<p>Thanks in advance,
Rich</p>
| <p>One option would be </p>
<pre><code>SELECT trunc(timestamp_column)
,count(*)
FROM your_table
GROUP BY trunc(timestamp_column)
</code></pre>
<p>You could, of course, create a string for the "My Remarks" column that combined the information from these two columns if that's all that column is doing (in which case I'm not sure why you'd bother...).</p>
|
How to run application in cmd.exe with Inno Setup? <p>Say I want to install an <code>app.exe</code> with Inno Setup, but when the installation is done, I want the program to run </p>
<pre><code>cmd /k app.exe
</code></pre>
<p>instead of just <code>app.exe</code>.</p>
<p>Currently I have:</p>
<pre><code>Filename: "cmd /k {app}\app.exe"; Description: "{cm:LaunchProgram,app}"; \
Flags: nowait postinstall skipifsilent runascurrentuser
</code></pre>
<p>But of course this complains about cannot find the file with the given file name. What should I do?</p>
| <ol>
<li>The command parameters have to go to a separate parameter <code>Parameters</code>. See the documentation for the <a href="http://www.jrsoftware.org/ishelp/index.php?topic=runsection" rel="nofollow"><code>[Run]</code> section</a>.</li>
<li>You have to surround the path to the application with double-quotes as the path may contain a space (and typically does: <code>Program Files</code>). And you need to <a href="http://www.jrsoftware.org/ishelp/index.php?topic=params" rel="nofollow">double the double-quotes</a>.</li>
<li>Use the <a href="http://www.jrsoftware.org/ishelp/index.php?topic=consts&anchor=cmd" rel="nofollow"><code>{cmd}</code> constant</a> instead of an explicit reference to the <code>cmd.exe</code>.</li>
</ol>
<pre><code>Filename: "{cmd}"; Parameters: "/k ""{app}\app.exe"""; \
Description: "{cm:LaunchProgram,app}"; \
Flags: nowait postinstall skipifsilent runascurrentuser
</code></pre>
|
Create a class that contains all functions of its parent class except one <p>Suppose I have two classes,
one is:</p>
<pre><code>class A{
public:
void f1()
{
cout << "function 1";
}
void f2()
{
cout << "function 2";
}
void f3()
{
cout << "function 3";
}
};
</code></pre>
<p>Now I want class <code>B</code> to contain all the functions of <code>A</code> except <code>f3</code>.</p>
<p>what I am doing is:</p>
<pre><code>class B: public A
{
private:
void f3()
{
}
};
</code></pre>
<p>According to my knowledge, <code>B::f3()</code> is hiding the definition of <code>A::f3()</code>, and as <code>B::f3()</code> is private, <code>f3()</code> is not accessible via class <code>B</code>. But what I can still do is call it like this:</p>
<pre><code>B var();
var.A::f3();
</code></pre>
<p>Is there any way I could completely hide <code>f3</code> from class <code>B</code> using inheritance and without changing class <code>A</code>?</p>
| <p>You should <strong>not make <code>B</code> inherit from <code>A</code>.</strong></p>
<p>If <code>B</code> lacks some functionality of <code>A</code>, then <code>B</code> and <code>A</code> do not have the <em>is-a</em> relationship that inheritance is intended to model (and which clients will expect). You should use composition instead: introduce a member of <code>B</code> of type <code>A</code>.</p>
|
Microsoft CRM User Default Form Query <p>We're using Microsoft Dynamics CRM 2016 on-premise. Is there a way to do a database query on the default form that users will see for a specific entity?</p>
<p>The reason I ask, we have a user that has an error when opening an email form:
systemform With Id = a7415a93-0113-4d90-80cd-280e28dfb4f7 Does Not Exist</p>
<p>This might have been an old form that has long been deleted from our system, and I'm wondering if there are any other users that might have this default systemform ID, as it will prevent them from opening that entity.</p>
| <p>Users' most recently viewed forms are stored in the <code>UserEntityUISettingsBase</code> table. You can query the <code>UserEntityUISettings</code> view to see if any users are having the given form as their default form:</p>
<pre><code>SELECT * FROM UserEntityUISettings
WHERE LastViewedFormXml LIKE '%a7415a93-0113-4d90-80cd-280e28dfb4f7%'
</code></pre>
<p>Keep in mind that it is entirely unsupported to update the database directly, so I would strongly recommend that you only stick to querying. If you find any forms this way, you should change them in a supported manner.</p>
|
How can I use PowerShell to install this service fabric project? <p>I have the following folder structure once I package my <a href="https://azure.microsoft.com/en-us/services/service-fabric/" rel="nofollow">Service Fabric</a> <code>NS1.NS2.MicroServicesTest</code> project (written in <code>C#</code>, using <code>.NET</code>):</p>
<pre><code>pkg
|-NS1.NS2.MicroServicesTest.MicroServiceA
|-NS1.NS2.MicroServicesTest.MicroServiceB
|-NS1.NS2.MicroServicesTest.MicroServiceC
|-NS1.NS2.MicroServicesTest.MicroServiceD
|-ApplicationManifest.xml
</code></pre>
<p>I am trying to deploy this package using the following <code>PowerShell</code> script:</p>
<pre><code>Copy-ServiceFabricApplicationPackage pkg -ImageStoreConnectionString file:C:\SfDevCluster\Data\ImageStoreShare -ApplicationPackagePathInImageStore NS1.NS2.MicroServicesTest
Register-ServiceFabricApplicationType NS1.NS2.MicroServicesTest
New-ServiceFabricApplication fabric:/NS1.NS2.MicroServicesTest NS1.NS2.MicroServicesTest 1.0.0
</code></pre>
<p>It fails on the last command, <code>New-ServiceFabricApplication</code>, with the following error:</p>
<blockquote>
<p>New-ServiceFabricApplication : Application type and version not found</p>
</blockquote>
<p>Where have I gone wrong? I have tried to follow this <a href="https://azure.microsoft.com/en-us/documentation/articles/service-fabric-automate-powershell/" rel="nofollow">tutorial</a>, albeit it kind of uses a base case in its example, whereas my project has 4 microservices as part of it, and an odd naming convention, which makes it even more confusing...</p>
<p><strong>Edit</strong>: When I run the <code>Get-ServiceFabricApplicationType</code> command, I see:</p>
<pre><code>ApplicationTypeName : MicroServicesTestType
ApplicationTypeVersion : 1.0.0
DefaultParameters : { "MicroServiceA_InstanceCount" = "-1";
"MicroServiceB_InstanceCount" = "-1";
"MicroServiceC_Endpoint" = "defaultValue";
"MicroServiceC_InstanceCount" = "-1";
"MicroServiceC_MaxRecords" = "100";
"MicroServiceD_InstanceCount" = "-1" }
</code></pre>
| <p>(from discussion to answer)</p>
<ul>
<li><p>After registering it, validate that your Application Type shows up when calling 'Get-ServiceFabricApplicationType'</p></li>
<li><p>Check your Application Type version 1.0.0?</p></li>
<li><p>Try using this command: <code>New-ServiceFabricApplication fabric:/ MicroServicesTestType MicroServicesTestType 1.0.0</code></p></li>
</ul>
|
Redshift (SQL): try convert to timestamp <p>I have a column with timestamps as string, like so:</p>
<pre><code>starttime | attribute
2000-08-21T23:10:37Z | X
</code></pre>
<p>Now I want to convert these strings to proper timestamps in AWS Redshift.
The following works for the row shown in the above example, </p>
<pre><code> CAST(starttime as timestamp)
</code></pre>
<p>but some rows are not in the correct format and hence throw an exception:</p>
<pre><code> error: Invalid data
code: 8001
context: Invalid format or data given:
</code></pre>
<p>Is there a way to use something similar to <strong><em>try_convert</em></strong> available in MS SQL server?
I have tried the following without much success:</p>
<pre><code>case when starttime ~ '\d{1,4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}:\d{1,2}Z'
then cast(starttime as timestamp) else null end
</code></pre>
<p>But this regex expression does not work.. Also tried using [[:digit:]] instead of \d or \d, but nothing works..</p>
<p>To be clear: I know that some rows contain erroneous data so I am not worried about excluding them.</p>
| <p>You missed out a minor detail: change all the <code>\d</code>s to <code>\\d</code>. As per the documentation <a href="http://docs.aws.amazon.com/redshift/latest/dg/pattern-matching-conditions-posix.html" rel="nofollow">here</a>:</p>
<blockquote>
<p>Amazon Redshift supports the following Perl-influenced operators in regular expressions. Escape the operator using two backslashes (â\â).</p>
</blockquote>
<p>I tried the following:</p>
<pre><code>create temp table v (starttime varchar(255));
insert into v values ('2000-08-21T23:10:37Z'), ('ddd');
-- the next line doesn't work, as you yourself suggested.
select CAST(starttime as timestamp) from v;
-- the next line works.
select case when starttime ~ '\\d{1,4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}Z' then cast(starttime as timestamp) else null end from v;
</code></pre>
|
Questions to appear in the same location <p>My form has many Questions. I'm looking for a way to have all my questions appear in one single location rather than one below the other as seen in my code below - </p>
<pre><code><p> <SPAN ID="FirstQuestion"> Blah Blah Blah </p>
<button class="button1" button onclick="Function1()"><span>NEXT</span></button>
<p> <SPAN ID="SecondQuestion"> Blah Blah Blah <br> </p>
<button class="button2" button onclick="Function2()"><span>NEXT</span></button>
<script>
function Function1() {
$( "#SecondQuestion" ).css('visibility', 'visible');
$( "#FirstQuestion" ).css('visibility', 'hidden');
</script>
</code></pre>
<p>I already have almost 30 Questions in the form. I do not want these questions to appear one below other instead once the first question is read and when NEXT button is clicked, the second question should appear on the same location were the first one appeared(of course hiding the first question)
Can this be done or do i have to create separate pages for each question and then link it.
Hope I'm clear.</p>
| <p><code>visibility</code> only masks the element, leaving the space it takes up. Perhaps you want <code>.show()</code>, <code>.hide()</code>?</p>
|
No Write Access on Wordpress Folder permissions for Bitnami running on AWS <p>I recently migrated my Wordpress sites to Bitnami on Amazon Web Services. Everything it up and running from the user's perspective, but I'm struggling with a minor permission issue with the themes folder. When I download (or upload my own) theme, it doesn't have write permissions. Bitnami has this as the default for security purposes but when I had my stuff hosted at GoDaddy, this issue never came up.</p>
<p>The odd time I like to go and edit a theme file directly from Wordpress. I also have a File Manager plugin installed that I'll sometimes use instead of FTP to upload theme files.</p>
<p>I can manually change the permissions, either in FileZilla or using SSH but my curiosity and stubbornness would like to have write permission by default on any themes, new or existing.</p>
<p>Do I need to edit a config file somewhere to make this happen?</p>
| <p>You need to connect to your server via SSH and execute the commands below described in order to assign correct permissions definitively: </p>
<pre><code>sudo chmod -R g+w /opt/bitnami/apps/wordpress/htdocs/wp-content
sudo chown -R bitnami:daemon /opt/bitnami/apps/wordpress/htdocs/wp-content
</code></pre>
<p>Then check again if your themes works as you expected. </p>
<p>You can read our documentation to clarify all this situation: <a href="https://docs.bitnami.com/general/apps/wordpress/" rel="nofollow">https://docs.bitnami.com/general/apps/wordpress/</a></p>
|
how do I reset a input in python <p>so i have this code that basically consists of you asking questions, but i have it so the input answers the question, so you can only ask one question, then you have to reset the whole thing again and again, and i have it to ask you your name first so i want a loop that ignores that.</p>
<pre><code> print("hello,what is your name?")
name = input()
print("hello",name)
while True:
question = input("ask me anything:")
if question == ("what is love"):
print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name)
break
if question == ("i want a dog"):
print("ask your mother, she knows what to do",name)
break
if question == ("what is my name"):
print("your name is",name)
break
</code></pre>
| <p>Get rid of the <code>break</code>s, so the loop keeps prompting for new questions. For performance, change the subsequent <code>if</code> tests to <code>elif</code> tests (not strictly necessary, but it avoids rechecking the string if you get a hit early on):</p>
<pre><code>while True:
question = input("ask me anything:")
if question == "what is love":
print("love is a emotion that makes me uneasy, i'm a inteligence not a human",name)
elif question == "i want a dog":
print("ask your mother, she knows what to do",name)
elif question == "what is my name":
print("your name is",name)
</code></pre>
<p>Of course, in this specific case, you could avoid the repeated tests by using a <code>dict</code> to perform a lookup, making an arbitrary number of prompts possible without repeated tests:</p>
<pre><code># Defined once up front
question_map = {
'what is love': "love is a emotion that makes me uneasy, i'm a inteligence not a human",
'i want a dog': 'ask your mother, she knows what to do',
'what is my name': 'your name is',
# Put as many more mappings as you want, code below doesn't change
# and performance remains similar even for a million+ mappings
}
print("hello,what is your name?")
name = input()
print("hello",name)
while True:
question = input("ask me anything:")
try:
print(question_map[question], name)
except KeyError:
# Or check for "quit"/break the loop/alert to unrecognized question/etc.
pass
</code></pre>
|
C# Generic class definition with inerited class syntax error <p>I've looked at a number of questions related to defining a generic class that inherits a base class, but did not see this case. (Sorry if I missed it.)</p>
<p>My class is a generic class. It inherits a concrete base class. The constructor for the base class takes arguments.</p>
<p>I can make the class definition work if I eliminate the generic specification, as follows:</p>
<pre><code>public class DataItemType : DataItem
{
public DataItemType(string sNameArg, string sAddressArg, bool nWriteAllowedArg)
: base(sNameArg, sAddressArg, nWriteAllowedArg)
{
}
}
</code></pre>
<p>Here is the definition with the generic specification.</p>
<pre><code>public class DataItemType<TValue> : DataItem where TValue : struct
{
public DataItemType<TValue>(string sNameArg, string sAddressArg, bool nWriteAllowedArg)
: base(sNameArg, sAddressArg, nWriteAllowedArg)
{
}
}
</code></pre>
<p>In the class definition line, the IDE complains that there is no argument given that corresponds to the required formal parameter sNameArg of the base class. The IDE offers to create the constructor. But when it does, the syntax fails. (The inserted constructor doesn't seem to make any sense, either, for what it's worth.)</p>
| <p>Just remove the <code><TValue></code> from the row of the constructor in the generic class:</p>
<pre><code>public class DataItem
{
public DataItem(string sNameArg, string sAddressArg, bool nWriteAllowedArg) {}
}
public class DataItemType<TValue> : DataItem where TValue : struct
{
public DataItemType(string sNameArg, string sAddressArg, bool nWriteAllowedArg)
: base(sNameArg, sAddressArg, nWriteAllowedArg)
{
}
}
</code></pre>
<p>The use of the <code>TValue</code> in the generic class is for parameters you pass to functions or return values. But not on the constructor.</p>
<p>You are confusion it with adding the <code><></code> after a function. Adding it there means that the function itself is generic and can receive different types.</p>
<ul>
<li>For Generics on methods see <a href="https://msdn.microsoft.com/en-us/library/twcad0zb.aspx" rel="nofollow">Generic Methods</a></li>
<li>For Generics on classes see <a href="https://msdn.microsoft.com/en-us/library/sz6zd40f.aspx" rel="nofollow">Generic Classes</a></li>
</ul>
<p>If for example you want to receive a parameter in the constructor that is from the generic type then:</p>
<pre><code>public class DataItemType<TValue> : DataItem where TValue : struct
{
public DataItemType(TValue someParameter, string sNameArg, string sAddressArg, bool nWriteAllowedArg)
: base(sNameArg, sAddressArg, nWriteAllowedArg)
{
}
//Note that as in the constructor you can use this generic type for the function
public void SomeFunction(TValue value) { }
//Or define a new generic type which will be only in the scope of this function
public void SomeOtherFunction<TValue2>(TValue2 value2) { }
}
</code></pre>
|
CMake does not find boost_thread <p>I am trying to install the OpenGM library. However, while using CMake, I get the following error:</p>
<pre><code> CMake Error at /usr/local/share/cmake-3.6/Modules/FindBoost.cmake:1753 (message):
Unable to find the requested Boost libraries.
Boost version: 1.62.0
Boost include path: /usr/local/include
Could not find the following Boost libraries:
boost_thread
Some (but not all) of the required Boost libraries were found. You may
need to install these additional Boost libraries. Alternatively, set
BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT
to the location of Boost.
</code></pre>
<p>However, when I do:</p>
<pre><code>ls -l
</code></pre>
<p>in</p>
<pre><code>/usr/local/include
</code></pre>
<p>I get the following line:</p>
<pre><code> lrwxr-xr-x 1 Florian admin 36 13 oct 19:11 boost -> ../Cellar/boost/1.62.0/include/boost
</code></pre>
<p>which suggests that it looks in the right directory.</p>
<p>In:</p>
<pre><code>/usr/local/lib
</code></pre>
<p>I have:</p>
<pre><code>libboost_thread-mt.a
libboost_thread-mt.dylib
</code></pre>
<p>So, it seems that the boost_thread library does exist...</p>
<p>Regarding the CMake configuration related to Boost, I have:</p>
<pre><code> Boost_DIR Boost_DIR-NOTFOUND
Boost_INCLUDE_DIR /usr/local/include
Boost_LIBRARY_DIR_DEBUG /usr/local/lib
Boost_LIBRARY_DIR_RELEASE /usr/local/lib
Boost_PYTHON_LIBRARY_DEBUG /usr/local/lib/libboost_python.dylib
Boost_PYTHON_LIBRARY_RELEASE /usr/local/lib/libboost_python.dylib
</code></pre>
<p>If it can help, I am under Mac OSX and Boost was installed through:</p>
<pre><code>brew install boost --with-python
brew install boost-python
</code></pre>
| <p>I have managed to handle this error by setting the Boost multithreading flag to ON n CMakeLists.txt.</p>
|
Javascript - Calculate missing 5 stars to reach desired rating <p>I would like to make a script that calculate how many "5" I need to reach 4.95 rating.</p>
<p>I created an object:</p>
<pre><code>var obMed = {
5: 0,
4: 0,
3: 0,
2: 0,
1: 0
};
</code></pre>
<p>I got this function to update previous object with my rating</p>
<pre><code>function upOB(a,b,c,d,e) {
obMed["5"] = a;
obMed["4"] = b;
obMed["3"] = c;
obMed["2"] = d;
obMed["1"] = e;
return obMed;
}
</code></pre>
<p>And this function to get the rating value</p>
<pre><code>function med(obj) {
div = obj["5"] + obj["4"] + obj["3"] + obj["2"] + obj["1"];
somma = (obj["5"] * 5) + (obj["4"] * 4) + (obj["3"] * 3) + (obj["2"] * 2) + (obj["1"] * 1);
media = (somma/div).toFixed(2);
return media;
}
</code></pre>
<p>At this point I would like to add 1 to object["5"] until my average is greater than or equal to 4.95 but I'm really stuck.</p>
<p>I tried loops with no results, probably I wrote them bad.</p>
| <p>If you do the equations you get the following relation (using the same variable names that your code uses)</p>
<pre><code>function getNeed(div, somma) {
return Math.ceil((4.95*div - somma) / 0.05);
}
</code></pre>
<p>As I understand that <code>div</code> is the total amount of votes sent, and <code>somma</code> is the sum of all scores.</p>
<p><br>
<strong>Math behind the method</strong> </p>
<p>current score: <code>somma / div</code><br>
if you add <code>N</code> votes of 5 stars, the new score would be: <code>(somma + N * 5) / (div + N)</code><br>
If you want that to be equal to 4.95, then you do <code>(somma + N * 5) / (div + N) = 4.95</code>, and the result is that:<br>
<code>N = (4.95*div - somma) / 0.05</code> </p>
<p>Then you'll have to ceil that value as @dvsoukup commented, as you cannot have a non-integer amount of votes. This way, for example, you would have as a result 7 if the value of the computed <code>N</code> was 6.72.</p>
|
Renumbering Identical Field Values <p>I have a table with field values that are identical (0). I want to renumber them sequentially backwards starting with -1. There are about 1800 rows with this field value. Is there a way to do this with a query? I'd rather not use VBA for this task if I don't have to.</p>
| <p>You can use an autonumber field to generate your numbers.</p>
<p>Since you have rows with different values than 0 in the field you need to number, it gets sloppy. You would extract the '0' rows, place them an interim table with its own autonumber field (start value 1, increment by +1), run this query (for this example it would be called newnum_qry).</p>
<pre><code>SELECT autonumber, autonumber-(autonumber*2) as newnumber , [your other columns]
FROM int_tbl
</code></pre>
<p>and then return the rows to the original table, leaving the autonumber from the interim table behind. Query to remerge:</p>
<pre><code>SELECT source_of_zeroes, null as newnumber, [your other columns]
FROM orig_tbl
WHERE source_of_zeroes != 0
UNION
SELECT source_of_zeroes, newnumber, [your other columns]
FROM newnum_qry
</code></pre>
<p>This is solution is, IMO, really junky. There's should be a better way, but as is often the case in Access, junk may be the best you can do.</p>
|
How to Get key value pair tuple array in swift? <p>I have pairs tuple array pickerDataVisitLocation.just I want to know how to return key value pair location from my array using uniqId ex 204 </p>
<pre><code>var pickerDataVisitLocation:[(uniqId:Int,location:String)] = [(203,"Home"),(204,"Hospital"),(205,"Other")]
var selectedIndex = pickerDataVisitLocation[1].uniqId
pickerDataVisitLocation[selectedIndex].location //<--fatal error: Index out of range
</code></pre>
| <p>According to the given code: <br>Try this</p>
<pre><code>var pickerDataVisitLocation:[(uniqId:Int,location:String)] = [(203,"Home"),(204,"Hospital"),(205,"Other")]
let selectedIndex = pickerDataVisitLocation[1].uniqId
var location = ""
for item in pickerDataVisitLocation {
if item.uniqId == selectedIndex {
location = item.location
}
}
print(location) //Will print Hospital here
</code></pre>
|
Grouping columns into count in R dataframe <p>So i have these 4 different cols in total in a dataframe</p>
<pre><code> port ip service numberOfTimes
1 22 11.11.79.100 ssh 16
2 80 11.11.79.100 www 19
3 111 11.13.79.110 ipw 21
4 123 11.13.79.110 ssh 50
5 22 64.50.80.140 cde 45
6 80 64.50.80.140 www 16
7 22 71.11.64.100 ssh 234
8 80 71.11.64.100 you 33
9 22 100.15.31.1 ssh 99
10 41 120.15.31.12 has 19
</code></pre>
<p>So I have the following question:</p>
<p>Is it possible to group using r to the following such that it can become something like that?</p>
<p><strong>After</strong></p>
<pre><code>port ip(count of same ip) service numberOfTimes
22 4 ssh 399 (#1+#5+#7+#9)
80 3 www 68 (#2+#6+#8)
</code></pre>
<p>so on and so for the rest of the ports</p>
| <p>Using <code>dplyr</code>, this is quite straightforward:</p>
<pre><code>testData %>%
group_by(port, service) %>%
summarise(`Number of IPs` = n_distinct(ip)
, `Total number of times` = sum(numberOfTimes))
</code></pre>
<p>Which for the sample data you included gives:</p>
<pre><code> port service `Number of IPs` `Total number of times`
<int> <chr> <int> <int>
1 22 cde 1 45
2 22 ssh 3 349
3 41 has 1 19
4 80 www 2 35
5 80 you 1 33
6 111 ipw 1 21
7 123 ssh 1 50
</code></pre>
<p>If you are getting some sort of an error (alluded to in a comment), you will need to provide data that actually causes that error before people can help you.</p>
|
Making JavaScript items independent <p>I'm using a jQuery script to expand/collapse a div on a page an it works perfectly. I'm now trying to replicate the code so there are two divs which do the same but I want them to be independent however when I click one, both open/close. Just wondering what i'm doing wrong? </p>
<p>So far, I have the following HTML:</p>
<pre><code> <div class="infoToggle1">
<div class="panel-controller">
<div class="tab-controller1">
<span class="close">CLOSE</span>
<span class="show">MORE INFO</span>
</div>
</div>
<div class="panel-content1">
Content goes here
</div>
</div>
<div class="infoToggle2">
<div class="panel-controller">
<div class="tab-controller2">
<span class="close">CLOSE</span>
<span class="show">MORE INFO</span>
</div>
</div>
<div class="panel-content2">
Content goes here
</div>
</div>
</code></pre>
<p>and the following jQuery code:</p>
<pre><code>(function($) {
jQuery(document).ready(function() {
Panel.init();
$(document).on('click', '.tab-controller1, .tab-controller2', function() {
Panel.togglePanel();
});
});
var Panel = {
isVisible : false,
showMessage : null,
hideMessage : null,
animationDuration : 300,
animationEasing : 'linear',
init: function() {
Panel.hidePanel();
},
hidePanel : function() {
$('.infoToggle1, .infoToggle2').animate({
bottom : -(Panel.getAnimationOffset())
}, Panel.animationDuration, Panel.animationEasing, function() {
Panel.isVisible = false;
Panel.updateTabMessage();
});
},
showPanel : function() {
$('.infoToggle1, .infoToggle2').animate({
bottom : 0
}, Panel.animationDuration, Panel.animationEasing, function() {
Panel.isVisible = true;
Panel.updateTabMessage();
});
},
togglePanel : function() {
((this.isVisible) ? this.hidePanel : this.showPanel)();
},
updateTabMessage : function() {
if (this.isVisible) {
$('.tab-controller1 .close, .tab-controller2 .close').show();
$('.tab-controller1 .show, .tab-controller2 .show').hide();
} else {
$('.tab-controller1 .close, .tab-controller2 .close').hide();
$('.tab-controller1 .show, .tab-controller2 .show').show();
}
},
getAnimationOffset : function() {
return $('.panel-content1, .panel-content2').height();
}
}
})(jQuery);
</code></pre>
<p>Thanks in advance!</p>
| <p>Instead of using a class selector for your open/close animation try focusing on referencing your element in relation to the item clicked.</p>
|
Map requests to other directory with htaccess without redirect <p>I have a project structure like this:</p>
<pre><code>/php/
rest.php
/public/
index.html
/src/
/css
/js
/img
/src/
/sql/
.htaccess
</code></pre>
<p>I think it would be pretty nice if only files in /public/ would be accessable via the web. I would like to access these files via <strong>domain.tld/</strong> instead of <strong>domain.tld/public</strong>. How can I map the requests from / to /public?</p>
<p>Tried something like this but it doesn't work!</p>
<pre><code>RewriteEngine on
RewriteRule ^(.*)$ /public/$1
</code></pre>
| <p>You can use this rule in site root .htaccess:</p>
<pre><code>RewriteEngine on
RewriteRule ^(?!public/)(.*)$ public/$1 [L,NC]
</code></pre>
<p><code>(?!public/)</code> is negative lookahead to prevent infinite looping, that avoid forwarding to <code>/public/</code> if URI already starts with <code>/public/</code>.</p>
|
How to install Baidu's PaddlePaddle on ubuntu 16.04? <p>I recently wanted to install PaddlePaddle on ubuntu 16, but there's a missing dependency, the package requires libgflags2, I couldn't find this library on Ubuntu's canonical repos, I found libgflags2v5 instead, so I played a little with the paddle's package dependencies and changed "libgflags2" to "libgflags2v5", and the installation was successful, but the package crashes when I use this command</p>
<blockquote>
<p>paddle train --help</p>
</blockquote>
<p>I later on understood that the package works fine on ubuntu 14.04, but unfortunately I can't degrade to that version and I have to use version 16, so how do I deal with this?</p>
<p>EDIT: <br>
When I run this command </p>
<blockquote>
<p>paddle train --help</p>
</blockquote>
<p>I get this error</p>
<blockquote>
<p>I1014 10:38:32.837656 3658 Util.cpp:151] commandline:
/usr/bin/../opt/paddle/bin/paddle_trainer --help <br>paddle_trainer:
Warning: SetUsageMessage() never called<br> terminate called after
throwing an instance of 'std::bad_alloc'<br> what(): std::bad_alloc<br>
<strong>* Aborted at 1476434312 (unix time) try "date -d @1476434312" if you are using GNU date <em></strong> <br>PC: @ 0x7f8e7ed14418 gsignal<br>
<strong></em> SIGABRT (@0x3e800000e4a) received by PID 3658 (TID 0x7f8e80e68740) from PID 3658; stack trace: *</strong><br>
@ 0x7f8e8075e3d0 (unknown)<br>
@ 0x7f8e7ed14418 gsignal<br>
@ 0x7f8e7ed1601a abort<br>
@ 0x7f8e7f65684d __gnu_cxx::__verbose_terminate_handler()<br>
@ 0x7f8e7f6546b6 (unknown)<br>
@ 0x7f8e7f654701 std::terminate()<br>
@ 0x7f8e7f654919 __cxa_throw<br>
@ 0x7f8e7f654ebc operator new()<br>
@ 0x7f8e7f94ee6d (unknown)<br>
@ 0x7f8e7f94f619 (unknown)<br>
@ 0x7f8e7f94f830 (unknown)<br>
@ 0x7f8e7f95629a google::GetAllFlags()<br>
@ 0x7f8e7f95d707 (unknown)<br>
@ 0x7f8e7f95dda2 google::ShowUsageWithFlagsRestrict()<br>
@ 0x7f8e7f95e56f google::HandleCommandLineHelpFlags()<br>
@ 0x7f8e7f9554db (unknown)<br>
@ 0x74a8f5 paddle::ParseCommandLineFlags()<br>
@ 0x748341 paddle::initMain()<br>
@ 0x509a3b main<br>
@ 0x7f8e7ecff830 __libc_start_main<br>
@ 0x515455 (unknown)<br>
@ 0x0 (unknown) /usr/bin/paddle: line 81: 3658 <br>Aborted (core dumped) ${DEBUGGER}
$MYDIR/../opt/paddle/bin/paddle_trainer ${@:2}<br></p>
</blockquote>
| <p>Out of the box installation, see <a href="http://www.paddlepaddle.org/doc/build/" rel="nofollow">http://www.paddlepaddle.org/doc/build/</a></p>
<p>For Ubuntu without GPU:</p>
<pre><code>sudo apt-get install gdebi
wget https://github.com/baidu/Paddle/releases/download/V0.8.0b1/paddle-cpu-0.8.0b1-Linux.deb
gdebi paddle-*.deb
sudo paddle version
</code></pre>
<p>Building from source, see <a href="http://www.paddlepaddle.org/doc/build/build_from_source.html" rel="nofollow">http://www.paddlepaddle.org/doc/build/build_from_source.html</a></p>
|
Why ion auth library use custom where() instead of using the native where() CI provided <pre><code> public function groups()
{
$this->trigger_events('groups');
// run each where that was passed
if (isset($this->_ion_where) && !empty($this->_ion_where))
{
foreach ($this->_ion_where as $where)
{
$this->db->where($where);
}
$this->_ion_where = array();
}
if (isset($this->_ion_limit) && isset($this->_ion_offset))
{
$this->db->limit($this->_ion_limit, $this->_ion_offset);
$this->_ion_limit = NULL;
$this->_ion_offset = NULL;
}
else if (isset($this->_ion_limit))
{
$this->db->limit($this->_ion_limit);
$this->_ion_limit = NULL;
}
// set the order
if (isset($this->_ion_order_by) && isset($this->_ion_order))
{
$this->db->order_by($this->_ion_order_by, $this->_ion_order);
}
$this->response = $this->db->get($this->tables['groups']);
return $this;
}
</code></pre>
<p>It seems nonsense to me as you can see from the groups() function above, why use the custom _ion_limit, _ion_offset, _ion_where when CI has already give you the choice to write native where()->limit()->get(), keep its own private _ion_limit, _ion_offset, _ion_where private property does anything good to the workflow? DO I miss some part here or is there some design pattern involved here?</p>
| <p>It seems to me the main reason is to implement event hook functionality. All the "duplicate" db functions make a call to <code>$this->trigger_events()</code> which in turn calls any function provided to <code>set_hook()</code>. </p>
<p>I have a really vague recollection of noticing some other decent reason. But that was back quite a long time and I cannot remember what it was. </p>
|
Idle timer never activated so App never sleeps <p>I have an app with a sleep timer where the user can select that after a certain duration of time, the app will suspend. Basically what I do is:</p>
<ol>
<li><p>Use this code at the start of the app to disable the app timer:</p>
<p>[[UIApplication sharedApplication] setIdleTimerDisabled: YES];</p></li>
<li><p>When the sleep timer expires:</p>
<p>[[UIApplication sharedApplication] setIdleTimerDisabled: NO];</p></li>
</ol>
<p>Once the the Auto-Lock value in the user preferences is up, the screen dims and the app goes asleep.</p>
<p>It was working fine but no longer for some reason. I'm troubleshooting and have commented out the commands involving setIdleTimerDisabled still it never goes to sleep. </p>
<p>If I test the state of the idleTimer with ([UIApplication sharedApplication].isIdleTimerDisabled) I can see that IdleTimer is not actually disabled so it can't be that.</p>
<p>What else could be preventing a device from sleeping? when app is left without any interaction. My device is running 9.3.3 in case that's useful.</p>
| <p>I think I found the answer â there were actually two problems.
1. So long as I'm running and building on Xcode, the app will never go to sleep (I think).
2. My app has sound so I'm doing something like this to ensure the controls and audio still work in when the device is locked:</p>
<pre><code>audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
</code></pre>
<p>This however prevents the device from sleeping â the sound keeps playing. So what I do now is, once the screen is locked, I change the category of the audioSession to </p>
<pre><code>[audioSession setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
</code></pre>
<p>That however causes another problem which I haven't figured out yetâ¦</p>
|
How to implement database download at install and after in app purchase <p>My app is an e-learning app. Content is served from a database on the user's device. Currently my database is 'Realm' and not 'SQLite'. My question is: How do I have my users download part of the database on installation and then as they progress, be able to download more of the database after making in app purchases? </p>
<p>I have done some reading and have come to think that the way forward, would be to use a Content Provider or Google Cloud Storage. Could you please point me in the right direction? Any tutorials would be appreciated as I am quite new to Android.</p>
<p>In a nutshell: </p>
<ol>
<li>User installs app</li>
<li>App downloads part of the database</li>
<li>User makes an in app purchase</li>
<li>App downloads the next part of the database</li>
</ol>
<p>I hope this isn't too much of a general question.</p>
| <p>My question was too much of a generalisation, but bottled down, <strong>Firebase Database</strong> is the way to go if your files aren't Gigabytes big. Did my research, designed my solution, works perfectly, is elegant and if anyone's interested post on this thread, I'd be glad to lay everything down, just don't know where to start laying it down from as it involves stuff that wasn't originally part of the tags I'd thought were essential.</p>
|
Double Click on Edge of Cell Jump (How to Disable?) <p>The code takes an active cell and if it is in the appropriate column, and has the value "YES" it runs one of two codes (depending on whether it is a summary or an individual value). This done on 'raw' data that is not in a table or pivot table. </p>
<p>About half the time that I double click on any cell in that sheet it jumps my active cell to either the top or bottom of the range of cells. What is causing this? What can I do to fix it?</p>
<p>This happens on both "YES" and "NO" cells.</p>
<p>Edit: Figured it out. It's an excel shortcut I was not aware of (I don't use the mouse much on excel). Double clicking a cells border jumps you to the top or bottom of that section. Is there a way in VBA to disable this 'feature' for a specific sheet. I can't seem to find any info on Google about it...</p>
<p>Edit 2: Found this: <a href="http://superuser.com/questions/610805/disable-navigate-to-end-of-list-when-double-clicking-on-border-of-selected-cell">http://superuser.com/questions/610805/disable-navigate-to-end-of-list-when-double-clicking-on-border-of-selected-cell</a>
But I do not want to disable drag and drop in the worksheet AND I want to do it with VBA. </p>
<pre><code>Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Value <> "YES" Then
Exit Sub
Else
If Target.Column <> 11 Then
Exit Sub
Else
Cancel = False
Dim j As String
Dim k As String
Dim i As Range
Application.ScreenUpdating = False
Set i = Target
k = i.Offset(0, -7).Value 'First value for filter
Worksheets("Comments").Activate
If Worksheets("Comments").AutoFilterMode = True Then
Worksheets("Comments").AutoFilterMode = False
End If
If i.Offset(-1, 0).Value = "Comments" Then
j = i.Offset(-1, -9).Value
Worksheets("Comments").Range("C2").AutoFilter Field:=3, Criteria1:=j
Else
j = i.Offset(0, -9).Value
Worksheets("Comments").Range("C2").AutoFilter Field:=4, Criteria1:=k
Worksheets("Comments").Range("C2").AutoFilter Field:=3, Criteria1:=j
End If
Application.ScreenUpdating = True
Worksheets("Comments").Range("A1").Activate
End If
End If
Cancel = True
End Sub
</code></pre>
| <p>First of all, let me organize your code, it is not very easy to read. Hope this works, I cannot try it right now.</p>
<pre><code>Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim j As String
Dim k As String
Dim i As Range
Application.ScreenUpdating = False
Cancel = False
Set i = Target
If Target.Value <> "YES" and Target.Column <> 11 Then
Application.ScreenUpdating = True
Exit Sub
Else
Application.CellDragAndDrop = False
k = i.Offset(0, -7).Value 'First value for filter
Worksheets("Comments").Activate
If Worksheets("Comments").AutoFilterMode = True Then
Worksheets("Comments").AutoFilterMode = False
End If
If i.Offset(-1, 0).Value = "Comments" Then
j = i.Offset(-1, -9).Value
Worksheets("Comments").Range("C:C").AutoFilter Field:=3, Criteria1:=j
Else
j = i.Offset(0, -9).Value
Worksheets("Comments").Range("C:C").AutoFilter Field:=4, Criteria1:=k
Worksheets("Comments").Range("C:C").AutoFilter Field:=3, Criteria1:=j
End If
Application.ScreenUpdating = True
Worksheets("Comments").Range("A1").select
End If
Application.CellDragAndDrop = true
Cancel = True
End Sub
</code></pre>
|
Is it necessary to explicitly instantiate an array in java? <p>How does instantiation work in this code:</p>
<pre><code>// decleration
dataType[] arrayRefVar;
//instantiation - is it required?
arrayRefVar = new dataType[arraySize]; //A
arrayRefVar[0]=1; //B
arrayRefVar[1]=2;
</code></pre>
<p>I am from a C++ background, so i don't really understand creation of objects/arrays with 'new'. I know it is for allocating memory to the array and returning reference. Will the creation of array take place automatically at B if line A is skipped?</p>
<p><strong>Edit:</strong> Found a similar one, if anyone interested:
<a href="https://stackoverflow.com/questions/5387643/array-initialization-syntax-when-not-in-a-declaration">Array initialization syntax when not in a declaration</a> </p>
| <p>This is just reference(pointer) declaration but not object creation </p>
<pre><code>// decleration
dataType[] arrayRefVar;
</code></pre>
<p><strong>new</strong> keyword specifies that new memory location for given Type has to be created. This step is your actual object creation not the above step.You are pointing the reference named <strong>arrayRefVar</strong> to the newely created object. </p>
<pre><code>//instantiation -
arrayRefVar = new dataType[arraySize]; //A
</code></pre>
<p>Without step 2, you will get NullPointerException.Meaning your trying to assign value to an object which does not exist </p>
|
What Regular Expression would Pass these Conditions? <p>How do i write regular expression to pass the following?</p>
<pre><code>LastName
LastName SecondLastName
LastName-SecondLastName
LastName, F
LastName SecondLastName, F
LastName-SecondLastName, F
LastName, FirstName
LastName SecondLastName, FirstName
LastName-SecondLastName, FirstName
LastName SecondLastName, FirstName SecondFirstName
LastName SecondLastName, FirstName-SecondFirstName
LastName-SecondLastName, FirstName-SecondFirstName
</code></pre>
<p>At the same time, atleast the following should fail:</p>
<pre><code>Any special Character (,?!#@%* etc) at the begining
,FirstName
, FirstName
LastName,
LastName,Any special Character (,?!#@%* etc)
LastName,FirstName
</code></pre>
<p>Basically, after a comma, there should be a space and alpha character(s)</p>
<p>Resources:</p>
<p><a href="https://regex101.com/" rel="nofollow">https://regex101.com/</a></p>
<pre><code>[A-Za-z]+,\s+[A-Za-z]+
</code></pre>
<p>Thanks in advance! :)</p>
| <p>How about you try something like:</p>
<pre><code>^[a-zA-Z]+([- ][a-zA-Z]+)?(, [a-zA-Z]+([- ][a-zA-Z]+)?)?$
</code></pre>
<p>Example: <a href="https://regex101.com/r/ipffrk/3" rel="nofollow">https://regex101.com/r/ipffrk/3</a></p>
|
converting LocalDate to GregorianCalendar in java <p>I want to convert LocalDate to GregorianCalendar. Please advice.
In my application we are using GregorianCalendar to work with date's. But i got a joda LocalDate as a return type when i called one of the webservice.
Now i want to convert that LocalDate to GregorianCalendar as its differing with the month value display. Please see the sample code below.
LocalDate displays 10 for the month October whereas GregorianCalendar display 9 for the month October as it starts from index 0.
Please suggest how to convert LocalDate to GregorianCalendar, i tried to see API methods but with no luck.</p>
<pre><code>import java.util.GregorianCalendar;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
//sample code below
LocalDate localDateObj = new LocalDate();
System.out.println("Month value using LocalDate :" + localDateObj.getMonthOfYear());
System.out.println("Date using LocalDate : " + localDateObj);
//converting LocalDate to DateTime
DateTime dateTimeObj = localDateObj.toDateTimeAtStartOfDay();
System.out.println("DateTime month " + dateTimeObj.getMonthOfYear());
System.out.println("Date using DateTime : " + dateTimeObj);
//GregorianCalendar
GregorianCalendar gc = new GregorianCalendar();
System.out.println("Month value using GregorianCalendar:" + gc.OCTOBER);
System.out.println("GC :" + gc.getTime());
</code></pre>
<p>Output:</p>
<pre><code>Month value using LocalDate :10
Date using LocalDate : 2016-10-13
DateTime month 10
Date using DateTime : 2016-10-13T00:00:00.000-04:00
Month value using GregorianCalendar:9
GC :Thu Oct 13 16:14:43 EDT 2016
</code></pre>
<p>Please advice how to convert <strong>org.joda.time.LocalDate to java.util.GregorianCalendar</strong> or is there any better way to solve this. As I cannot modify the logic which is using GregorianCalendar , so I want to change the logic which is using joda LocalDate to display the month as GregorianCalendar(ex.,for October month it displays 9 as index start from 0 to 11).</p>
| <p>Try this example to convert LocalDate to GregorianCalendar </p>
<pre><code>LocalDate localDateObj = LocalDate.now();
GregorianCalendar gc = GregorianCalendar.from(localDateObj.atStartOfDay(ZoneId.systemDefault()));
</code></pre>
<p>Note: gc.OCTOBER is set to 9 but it is indicating the tenth month of the year in the Gregorian and Julian calendars.</p>
<p>Hope this help!</p>
|
For a spring application, do changes made to application context propagation levels take immediate effect? <p>I have a web application in production that is based on spring transactions. propagation levels are set in applicationcontext.xml. Will tomcat pick up any change I make to the propagation levels in this xml with a restart? of do I have to redeploy the entire war?</p>
| <p>Usually, applicationContext.xml will be IN your WAR file. In this case you will need to redeploy it.
If for some reason it is outside your WAR, then changing it and restarting tomcat will be OK.
PS of course you can change the applicationContext.xml in the exploded version of your WAR but this is not suggested as changes will be overridden on the next deployment.</p>
|
php array syntax ${ is confusing me <p>I create a $values array and then extract the elements into local scope.</p>
<pre><code> $values['status'.$i] = $newStatus[$i];
extract($values);
</code></pre>
<p>When I render an html page. I'm using the following</p>
<pre><code> <?php if(${'status'.$i} == 'OUT'){ ?>
</code></pre>
<p>but am confused by what the ${ is doing and why $status.$i won't resolve</p>
| <p><code>$status.$i</code> means </p>
<blockquote>
<p>take value of <code>$status</code> variable and concatenate it with value of <code>$i</code> variable.</p>
</blockquote>
<p><code>${'status'.$i}</code> means</p>
<blockquote>
<p>take value of <code>$i</code> variable, append id to <code>'status'</code> string and take value of a variable <code>'status'.$i</code></p>
</blockquote>
<p><strong>Example:</strong></p>
<p>With <code>$i</code> equals <code>'2'</code> and <code>$status</code> equals <code>'someStatus'</code>:</p>
<ul>
<li><p><code>$status.$i</code> evaluated to <code>'someStatus' . '2'</code>, which is <code>'someStatus2'</code></p></li>
<li><p><code>${'status'.$i}</code> evaluated to <code>${'status'.'2'}</code> which is <code>$status2</code>. And if <code>$status2</code> is defined variable - you will get some value.</p></li>
</ul>
|
Why is my image being distorted (shrunk) in Firefox? <p>This problem occurs on Firefox. On Chrome all is well. </p>
<p>I have a magnifying glass image next to my search fields.</p>
<p>However, on Firefox the image is being distorted (shrunk) and I canât figure out why.</p>
<p>Hereâs the Fiddle â <a href="https://jsfiddle.net/k01jLb28/3/" rel="nofollow">https://jsfiddle.net/k01jLb28/3/</a>. </p>
<p>Here are the styles Iâm applying to my search fields:</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-css lang-css prettyprint-override"><code>*/@media screen and (max-width: 500px) {
/* line 19, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
body {
margin: 0px;
}
/* line 23, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#container {
border-radius: 0px;
background: #ffffff;
padding: 2px;
width: 100%;
}
}
/* line 31, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
ul.nav {
font-family: 'russo_oneregular';
letter-spacing: 1px;
}
/* line 35, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
ul.nav li.ui-state-active,
ul.nav li.ui-tabs-selected {
font-weight: bold;
color: #000000;
}
/* line 40, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
ul.nav li.ui-tabs-active a,
ul.nav li.ui-tabs-selected a {
background-color: silver;
color: #ffffff;
}
/* line 46, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.ui-tabs-panel {
height: 0px;
}
/* line 50, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#add_form {
display: none;
box-shadow: inset 0 0 10px #000000;
padding: 20px;
background-color: #f0f0f0;
}
/* line 59, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#headerText {
font-family: 'russo_oneregular';
font-weight: bold;
font-size: 24px;
text-align: center;
}
/* line 66, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.tab {
font-family: 'russo_oneregular';
}
/* line 70, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.field {
font-family: Arial;
font-size: 11px;
padding: 5px;
}
/* line 76, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.required {
color: red;
}
/* line 80, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.errorMsg {
color: red;
}
/* line 84, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#modalCloseButton {
position: absolute;
top: 10px;
right: 10px;
cursor: pointer;
}
/* line 91, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.modal_button {
border: 1px solid #a8c1d5;
border-radius: 8px;
font-size: 14px;
font-family: arial, helvetica, sans-serif;
padding: 10px 10px 10px 10px;
text-decoration: none;
display: inline-block;
text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3);
font-weight: bold;
color: #FFFFFF;
background-color: #CEDCE7;
background-image: -webkit-gradient(linear, left top, left bottom, from(#CEDCE7), to(#596a72));
background-image: -webkit-linear-gradient(top, #CEDCE7, #596a72);
background-image: linear-gradient(to bottom, #CEDCE7, #596a72);
filter: progid: DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#CEDCE7, endColorstr=#596a72);
}
.modal_button:hover {
border: 1px solid #8aabc5;
background-color: #acc4d6;
background-image: -webkit-gradient(linear, left top, left bottom, from(#acc4d6), to(#434f55));
background-image: -webkit-linear-gradient(top, #acc4d6, #434f55);
background-image: linear-gradient(to bottom, #acc4d6, #434f55);
filter: progid: DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#acc4d6, endColorstr=#434f55);
}
/* line 113, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.modal a.close-modal {
display: none;
}
/* line 117, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.noRaceData {
font-family: Verdana;
}
/* line 122, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchContainer {
padding: 10px;
font-family: "Calibre", "Helvetica Neue", "Helvetica", "Roboto", "Arial", sans-serif;
background-color: tan;
max-width: 1000px;
width: 100%;
display: inline-block;
-webkit-box-flex: 1;
-ms-flex: 1 0 auto;
flex: 1 0 auto;
box-sizing: border-box;
}
/* line 132, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchContainer h1 {
margin: 5px 0;
font-size: 1.0em;
}
/* line 137, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#search-form {
display: -webkit-inline-box;
display: -ms-inline-flexbox;
display: inline-flex;
/*In screen >400px input element will be inline*/
width: 100%;
}
/* line 143, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#first_name,
#last_name {
width: 40%;
/*make the width like event so all the input fields looks good*/
}
/* line 149, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#event {
width: 100%;
}
#last_name,
#event {
margin-left: 2px;
}
/* line 158, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#event {
margin-right: 2px;
}
@media only screen and (max-width: 400px) {
/*set the max width 400px so they will wrap after the media screen reach 400px*/
/* line 164, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#search-form {
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
/* line 168, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#first_name {
width: calc(50% - 8px);
margin: 0;
}
/* line 172, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#last_name {
width: calc(50% - 8px);
margin-left: 2px;
}
/* line 176, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#first_name,
#last_name {
margin-bottom: 1px;
}
/* line 152, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
/* line 181, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#event {
width: calc(100% - 35px);
margin-right: 2px;
}
/* line 185, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
input.search_button {
/* Search-button will be center when meda screen < 400px */
}
}
/* line 192, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#search_form {
display: table-cell;
padding: 0px;
}
/* line 196, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#search_form form input {
vertical-align: middle;
}
#searchResultsContainer {
font-family: "Calibre", "Helvetica Neue", "Helvetica", "Roboto", "Arial", sans-serif;
padding: 5px 0px 5px 0px;
width: 100%;
}
/* line 206, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchResults {
width: 100%;
text-align: left;
}
/* line 211, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.eventNameSearchResult {
text-decoration: none;
}
@media screen and (max-width: 400px) {
/* line 216, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
.saveHeader {
display: none;
}
/* line 219, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchResults th:nth-of-type(3) {
display: none;
}
/* line 222, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchResults th:nth-of-type(6) {
display: none;
}
/* line 225, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchResults td:nth-of-type(3) {
display: none;
}
/* line 228, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchResults td:nth-of-type(6) {
display: none;
}
}
@media screen and (min-width: 401px) {
/* line 234, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchResults th:nth-of-type(2) {
display: none;
}
/* line 237, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchResults td:nth-of-type(2) {
display: none;
}
}
/* line 242, /Users/davea/Documents/workspace/runtrax/app/assets/stylesheets/events.css.scss */
#searchResults thead tr {
background-color: #000000;
color: #ffffff;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="searchContainer">
<h1>Search For Events:</h1>
<form id="search-form" action="/races/search" accept-charset="UTF-8" method="get">
<input name="utf8" type="hidden" value="â">
<input type="text" name="first_name" id="first_name" value="Dave" placeholder="First Name">
<input type="text" name="last_name" id="last_name" value="" placeholder="Last Name">
<input type="text" name="event" id="event" value="" placeholder="Event">
<input alt="Search" type="image" src="http://www.racertracks.com/assets/magnifying-glass-0220f37269f90a370c3bb60229240f2ef2a4e15b335cd42e64563ba65e4f22e4.png" class="search_button">
</form>
</div></code></pre>
</div>
</div>
</p>
| <p>An initial setting of a flex container is <code>flex-shrink: 1</code> (<a href="https://www.w3.org/TR/css-flexbox-1/#flex-shrink-property" rel="nofollow">source</a>).</p>
<p>This means that, by default, flex items are allowed to shrink below their initial size in order to fit inside the container.</p>
<p>For your layout to work in Firefox you need to disable <code>flex-shrink</code> on the image. </p>
<p>Add this to your code:</p>
<pre><code>.search_button { flex-shrink: 0; }
</code></pre>
<p><a href="https://jsfiddle.net/k01jLb28/4/" rel="nofollow">revised fiddle</a></p>
<p>As to why this is needed in Firefox but not Chrome, I would say that flex layout is relatively new (CSS3) and different browsers have different implementations and interpretations of spec language.</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>As pointed out by <a href="http://stackoverflow.com/users/1529630/oriol">@Oriol</a> in <a href="http://stackoverflow.com/a/40065549/3597276">an answer</a>, another initial setting of a flex container is <code>min-width: auto</code> on flex items. This means that a flex item cannot be smaller than the size of its content.</p>
<p>Chrome has implemented this spec instruction. It appears that Firefox has not (at least in terms of replaced elements?), and the flex item is shrinking below the inherent size of the image. </p>
<p>More details here:</p>
<ul>
<li><a href="http://stackoverflow.com/q/36247140/3597276">Why doesn't flex item shrink past content size?</a></li>
</ul>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.