text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How do I get the pcap lib on Ubuntu?
I have a programming assignment where I need to use the pcap lib.
#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pcap.h> // <-- missing include
#include <netinet/ip.h>
#include <netinet/tcp.h>
void logpacket( unsigned char* payload, struct ip* ipheader, struct tcphdr* tcpheader )
{
//...
}
int main(int argc, char* argv[] )
{
//...
}
How can I get the library files I need to compile this program?
A:
For Ubuntu 12.04, 12.10, 13.10, 14.04 and onward open the terminal and type:
sudo apt-get install libpcap0.8-dev
| {
"pile_set_name": "StackExchange"
} |
Q:
yii afterfind pass array to view
Inside my Model i have this code, this is partial code
protected function afterFind ()
{
$car= Car::model()->findAll("car_id = '{$this->model_id}'");
foreach($car as $cars) {
$val['car_name'][] = $cars->car_name;
$val['car_value'][] = $cars->car_value;
}
$this->car_arr = $val;
parent::afterFind();
}
How do i pass array to view? When i do something like this, there was an error output by YII saying
htmlspecialchars() expects parameter 1 to be string, array given
A:
Yii afterfind() method is overrided to Postprocess AR attributes.
From the docs:
This method is invoked after each record is instantiated by a find
method. The default implementation raises the onAfterFind event. You
may override this method to do postprocessing after each newly found
record is instantiated. Make sure you call the parent implementation
so that the event is raised properly.
So it usually works like:
protected function afterFind()
{
$this->attribute_a = customize($this->attribute_a); //return customized attribute_a
$this->attribute_b = customize($this->attribute_b); //return customized attribute_b
....
parent::afterFind(); //To raise the event
}
I am not sure what are you trying to do? but may be you want to automate some task (populating some array) after each find !!
In that case you can define a public array in your model:
$public car_arr = array();
Then populate it in your afterFind() and it will be accessible in the View.
| {
"pile_set_name": "StackExchange"
} |
Q:
About list sorting and delegates & lambda expressions Func stuff
List<bool> test = new List<bool>();
test.Sort(new Func<bool, bool, int>((b1, b2) => 1));
What Am I missing?
Error 2 Argument 1: cannot convert from 'System.Func' to 'System.Collections.Generic.IComparer'
Error 1 The best overloaded method match for 'System.Collections.Generic.List.Sort(System.Collections.Generic.IComparer)' has some invalid arguments
When I have
private int func(bool b1, bool b2)
{
return 1;
}
private void something()
{
List<bool> test = new List<bool>();
test.Sort(func);
}
it works fine. Are they not the same thing?
A:
Func is the wrong delegate type. You can use either of these:
test.Sort((b1, b2) => 1);
test.Sort(new Comparison<bool>((b1, b2) => 1));
| {
"pile_set_name": "StackExchange"
} |
Q:
Rows To Columns in SQL SERVER USING PIVOT Command (Replacing NULL Values To 0 & Display SUM Of ALL VALUES)
I want to display rows to columns in Sql Server. I have seen the other questions but those columns are hardcoded in the pivot but my columns will be dynamic. What I have achieved till now. As shown in the screenshot I am able to convert the rows into columns but few things I am not able to accomplish.. Need your guyz help
Replacing NULL To 0 in All the Columns
Need to Add 1 more column which will show the sum of all Columns except the companyID
My SQL code:
DECLARE @Columns VARCHAR(MAX)
DECLARE @Convert VARCHAR(MAX)
SELECT @Columns = STUFF((
SELECT '],[' + ErrClassfn
from ArchimedesTables.dbo.PM_ErrClassificationSetup
WHERE CONVERT(VARCHAR(10), ISNULL(EndDate, GETDATE()), 101)
Between CONVERT(VARCHAR(10), GETDATE(), 101)
AND CONVERT(VARCHAR(10), GETDATE(), 101)
ORDER BY '],[' + CONVERT(VARCHAR(MAX), ID) ASC
FOR
XML PATH('')
), 1, 2, '') + ']'
SET @Convert = 'SELECT * INTO #mynewTable FROM
(
SELECT COUNT(WQ.ErrClassfnID) as ErrorCount, UPPER(WQ.CompanyID) as CompanyID,
PME.ErrClassfn as ErrorName
FROM Version25.dbo.WF_Quality AS WQ
LEFT JOIN ArchimedesTables.dbo.PM_ErrClassificationSetup as PME
ON WQ.ErrClassfnID = PME.ID
GROUP BY
UPPER(CompanyID), ErrClassfn
) Quality PIVOT ( SUM(ErrorCount) For ErrorName IN (' + @Columns
+ ')) as PivotTable SeLeCt * FROM #mynewTable'
EXEC(@Convert)
A:
You can alter the columns names, etc for a Dynamic Pivot, similar to this:
DECLARE @ColumnsNull VARCHAR(MAX)
DECLARE @Columns VARCHAR(MAX)
DECLARE @Convert VARCHAR(MAX)
SELECT @ColumnsNull = STUFF((SELECT ', IsNull(' + QUOTENAME(ErrClassfn) +', 0) as ['+ rtrim(ErrClassfn)+']'
from ArchimedesTables.dbo.PM_ErrClassificationSetup
WHERE CONVERT(VARCHAR(10), ISNULL(EndDate, GETDATE()), 101)
Between CONVERT(VARCHAR(10), GETDATE(), 101)
AND CONVERT(VARCHAR(10), GETDATE(), 101)
ORDER BY ID ASC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SELECT @Columns = STUFF((
SELECT '],[' + ErrClassfn
from ArchimedesTables.dbo.PM_ErrClassificationSetup
WHERE CONVERT(VARCHAR(10), ISNULL(EndDate, GETDATE()), 101)
Between CONVERT(VARCHAR(10), GETDATE(), 101)
AND CONVERT(VARCHAR(10), GETDATE(), 101)
ORDER BY '],[' + CONVERT(VARCHAR(MAX), ID) ASC
FOR
XML PATH('')
), 1, 2, '') + ']'
SET @Convert = 'SELECT CompanyID, '+ @ColumnsNull + '
INTO #mynewTable
FROM
(
SELECT COUNT(WQ.ErrClassfnID) as ErrorCount, UPPER(WQ.CompanyID) as CompanyID,
PME.ErrClassfn as ErrorName
FROM Version25.dbo.WF_Quality AS WQ
LEFT JOIN ArchimedesTables.dbo.PM_ErrClassificationSetup as PME
ON WQ.ErrClassfnID = PME.ID
GROUP BY
UPPER(CompanyID), ErrClassfn
) Quality PIVOT ( SUM(ErrorCount) For ErrorName IN (' + @Columns
+ ')) as PivotTable SeLeCt * FROM #mynewTable'
EXEC(@Convert)
I would advise to write the query and get the columns working first, then add the data to a #temp table. It will be easier to debug that way.
You can also create a SUM() field the same way, where you build it dynamically and then add it at in the final SELECT:
So it could be something like this that you could add to the final SELECT:
SELECT @ColumnsTotal = STUFF((SELECT '+' + QUOTENAME(ErrClassfn)
from ArchimedesTables.dbo.PM_ErrClassificationSetup
WHERE CONVERT(VARCHAR(10), ISNULL(EndDate, GETDATE()), 101)
Between CONVERT(VARCHAR(10), GETDATE(), 101)
AND CONVERT(VARCHAR(10), GETDATE(), 101)
ORDER BY ID ASC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
| {
"pile_set_name": "StackExchange"
} |
Q:
how to group dictionaries using itemgetter
I have a list of dictionaries like this:
students = [
{'name': 'alex','class': 'A'},
{'name': 'richard','class': 'A'},
{'name': 'john','class': 'C'},
{'name': 'harry','class': 'B'},
{'name': 'rudolf','class': 'B'},
{'name': 'charlie','class': 'E'},
{'name': 'budi','class': 'C'},
{'name': 'gabriel','class': 'B'},
{'name': 'dessy', 'class': 'B'}
]
I would like to group these dictionaries by class, append them to a list and append each list to a list:
[[{'name': 'alex', 'class': 'A'},
{'name': 'richard', 'class': 'A'}],
[{'name': 'harry', 'class': 'B'},
{'name': 'rudolf', 'class': 'B'},
{'name': 'gabriel', 'class': 'B'},
{'name': 'dessy', 'class': 'B'}],
[{'name': 'john', 'class': 'C'},
{'name': 'budi', 'class': 'C'}],
[{'name': 'charlie', 'class': 'E'}]]
I know how to sort the previous list, using itemgetter:
import itertools
from operator import itemgetter
students = sorted(students, key=itemgetter('class'))
How can I group-append them in a list and create a list of lists? Also, would using sets be better in this case (order would not matter, as long as the dictionaries are grouped by class).
A:
You can do it with defaultdict
from collections import defaultdict
res = defaultdict(list)
for i in students:
res[i['class']].append(i)
print(list(res.values()))
Output
[[{'name': 'alex', 'class': 'A'}, {'name': 'richard', 'class': 'A'}],
[{'name': 'john', 'class': 'C'}, {'name': 'budi', 'class': 'C'}],
[{'name': 'harry', 'class': 'B'},
{'name': 'rudolf', 'class': 'B'},
{'name': 'gabriel', 'class': 'B'},
{'name': 'dessy', 'class': 'B'}],
[{'name': 'charlie', 'class': 'E'}]]
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery and Asynchronous Methods in popup.html
I'm playing around with building chrome extensions. I'm currently testing out the popup.html functionality when you click on the icon in the tool bar.
However I'm having a difficult time trying to wrap my head around using jquery in conjunction with the asynchronous methods of chrome.* apis. Maybe someone can elaborate further for me?
Scenario
popup.html contains buttons that interact with the current tab, The button's href is generated based on the current tab's url + additional text from an array. Using jQuery, I have a $("button").click(); inside of a document is ready. However these two do not seem to play nicely. Everything except for the jQuery stuff works.
example.
var the_current_url = '';
var url_addition = {
"button 1" : "/home",
"button 2" : "/about",
"button 3" : "/content"
}
function getCurrentURL(currentURL) {
if(currentURL) {
var scheme = currentURL.match(/^https?:\/\//i);
var newURL = '';
currentURL = currentURL.substring( scheme[0].length, currentURL.length );
currentURL = currentURL.substring( 0, currentURL.indexOf("/") );
the_current_url = newURL.concat(scheme[0], currentURL);
}
return true;
}
function buildButtons() {
var new_code = "<ul>\n";
// Generate the <li>
for (var key in url_addition) {
new_code = new_code.concat("<li><a href=\"",
the_current_url.concat(url_addition[key]),
"\" title=\"",
url_addition[key],
"\">",
key,
"</a></li>\n");
}
new_code = new_code.concat("</ul>");
return new_code;
}
// Get the Current URL and build the new url
chrome.tabs.query({
'active': true
}, function(tab) {
var currentURL = tab[0].url;
// Pass the Current URL to bb_current_url via Function
getCurrentURL(currentURL);
// add the popup buttons
document.getElementById("button-container").innerHTML = buildButtons();
});
$(document).ready(function() {
// Clicked on buttons
$("a").parents("#button-container").click(function() {
console.log("test" );
});
});
I'm able to get the current tab's url and build the buttons with the proper links, however when it comes to the jquery click action don't work. It seems like the jquery stuff happens before the button-container's buttons are created. So that the $("a")'s click doesn't return any output to the console.log. Anyone know how I'm suppose to correctly use chrome's api with jquery in this instance?
A:
This has nothing to do with jQuery - the same problem would occur with plain JS as well.
Basically, you need to make sure that:
The links are inserted into the DOM only when it is ready (so your button-container is present).
The behaviour is attached to the links after they have been inserted into the DOM.
You can change your code so that the links are inserted inside of $(document).ready(...) (to ensure the button-container is already there) and the event-handlers are registered right after inserting the links (to ensure that the links are present in the DOM).
E.g.:
/* Original comments omitted for brevity */
$(document).ready(function () {
/* The DOM is ready, so `#button-container` is guaranteed to be present */
chrome.tabs.query({ active: true } , function (tabs) {
var currentURL = tabs[0].url;
getCurrentURL(currentURL);
$('#button-container').html(buildButtons());
/* Place this inside the callback to ensure the links are present */
$('a').parents('#button-container').click(function() {
console.log('test');
});
});
});
BTW, your $('a').parents('#button-container') will resolve to #button-container (not to the children as). If I am not mistaken, you want to target all as that are inside #button-container and not #button-container itself.
To achieve this change your expression to:
$('#button-container a').click(function () {...});
| {
"pile_set_name": "StackExchange"
} |
Q:
Create a Scriptable Object Instance through a Constructor
I have a Character Scriptable Object and I have several methods in it. Like GetDate,GetAge (which I am not showing here). I have created a Constructor there, but I don't know how to create an instance of that ScriptableObject through the Constructor. That's what I want to do.
I have tried to just type the values in the inspector but that did not run the methods in the Constructor.
Character.cs
[CreateAssetMenu]
[Serializable]
public class Character : Scriptable Object
{
// Attributes
public string firstName;
public string middleName;
public string lastName;
public string fullName;
public bool isMale;
// Constructor
public Character(string _firstName, string _middleName, string _lastName, bool _isMale)
{
firstName = _firstName;
middleName = _middleName;
lastName = _lastName;
// All The Functions
fullName = string.Format("{0} {1} {2}", firstName, middleName,
lastName);
isMale = _isMale;
// and all the other functions like date calculator.
}
}
I want to create an instance of this Scriptable Object through this Construction. Something like
Character char("x", "y", "z", true);
or when I type the required fields in the Unity Inspector, then it will run all the methods like that full name string.format.
A:
You can't create a new ScriptableObject Instance using a constructor (much like a monobehaviour).
so you need to use Unity API methods
I have added a working sample
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[CreateAssetMenu]
[Serializable]
public class Character : ScriptableObject
{
// Attributes
public string firstName;
public string middleName;
public string lastName;
public string fullName;
public bool isMale;
// Constructor
public Character(string _firstName, string _middleName, string _lastName, bool _isMale)
{
firstName = _firstName;
middleName = _middleName;
lastName = _lastName;
// All The Functions
fullName = string.Format("{0} {1} {2}", firstName, middleName,
lastName);
isMale = _isMale;
// and all the other functions like date calculator.
}
public void Initialize(string _firstName, string _middleName, string _lastName, bool _isMale)
{
firstName = _firstName;
middleName = _middleName;
lastName = _lastName;
// All The Functions
fullName = string.Format("{0} {1} {2}", firstName, middleName,
lastName);
isMale = _isMale;
}
}
and here is the class that creates the Character
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class Tester : MonoBehaviour
{
int characterCounter = 0;
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0))
{
Character c = CreateMyAsset();
c.Initialize("a", "b", "c", true);
}
}
public Character CreateMyAsset()
{
Character asset = ScriptableObject.CreateInstance<Character>();
string assetName = "Assets/c" + characterCounter + ".asset";
characterCounter++;
AssetDatabase.CreateAsset(asset, assetName);
AssetDatabase.SaveAssets();
EditorUtility.FocusProjectWindow();
Selection.activeObject = asset;
return asset;
}
}
A:
No, not like that. It is still unclear why you have to use ScriptableObjects
instead of having a simple class (we came from this question) where you would simply configure those Characters e.g. in the Inspector or use eg.
new Character("abc", "xyz", "kfk", true);
You could however have some kind of factory method like e.g.
[CreateAssetMenu]
[Serializable]
public class Character : Scriptable Object
{
// Attributes
public string firstName;
public string middleName;
public string lastName;
public string fullName;
public bool isMale;
// Constructor
private void Init(string _firstName, string _middleName, string _lastName, bool _isMale)
{
firstName = _firstName;
middleName = _middleName;
lastName = _lastName;
// All The Functions
fullName = string.Format("{0} {1} {2}", firstName, middleName, lastName);
isMale = _isMale;
// and all the other functions like date calculator.
}
public static Character CreateCharacter(string firstName, string middleName, string lastName, bool isMale)
{
var character = ScriptableObject.CreateInstance<Character>();
character.Init(firstName, middleName, lastName, isMale);
}
}
or alternatively do it e.g. in
private void OnEnable()
{
fullName = $"{firstName} {middleName} {lastName}";
}
so it is there when the game starts.
If you really want to have it while typing those names in the Inspector you won't come around using a Custom Inspector by implementing Editor
#if UNITY_EDITOR
using UnityEditor;
#endif
public class Character : Scriptable Object
{
...
}
#if UNITY_EDITOR
[CustomEditor(typeof(Character))]
public class CharacterEditor : Editor
{
private SerializedProperty firstName;
private SerializedProperty middleName;
private SerializedProperty lastName;
private SerializedProperty fullName;
// called once when the Object of this type gains focus and is shown in the Inspector
private void OnEnable()
{
firstName = serializedObject.FindProperty("firstName");
middleName= serializedObject.FindProperty("middleName");
lastName= serializedObject.FindProperty("lastName");
fullName= serializedObject.FindProperty("fullName");
}
// kind of like the Update method of the Inspector
public override void OnInspectorGUI()
{
// draw the default inspector
base.OnInspectorGUI();
serializedObject.Update();
fullName.stringValue = $"{firstName.stringValue} {middleName.stringValue} {lastName.stringValue}";
serializedObject.ApplyModifiedProperties();
}
}
#endif
alternatively to using #if UNITY_EDITOR you can ofcourse have the CharacterEditor in a complete separate script and put that one in a folder named Editor. In both cases the according code is stripped of in a build.
| {
"pile_set_name": "StackExchange"
} |
Q:
Attempting to use an array within an array to store and retrieve data. Having some isses
I have a loop iterating through various users (the counter is simply determining how many users to parse through). In every iteration a user's id and distance are stored in Array $friendObj. Then I want to add the $friendObj array to the $friendsArry. It does this, but each user iteration it replaces the data at the $friendArry[0] spot. Out of the five echo's at the end, only the first one displays anything and that data is the id of the very last user processed. Any suggestions to alter (or completely change my code) would be great (kind of new to php).
//...
//There is a loop above this cycling through different users.
$friendObj = array('id' => $fId, 'distance' => $distanceFromYou);
$friendsArry = array();
array_push($friendsArry, $friendObj);
echo "<br />";
if($counter >= 5)
{
break;
}
} //end of loop
echo "Test1: ". $friendsArry[0]['id']. "<br />";
echo "Test2: ". $friendsArry[1]['id']. "<br />";
echo "Test3: ". $friendsArry[2]['id']. "<br />";
echo "Test4: ". $friendsArry[3]['id']. "<br />";
echo "Test5: ". $friendsArry[4]['id']. "<br />";
A:
Try deleting this line:
$friendsArry = array($friendInc => friendObj);
I don't even understand what are you doing with that one.. o.O
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery - Toggle Input text after checkbox
I have this code which works perfectly, It can toggle an input when checkbox is checked.
https://jsfiddle.net/majmo6r4/
But, if one day I want to add more checkboxes, I have to duplicate my code and that's not what I want. I want to improve my code in order to have the same feature with each checkboxes without create another class and duplicate my if statement and variables on my js file.
I had an idea like this :
(function($){
function $test() {
let $cbs = $(".cbTeam");
$cbs.each(function () {
let $inputs = $('.inputTeam');
if($cbs.siblings().is(':checked')) {
$inputs.css("display", "flex");
} else {
$inputs.css("display", "none");
}
});
}
$(this).click($test);
}(jQuery));
For each checkboxes, I can toggle his input, so I need to consider that the checkboxes has the same class name and for the inputs too.
<div class="form-group">
<label>Jeux - Préférences</label>
<div class="checkbox">
<label><input type="checkbox" class="cbTeam" value="">Hearthstone</label>
<input type="text" class="form-control inputTeam" placeholder="Equipe Hearthstone">
</div>
<div class="checkbox">
<label><input type="checkbox" class="cbTeam" value="">League of Legends</label>
<input type="text" class="form-control inputTeam" placeholder="Equipe LoL">
</div>
<button type="submit" class="btn btn-default">S'inscrire</button>
</div>
Thank you for taking time to my problem, I hope there's enough informations and have a nice day full of code :)
P.S. I want to say "Hello" at the start of the topic but it disappear when i publish the message :(
A:
You can show/hide the input text by using $(this).parent().next()
$(this) - will return to the current checkbox being clicked.
$(this).parent() - will return the parent of the checkbox. Which is <label> based on your html code.
$(this).parent().next() - will return the next element of the parent which is input text.
Basically, you are trying to locate the input text (one step at a time) and do some actions on it.
Since you already locate the right element(text input), you can now do actions like show() or hide(). Example: $(this).parent().next().hide()
The text input is the next element of the checkbox's parent.
$(document).ready(function() {
$(".checkbox input[type=checkbox]").click(function() {
if ($(this).is(":checked")) $(this).parent().next().show();
else $(this).parent().next().hide();
});
//Hide inputs initially
$(".checkbox input[type=text]").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label>Jeux - Préférences</label>
<div class="checkbox">
<label>
<input type="checkbox" class="cbHs" value="">Hearthstone
</label>
<input type="text" class="form-control teamHs" placeholder="Equipe Hearthstone">
</div>
<div class="checkbox">
<label>
<input type="checkbox" class="cbTeam" value="">League of Legends
</label>
<input type="text" class="form-control inputTeam" placeholder="Equipe LoL">
</div>
<button type="submit" class="btn btn-default">S'inscrire</button>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Possible values of current_session_context_class property in hibernate and uses
I wanted to know all possible values that can be used with current_session_context_class property in cfg.xml file? I have an idea of thread value that makes the session context to relate per thread, like propertyname="current_session_context_class" thread.
A:
For Hibernate 4 valid values include:
jta, thread, and managed (which are aliases for implementations delivered with Hibernate).
full class name with package to any other custom class that
implements org.hibernate.context.spi.CurrentSessionContext
This is told in Hibernate manual - 2.3. Contextual sessions
| {
"pile_set_name": "StackExchange"
} |
Q:
Jest did not exit one second after the test run has completed when using supertest and mongoose
I am using jest to test my node.js endpoints with supertest.
However after running my test jest does not exit, instead it returns the following and hangs:
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't
stopped in your tests. Consider running Jest with
--detectOpenHandles to troubleshoot this issue.
import request from "supertest";
import server from "../../src/index";
import mongoose from "mongoose";
describe("Authentication", () => {
beforeAll( async () => {
console.log("Test Starting...");
await mongoose.connection.dropDatabase();
});
afterAll( async () => {
console.log("... Test Ended");
await mongoose.connection.dropDatabase();
await mongoose.connection.close();
});
it("should authenticate with basic auth", async (done) => {
const BASIC_AUTH = Buffer.from(TEST_VARIABLES.HS_USERNAME + ":" + TEST_VARIABLES.HS_PASSWORD).toString("base64");
const auth_response = await request(server).get("/api/v2/auth/admin")
.set("Authorization", "Basic " + BASIC_AUTH)
.expect(200);
done();
});
A:
The app is the node.js server is still listening.
server = app.listen(this.config.port, "0.0.0.0");
adding server.close() to afterAll solved the problem.
afterAll( async () => {
console.log("... Test Ended");
await mongoose.connection.dropDatabase();
await mongoose.connection.close();
app.close()
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Update database based on dropdownlist selection?
I have a table called SisStatus, which contains two columns "StatusID" and "Status", it contains four rows, "Normal", "Withdrawn", "Temporally Withdrawn", and "Suspended".
I have pulled this table and displayed it into a drop down list with the following code:-
ASP.NET
<asp:DropDownList ID="ddlStatus" runat="server">
</asp:DropDownList>
C#
private void FillDropDownList()
{
string connectionString = WebConfigurationManager.ConnectionStrings["scConnection"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string dropDownQuery = "SELECT * FROM SisStatus";
SqlCommand cmd = new SqlCommand(dropDownQuery, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlStatus.DataTextField = ds.Tables[0].Columns["Status"].ToString();
ddlStatus.DataValueField = ds.Tables[0].Columns["Status"].ToString();
ddlStatus.DataSource = ds.Tables[0];
ddlStatus.DataBind();
}
This works fine, and the dropdown is being populated. The issue arises when I'm trying to update a different table SisStudents 'Status' column.
Below is the code I'm using to try and update it, however it does not work. The only way it works is if in the database (through me already putting it in) the status is 'Withdrawn', 'Temporally Withdrawn', 'Suspended', and you change the status to 'Normal' it works...
protected void UpdateBtnClick(object sender, EventArgs e)
{
/**
* When clicked takes the data the user has entered
* and updates their row in the db
*/
string newForename = txtForename.Text;
string newSurname = txtSurname.Text;
string newTermAddress = txtTermAddress.Text;
string newHomeAddress = txtHomeAddress.Text;
string newPhone = txtPhoneNumber.Text;
string newDOB = txtDOB.Text;
string newContactName = txtContactName.Text;
string newContactAddress = txtContactAddress.Text;
string newContactPhone = txtContactPhone.Text;
string newStatus = ddlStatus.SelectedValue;
if (newForename != "" && newSurname != "" && newTermAddress != "" && newHomeAddress != "" && newPhone != "" && newDOB != "" && newContactName != "" && newContactAddress != "" && newContactPhone != "")
{
string student = Request.QueryString["user"];
string connectionString = WebConfigurationManager.ConnectionStrings["scConnection"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string studentDetailsQuery = "UPDATE SisStudents SET TermAddress = @TermAddress, Phone = @Phone, DOB = @DOB, HomeAddress = @HomeAddress, Status = @Status WHERE UserID = @User";
SqlCommand cmdStudentDetails = new SqlCommand(studentDetailsQuery, con);
cmdStudentDetails.Parameters.AddWithValue("@TermAddress", newTermAddress);
cmdStudentDetails.Parameters.AddWithValue("@Phone", newPhone);
cmdStudentDetails.Parameters.AddWithValue("@DOB", newDOB);
cmdStudentDetails.Parameters.AddWithValue("@HomeAddress", newHomeAddress);
cmdStudentDetails.Parameters.AddWithValue("@User", student);
cmdStudentDetails.Parameters.AddWithValue("@Status", newStatus);
cmdStudentDetails.ExecuteNonQuery();
Any help would be appreciated, as the update query is working for everything else.
Edit: There is no error, the 'Status' column is just not updated with the selected value from the DropDownList.
A:
If only status is not getting update, then i guess it might be a problem of postback.
If you are loading the dropdownlist from page load, then make sure you are calling the function inside the !Page.IsPostback like,
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback)
{
FillDropDownList();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
TortoiseSVN Login not working after Windows AD Password Change
We are using VisualSVN as Subversion Server with Windows AD as authentification.
Yesterday I changed my Windows AD password.
I connected to the VisualSVN-Webserver which worked fine with the new password.
But I couldn't log in to the server using TortoiseSVN.
I cleared the cache of Tortoise and even reinstalled it, but the problem stays the same.
So I know for sure, that the new password is correct and VisualSVn-authetification works fine with Windows AD, but still Tortoise isn't working.
A:
In Germany we use ö, ä, ü. Our SVN Version couldn't handle this as it
is very old.
The problem has been solved in VisualSVN Server 3.5.0:
Fixed: unable to authenticate using Windows Basic Authentication when a password contains non-ASCII characters.
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Drive API javascript
I'm trying to use the Google drive to list files.
Using the answer in https://stackoverflow.com/a/11280257 I found a problem that I can't discover the reason.
var clientId = '*********.apps.googleusercontent.com';
var apiKey = '##########';
var scopes = 'https://www.googleapis.com/auth/drive';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
}
else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: [scopes], immediate: false}, handleAuthResult);
return false;
}
function makeApiCall() {
gapi.client.load('drive', 'v2', makeRequest);
}
function makeRequest()
{
var request = gapi.client.drive.files.list({'maxResults': 5 });
request.execute(function(resp) {
for (i=0; i<resp.items.length; i++) {
var titulo = resp.items[i].title;
var fechaUpd = resp.items[i].modifiedDate;
var userUpd = resp.items[i].lastModifyingUserName;
var userEmbed = resp.items[i].embedLink;
var userAltLink = resp.items[i].alternateLink;
var fileInfo = document.createElement('li');
fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd ));
document.getElementById('content').appendChild(fileInfo);
}
});
}
I have this error:
Uncaught TypeError: Cannot read property 'files' of undefined
in the line
var request = gapi.client.drive.files.list({'maxResults': 5 });
A:
Using
var request = gapi.client.request({
'path': '/drive/v2/files',
'method': 'GET',
'params': {'maxResults': '1'}
});
instead of
var request = gapi.client.drive.files.list({'maxResults': 5 });
resolved the problem!
A:
Code looks OK and you're correctly waiting until gapi.client.load completes. Might just be an error with loading the Drive JS files or some other issue (maybe bad JS file cached?). I modified your example a little bit to run on jsfiddle, take a look at http://jsfiddle.net/Rbg44/4/ for the full example:
HTML:
<button id="authorize-button">Authorize</button>
<div id="content">Files:</div>
JS:
var CLIENT_ID = '...';
var API_KEY = '...';
var SCOPES = '...';
function handleClientLoad() {
gapi.client.setApiKey(API_KEY);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
var options = {
client_id: CLIENT_ID,
scope: SCOPES,
immediate: true
};
gapi.auth.authorize(options, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
var options = {
client_id: CLIENT_ID,
scope: SCOPES,
immediate: false
};
gapi.auth.authorize(options, handleAuthResult);
return false;
}
function makeApiCall() {
gapi.client.load('drive', 'v2', makeRequest);
}
function makeRequest() {
var request = gapi.client.drive.files.list({'maxResults': 5 });
request.execute(function(resp) {
for (i=0; i<resp.items.length; i++) {
var titulo = resp.items[i].title;
var fechaUpd = resp.items[i].modifiedDate;
var userUpd = resp.items[i].lastModifyingUserName;
var userEmbed = resp.items[i].embedLink;
var userAltLink = resp.items[i].alternateLink;
var fileInfo = document.createElement('li');
fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo +
' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd ));
document.getElementById('content').appendChild(fileInfo);
}
});
}
$(document).ready(function() {
$('#authorize-button').on('click', handleAuthClick);
$.getScript('//apis.google.com/js/api.js', function() {
gapi.load('auth:client', handleClientLoad);
});
});
Can you check in your browsers dev tools if there is any sort of issue in the request made when you call gapi.client.load()?
A:
You need to write this :
gapi.client.load('drive', 'v2', null);
| {
"pile_set_name": "StackExchange"
} |
Q:
Need my mobile application to connect my website, will this method be better than using an API?
I want my mobile app to connect to my website to get/post data from and to the database, respectively.
I was looking up RESTful APIs (which I don't really understand how the file writing and retrieving gets data from the database), but another method I was thinking was to do the following. Make my app use normal HTTP Requests to specific "API-like" pages. The request can set certain variables to pretty much act like an actual user accessing the page.
For example, to register a user to my site I could POST a request with the postString look something like this:
"registeruser=true&username=NewUser123&password=SecretPass123&email=..."
Would this method be appropriate? Would it be slower than an API? Should I look into using an API instead? Obviously I would place checks to ensure proper client-credentials are in place before it can make any requests.
100% of the requests made by the mobile app will be to get and post data to and from databases.
A:
What you are proposing is very similar to what a RESTful API does.
In a RESTful API, the server also has a number of "API-like pages" (called Resources in REST terms) and normal HTTP requests are used to access and manipulate them.
The main difference between your proposed API (yes, you are also proposing an API) and a RESTful API seems to be how information is transferred in a HTTP POST request. In a RESTful API, the information needed to process a POST request is carried in the body of the request, because you can put a lot more information in there than would fit in the request-string.
An API is an Application Programming Interface, which means that it is an interface that other applications or modules can use to make use of a particular service.
This is in contract to an HMI (Human Machine Interface), which is meant for use by humans.
At any point where two applications or software modules interact with each other, that interaction goes through an API.
| {
"pile_set_name": "StackExchange"
} |
Q:
Logging in from settings username and password preferences
I have an app that uses webView. In the home screen of a website I want to login using username and password entered by the user in the app's settings option. Currently I have this code which I saw in solution to a similar question asked on this forum. But it isn't working (neither it did for the other guy).
-(IBAction)cachepressed:(id)sender{
NSString *baseurl=[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"];
NSString *username= [[NSUserDefaults standardUserDefaults] stringForKey:@"name_preference"];
NSString *password= [[NSUserDefaults standardUserDefaults] stringForKey:@"pswrd_preference"];
NSString* content = [NSString stringWithFormat:@"username=%@&password=%@", username, password];
NSData *data=[content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength=[NSString stringWithFormat:@"%d",[data length]];
NSString *loginpage= [baseurl stringByAppendingString:@"/index.php?title=Special:UserLogin"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:loginpage]];
[request setHTTPMethod:@"POST"];
[request setValue:postlength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:data];
NSError *error=nil;
NSURLResponse *response=nil;
NSData *result=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *HTMLString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
[webView loadHTMLString:HTMLString baseURL:[NSURL URLWithString:loginpage]];
}
I am not too sure about the two lines of code starting with [request setValue...]. Can somebody suggest a solution to this? It would be a great help. Thanks in anticipation.
A:
This depends a lot on how the authentication is done on the website.
Based on what I can figure from your question, the code you posted sends values for the fields named "username" and "password" to the index.php?title=Special:UserLogin page using POST.
You need to make sure that everything is set accordingly.
1. Are your fields name the same on the website?
Maybe the login form uses different field names, not username and password. Check the source code and see if the input names are indeed "username" and "password"
2. Does your host allow posting data from a different source?
I used to set mine so no POST request would work if they didn't originate from my server, so POSTing data from an iPad would not have functioned.
Is this the case for you too?
3. The login process is really done by posting data to that page?
Maybe on the website the authentication is done using AJAX on a different php page and then you get redirected to index.php?title=Special:UserLogin, I've seen such cases in the past.
Bottom line is that you need to know exactly how the login is done on the website before doing it inside a webview. Correct me if I'm wrong, but based on your post it doesn't seem to be the case here
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I create a network from connected links
I have a bundle of links in 'some' networks. I need to find out which ones are connected to each other i.e. I need to find out which links are not connected to the 'main' network.
I have been working on a flood fill recursive method, which effectively goes from link to link, finding out which ones are connected, and recursively doing the same. But the numbers are quite high, and my machine just bailed, so I wondered if there were other, better, or more efficient, ways of doing this.
Using arcpy
Thanks in advance
A:
I used FME 2013 NetworkTopologyCalculator. Phenominal, took 4 seconds...
| {
"pile_set_name": "StackExchange"
} |
Q:
JPanel does not fill containing JFrame
Hi so I'm writing an simple physics engine to understand object collisions and Java graphics a bit better, and so far I have successfully written the code to add the JPanel to the JFrame and allow them to show up somewhat the correct size, but when I view the actually program, the JPanel seems tobe the right size but it does not start in the upper corner of the window, but rather the upper left of the frame. I seem to have this problem alot where I want something to be at (0, 0) and starts in the upper corner of the frame rather than the panel. Here is my code:
I have an engine class that extends JFrame and contains the main method -->
package io.shparki.PhysicsEngine;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Engine extends JFrame{
public Engine(){
super("Physics Engine and Simulator");
setLayout(new BorderLayout());
add(new EnginePanel(), BorderLayout.CENTER);
pack();
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new Engine();
}
}
and this is my second class, the EnginePanel which extends JPanel and implements Runnable -->
package io.shparki.PhysicsEngine;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.JPanel;
public class EnginePanel extends JPanel implements Runnable{
private static final int WIDTH = 300;
private static final int HEIGHT = WIDTH / 16 * 9;
private static final int SCALE = 4;
public int getWidth() { return WIDTH * SCALE; }
public int getHeight() { return HEIGHT * SCALE; }
@Override
public Dimension getPreferredSize(){ return new Dimension(WIDTH * SCALE, HEIGHT * SCALE); }
private static final int FPS = 85;
private static final int PERIOD = 1000 / FPS;
private int currentFPS = 0;
private Thread animator;
private boolean running = false;
private Graphics dbg;
private Image dbImage = null;
public EnginePanel(){
setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setVisible(true);
}
public void addNotify(){
super.addNotify();
startEngine();
}
public void startEngine(){
running = true;
animator = new Thread(this, "Animator");
animator.start();
}
public void stopEngine(){
running = false;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if (dbImage != null){
g.drawImage(dbImage, 0, 0, null);
}
}
public void paintScreen(){
Graphics g;
try{
g = this.getGraphics();
if ( g != null && dbImage != null){
g.drawImage(dbImage, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
} catch(Exception ex) { System.out.println("Graphics Context Error : " + ex); }
}
public void run(){
running = true;
init();
Long beforeTime, timeDiff, sleepTime;
while(running){
beforeTime = System.currentTimeMillis();
updateEngine();
renderEngine();
paintScreen();
timeDiff = System.currentTimeMillis() - beforeTime;
sleepTime = PERIOD - timeDiff;
if (sleepTime <= 0){
sleepTime = 5L;
}
currentFPS = (int) (1000 / (sleepTime + timeDiff));
try{
Thread.sleep(sleepTime);
} catch (InterruptedException ex) { ex.printStackTrace(); }
}
}
private TextField FPSTextField;
public void init(){
FPSTextField = new TextField("Currnet FPS: " + currentFPS, 25, 25);
}
public void updateEngine(){
FPSTextField.setText("Currnet FPS: " + currentFPS);
}
public void renderEngine(){
if (dbImage == null){
dbImage = createImage((int)getWidth(), (int)getHeight());
if (dbImage == null){
System.out.println("Graphical Context Error : DBImage is Null");
return;
} else {
dbg = dbImage.getGraphics();
}
}
Graphics2D g2d = (Graphics2D) dbg;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
FPSTextField.render(g2d, Color.MAGENTA);
}
}
I'm not quite sure why this keeps happening and I have searched for help but can not find the answer. Thanks in advance for all who help :)
EDIT: Added code for the TextField object:
package io.shparki.PhysicsEngine;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
public class TextField{
private Point location;
public Point getLocation(){ return location; }
public double getX() { return location.getX(); }
public double getY() { return location.getY(); }
private String text;
public void setText(String text) { this.text = text; }
public String getText() { return this.text; }
public TextField(String text, int x, int y){
this.location = new Point(x, y);
this.text = text;
}
public TextField(String text, Point location){
this.location = location;
this.text = text;
}
public void render(Graphics g){
g.drawString(text, (int)location.getX(), (int)location.getY());
}
public void render(Graphics2D g2d){
g2d.drawString(text, (int)location.getX(), (int)location.getY());
}
public void render(Graphics g, Color color){
g.setColor(color);
g.drawString(text, (int)location.getX(), (int)location.getY());
}
public void render(Graphics2D g2d, Color color){
g2d.setColor(color);
g2d.drawString(text, (int)location.getX(), (int)location.getY());
}
public void render(Graphics g, Color color, Font font){
g.setColor(color);
g.setFont(font);
g.drawString(text, (int)location.getX(), (int)location.getY());
}
public void render(Graphics2D g2d, Color color, Font font){
g2d.setColor(color);
g2d.setFont(font);
g2d.drawString(text, (int)location.getX(), (int)location.getY());
}
}
A:
The preferred size of the JPanel EnginePanel restricts the panel from being resized the JFrame is rendered non-resizable. Invoke JFrame#pack after calling setResizable(false). Also move setLocationRelativeTo after pack so that the frame appears centered.
pack();
setLocationRelativeTo(null);
setVisible(true);
| {
"pile_set_name": "StackExchange"
} |
Q:
1000Base-T Server NIC speed slows down to 100Base-T when sending data to a 100Base-T device
I am conducting experiments to explore how data transmission is being influenced by the network speeds of the receivers. Here is my setup,
I have an Ubuntu server A connected to a Gigabit switch with 2 other clients (B and C). All machines have been installed with a gigabit NIC card
While Clients A B are operating at 1000mbps, client C is configured to run at 100Mbps by ethtool using the following command
ethtool -s eth0 speed 100 duplex full
With this setup, i have attempted to send a 500MB file from A to clients B and C at the same time via SCP.
I have expected the data transmission rate between A and C to be 100mbps, and A and B to be 1000mbps.
However in reality, the transmission rate of A to both B and C has been dropped to 100mbps.
My question is: is this behavior to be expected? If so, is there a way to send data from A to B and C concurrently at different network speeds?
A:
I believe that this is one of the boundary conditions that some network hardware manufacturers may or may not choose to implement wisely. a lot of it depends on the switch mode, per-port-buffer size, and backplane speed, as well as host metrics like the nic, systembus, and CPU speed.
SCP requires encryption/decryption so the host system bus, Nic bus, and CPU capacity are all factors. if the recieving pc can't keep up with the flow, it sends source-quench flow control messages to the switch, which slows down output to that port, which may cause the switch buffers to fill up, and may result in the switch relaying source-quench messages to the sending system, instructing it to slow down. source quench occurs at layer 2, so there is little or no differentiation between the two flows; it has to slow down both of them. the port-buffer for the sending host is likely full as well, meaning that data can only be sent into it at the rate it can be sent on to the slower destination.
in the end, it all depends on the grade of your equipment. if you are connecting rack servers over fiberchannel to a enterprise grade switch, and then into a smaller distribution switch, then I would not expect this problem. if you are using 3 old pc's connected by ratty cat5e to a couple $100 netgear switches, then I would completely expect it.
| {
"pile_set_name": "StackExchange"
} |
Q:
R Shiny/Shinydashboard: Hiding the last part of a string in a table
I have a data table that contains some very wide columns and I want to add a scrolling-bar to make it more presentable. So far I have found examples using a scrolling-bar for the entire table - but ideally I would like to have a scrolling-bar for EACH column in the table if that is possible. Below there is an illustrating example. In this code I want a scrolling-bar for both "This_is_a_very_long_name_1", "This_is_a_very_long_name_2" etc.
library("shinydashboard")
library("shiny")
body <- dashboardBody(
fluidPage(
column(width = 4,
box(
title = "Box title", width = NULL, status = "primary",
div(style = 'overflow-x: scroll', tableOutput('table'))
)
)
)
)
ui <- dashboardPage(
dashboardHeader(title = "Column layout"),
dashboardSidebar(),
body
)
server <- function(input, output) {
test.table <- data.frame(lapply(1:8, function(x) {1:10}))
names(test.table) <- paste0('This_is_a_very_long_name_', 1:8)
output$table <- renderTable({
test.table
})
}
# Preview the UI in the console
shinyApp(ui = ui, server = server)
I thought about splitting the table into 8 tables, making a scrolling table for each of them and then putting them next to each other, but space was added betweeen them and it did not look that nice. I think it would be preferable to keeping it as one table (but suggestions are very welcome!).
Does anyone whether this is possible - and how to solve it?
Thanks in advance!
A:
I would not recommend scrolling column header, i think it would not be very clear to read it or so. Here is the code which You can use to get the header in 2 lines so the columns are not too wide:
library("shinydashboard")
library("shiny")
library(DT)
test.table <- data.frame(lapply(1:8, function(x) {1:10}))
names(test.table) <- paste0('This_is_a_very_long_name_', 1:8)
body <- dashboardBody(
fluidPage(
column(width = 8,
box(
title = "Box title", width = NULL, status = "primary",
div(style = 'overflow-x: scroll', dataTableOutput('table'))
)
)
)
)
ui <- dashboardPage(
dashboardHeader(title = "Column layout"),
dashboardSidebar(),
body
)
server <- function(input, output) {
output$table <- renderDataTable({
names(test.table) <- gsub("_"," ",names(test.table))
datatable(test.table, options = list(columnDefs = list(list(width = '100px', targets = c(1:8)))))
})
}
# Preview the UI in the console
shinyApp(ui = ui, server = server)
[UPDATE] --> Column text rendering
Here is a one solution which can be usefull for You. There is no scrolling, however Your row text displays only first three characters (the number of characters displayed can be changed) and ..., with mouse over the row You get the pop up with whole variable name in this row:
library("shinydashboard")
library("shiny")
library(DT)
x <- c("aaaaaaaaaaaaaa", "bbbbbbbbbbbb", "ccccccccccc")
y <- c("aaaaaaaaaaaaaa", "bbbbbbbbbbbb", "ccccccccccc")
z <- c(1:3)
data <- data.frame(x,y,z)
body <- dashboardBody(
fluidPage(
column(width = 4,
box(
title = "Box title", width = NULL, status = "primary",
div(style = 'overflow-x: scroll', dataTableOutput('table'))
)
)
)
)
ui <- dashboardPage(
dashboardHeader(title = "Column layout"),
dashboardSidebar(),
body
)
server <- function(input, output) {
output$table <- renderDataTable({
datatable(data, options = list(columnDefs = list(list(
targets = c(1:3),
render = JS(
"function(data, type, row, meta) {",
"return type === 'display' && data.length > 3 ?",
"'<span title=\"' + data + '\">' + data.substr(0, 3) + '...</span>' : data;",
"}")),list(width = '100px', targets = c(1:3)))))
})
}
# Preview the UI in the console
shinyApp(ui = ui, server = server)
| {
"pile_set_name": "StackExchange"
} |
Q:
Submit form when Enter is pressed
I have an aspx page with many buttons and i have a search button whose event i want to be triggered when user press enter.
How can i do this?
A:
You set the forms default button:
<form id="Form1"
defaultbutton="SubmitButton"
runat="server">
A:
Make it the default button of the form or panel.
Either one has a DefaultButton property that you can set to the wanted button.
| {
"pile_set_name": "StackExchange"
} |
Q:
User Monitoring in Rails
We have an app with an extensive admin section. We got a little trigger happy with features (as you do) and are looking for some quick and easy way to monitor "who uses what".
Ideally a simple gem that will allow us to track controller/actions on a per user basis to build up a picture of the features that are used and those that are not.
Anything out there that you'd recommend..
Thanks
Dom
A:
I don't know that there's a popular gem or plugin for this; in the past, I've implemented this sort of auditing as a before_filter in ApplicationController:
from memory:
class ApplicationController < ActionController::Base
before_filter :audit_events
# ...
protected
def audit_events
local_params = params.clone
controller = local_params.delete(:controller)
action = local_params.delete(:action)
Audit.create(
:user => current_user,
:controller => controller,
:action => action,
:params => local_params
)
end
end
This assumes that you're using something like restful_authentication to get current user, of course.
EDIT: Depending on how your associations are set up, you'd do even better to replace the Audit.create bit with this:
current_user.audits.create({
:controller => controller,
:action => action,
:params => local_params
})
Scoping creations via ActiveRecord assoiations == best practice
| {
"pile_set_name": "StackExchange"
} |
Q:
Okay, the sandbox didn't work. We still have a quality problem; let's figure out how to address it
As of today, the riddle sandbox is no longer mandatory. The close reason related to it has been deactivated, and the requirement has been removed from the sandbox text. It was an experiment to see if it would be sustainable and effective going forward; for a variety of reasons many of you have pointed out, it didn't work. (We also screwed up at judging the amount of support an idea needs before it has consensus, and offering enough time for a thorough discussion of the merits of ideas.)
But that's fine; everything is reversible, and it gives us all a better sense of the capabilities of the system going forward.
The sandbox itself is probably still worth keeping around, though without the mandatory requirement, because as a tool it could still prove to be valuable to anyone who decides to use it. Even if it's never touched again, it does no harm just sitting there. Unless someone thinks of a good reason it shouldn't be there at all, this is probably what's going to happen.
However, this still leaves us with a quality problem. The idea of a sandbox requirement came about in response to a growing sense that riddle quality is dropping on the site, and that it's becoming more heavily populated with low quality content. (Number sequence and cipher puzzles were even tacked onto the proposal's discussion for similar problems.)
Most of what I said regarding quality in the riddle sandbox proposal I still stand by:
Riddle quality is dropping. I think most of us have seen it lately: there’s been a slow slide in effort and energy put into riddles, and it’s starting to seriously hurt the site. On Stack Exchange, our goal is to optimize for pearls, not sand, and right now, we’re very much not doing this. If we were, it would not only push the quality of the site up, but also drive us to advance the state of the art.
Nowhere else that I know of on the internet do people collaboratively come together to develop new puzzles - including riddles - and that’s not something we want to stop. However, we need to do something to sort out what makes a riddle high quality for this site, and set better quality standards.
So it’s time for us to set aside some energy and effort to sort this out, and start over with a better structure in place to support riddles.
This is the discussion that I want to see continue. I think most of us recognize that there is a problem, and Hugh Meyers even offered insight into why the proposal might have gotten the sort of initial support that it did, even the idea wasn't ultimately very good:
The massive support the proposal had in its first day shows the widespread recognition of the situation and a strong desire for some sort of a solution.
I don't want to belabor the point, rehashing stuff you've probably already read and read again. Instead, it's time for you all to drive the quality discussion on meta.
What we've been doing, bringing these proposals to meta, is partially intended to try and drive discussion. This is where these problems are solved, and there's definitely a solution out there; we just need to find it. (And yes, perhaps more carefully consider its implementation and subsequent effects before diving in head-first.)
So please, please propose and discuss ideas on meta. Don't let this issue stagnate; mods are three of hundreds of community members, and we're all going to get the site that we fight for together.
A:
Totally agree with both of Rand's answers, however, I think we need to hone in a little on what the new close reason should be, so I thought I'd add my thoughts...
New close reason
See Rand's answer for reasoning/precedent, however, I believe the text should be a little different. The primary aim should be to catch/close low quality content, which can be redirected to a sandbox where it can potentially be improved, so I propose the following close reason:
Low Quality1 - In it's current form, this puzzle does not meet Puzzling's [community quality standards]2 and needs refinement. Please take the time to read the guidelines and improve your puzzle. If you would like assistance, you can post your puzzle to the [Puzzling Sandbox]3 to get guidance from the community.
1 - Could possibly be renamed to Needs Refinement or something equivalent, to make it slightly less inflammatory/accusatory - we don't want to scare off innocent newbies.
2 - Would link to the meta post described in point 3, below.
3 - Would link to the either a new general purpose sandbox for all puzzle types, or could possibly be reworded to say "...post your puzzle to the [Riddle Sandbox], [Cipher Sandbox] or [General Puzzle Sandbox]...", if we wanted things split up into chunks.
Community Quality Guides
To keep the close criteria as objective and consistent as possible, we could create an faq tagged meta post, with individual answers per "major" tag (i.e. the big ones, that are currently problematic/controversial like riddle, mathematics, cipher, etc), plus a "general puzzle" catch-all, to help define exactly what constitutes the quality standard minimum, in as clear and unambiguous terms as possible.
We would obviously need individual discussion posts to gather consensus on criteria for each puzzle type above, but there's already some great content here on meta that we could draw from (eg. for ciphers, mathematics, etc). To give you an idea though, I imagine each "answer" would look something like the example below.
Indicative example of a Community Quality Guide, take with a grain of salt... the important stuff of this post is above.
Riddle Quality Criteria
To meet minimum quality standards for Puzzling, a riddle must:
Have a single "obviously correct" answer
Be more than just a straight description of the solution's features
Describe a common everyday object/concept (or be tagged with an appropriate secondary tag, such as trivia, movies, literature, etc to identify that specific domain knowledge is required)
Additionally, your riddle must meet at least three of the following criteria:
Use well structured meter and rhyme
Be concise and well written
Use a creative/unique structure or presentation
Employ letter/wordplay
Make use of metaphor/polysemy/turns of phrase
A:
This may not make a huge difference, but since new users are often high on the blame list for the poor-quality stuff, we should
change the Puzzling Tour to actually reflect this site.
I think this is probably a low-effort but some-reward step we could take, so why not do it. If you don't think it needs to be changed, go take the Puzzling Tour right now and try not to furrow your brow.
At least some of the recent poor quality questions (example, example, example) come from users who do have the Informed badge. That means at least there's one potential point of intervention to communicate something to new users. Right now, nothing Puzzling-specific is on that Tour, and in fact you could argue some of the stuff is Puzzling-detrimental.
And I think Emrakul indicated (as a comment on this post) that we do have some control over this. So...why not?
A:
A chatroom for detecting and discussing low-quality puzzles.
Whether or not we implement a new custom close reason for 'bad' puzzles as proposed in my other answer here, we need people to be aware of it and of any new puzzles coming in that should be closed using it, otherwise there's no point. Emrakul mentioned in comments on another meta post that part of the reason why moderators have been closing too many questions unilaterally is because the community haven't been active enough in closing questions which should be closed.
I propose creating a dedicated chatroom for crap-catching. It would have a feed to post new questions into the room, and in it people would discuss the possible closure of particular questions. This would:
be easier to keep a constant eye on than the Close Votes review queue, since people could hang out and chat idly in between discussing questions to be closed
encourage active community discussion rather than just hitting the "Close" or "Leave Open" button, which would be helpful in shaping policies for the future
draw people's attention to questions in need of closing quicker than the review queue does, since no initial VTC would be needed - all new questions would appear on the room feed.
For the first while, when not many people frequent the chatroom, we might find that more or less the same bunch of users are closing many of the questions, but as we attract more and more participants to the room and the project, that should change. Note that users with <3k rep would also be welcome to join in: even though they can't actually vote to close questions, they can still flag them for closure and take part in the discussions around them.
Of course we'd have to publicise this room as much as possible to make people aware of its existence. Ways to do this might include a featured meta post linking to it and superpings from any chat mods involved to bring active community members into the room.
| {
"pile_set_name": "StackExchange"
} |
Q:
Detect route change in an Angular service
I'm trying to create a service to check if a certain route needs a user to be logged in to access the page. I have a working code but I want to place the $scope.$on('routeChangeStart) function inside the service. I want to place it in a service because I want to use it in multiple controllers. How do I go about this?
Current code:
profileInfoCtrl.js
angular.module('lmsApp', ['ngRoute'])
.controller('profileInfoCtrl', ['$scope', '$location', ' 'pageAuth', function($scope, $location, pageAuth){
//I want to include this in canAccess function
$scope.$on('$routeChangeStart', function(event, next) {
pageAuth.canAccess(event, next);
});
}]);
pageAuth.js
angular.module('lmsApp')
.service('pageAuth', ['$location', function ($location) {
this.canAccess = function(event, next) {
var user = firebase.auth().currentUser;
//requireAuth is a custom route property
if (next.$$route.requireAuth && user == null ) {
event.preventDefault(); //prevents route change
alert("You must be logged in to access page!");
}
else {
console.log("allowed");
}
}
}]);
routes.js
angular.module('lmsApp')
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$routeProvider
.when('/admin', {
templateUrl: 'view/admin.html',
css: 'style/admin.css',
controller: 'adminCtrl',
requireAuth: true //custom property to prevent unauthenticated users
})
.otherwise({
redirectTo: '/'
});
}]);
A:
By using $routeChangeStart, you are listening to a broadcast sent by $routeProvider on every change of the route. I don't think you need to call it in multiple places ( controllers ), just to check this.
In your service:
angular.module('lmsApp')
.service('pageAuth', ['$location', function ($location) {
var canAccess = function(event,next,current){
var user = firebase.auth().currentUser;
//requireAuth is a custom route property
if (next.$$route.requireAuth && user == null ) {
event.preventDefault(); //prevents route change
alert("You must be logged in to access page!");
}
else {
console.log("allowed");
}
}
$rootScope.$on('$routeChangeStart',canAccess);
}]);
And then inject your service in the .run() part of your application. This will ensure the check will be done automatically ( by the broadcast as mentioned earlier ).
In you config part :
angular.module('lmsApp')
.run(function runApp(pageAuth){
//rest of your stuff
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Is $ x^n-y^n$ is a product of coprime factors?
In the expression: $x^n-y^n$, if $n>2$ and $x,y$ are relatively prime, are the factors $x-y$ and $ x^{n-1}+x^{n-2}y+.....$ always coprime? Why? Please exclude the cases where $x-y=\pm 1$ and $\pm 2$. I know it is for $x=2$. Please any input will be greatly appreciated. Thanks.
A:
If $x\equiv y\pmod k$ and $k\mid n$, then they're not coprime.
Proof:
$x\equiv y\pmod k$, so $k\mid x-y$.
Since $x\equiv y\pmod k$, we have $x^{n-1}+x^{n-2}y+\cdots+xy^{n-2}+y^{n-1}\equiv nx^{n-1}\equiv 0\pmod k$, since $k\mid n$. $\:\square$
| {
"pile_set_name": "StackExchange"
} |
Q:
How important are Design Patterns really?
How important are Design Patterns really?
I think the earlier generation of programmers didn't use Design Patterns that much (people who graduated in the 80s and before mid 90s). Do the recent graduate know it in general and use it a lot more?
A:
We used design patterns in the 80's, we just didn't know they were design patterns.
A:
The single biggest benefit of design patterns in my opinion is that it gives developers a common vocabulary to talk about software solutions.
If I say, "We should implement this using the singleton pattern", we have a common point of reference to begin discussing whether or not that is a good idea without me having to actually implement the solution first so you know what I mean.
Add in readability and maintainability that comes with familiar solutions to common problems, instead of every developer trying to solve the problem in their own way over an over again.
Pretty important. Software can be made without them, but it's certainly a lot harder.
A:
They are not absolutely needed, but the good definitely outweighs the bad.
The good:
Code readability: They do help you write more understandable code with better names for what you are trying to accomplish.
Code maintainability: Allows your code to be maintained easier because it is more understandable.
Communication: They help you communicate design goals amongst programmers.
Intention: They show the intent of your code instantly to someone learning the code.
Code re-use: They help you identify common solutions to common problems.
Less code: They allow you to write less code because more of your code can derive common functionality from common base classes.
Tested and sound solutions: Most of the design patterns are tested, proven and sound.
The bad:
Extra levels of indirection: They provide an extra level of indirection and hence make the code a little more complex.
Knowing when to use them: They are often abused and used in cases that they should not be. A simple task may not need the extra work of being solved using a design pattern.
Different interpretations: People sometimes have slightly different interpretations of design patterns. Example MVC as seen by django vs. MVC as seen by Ruby on Rails.
Singleton: Need I say more?
| {
"pile_set_name": "StackExchange"
} |
Q:
Elasticsearch 5 create in memory node for testing
I'm migrating to Elasticsearch 5 from 2 and we have integration tests which run on build servers which do not have ES nodes available. We have used the NodeBuilder from the previous version of ES to create in memory nodes on demand, but I can't find how to do the same thing with version 5.
A:
First time posting in stack overflow, sorry if any mistake in how ask my question.
I had exactly the same problem where I start a client in memory, but I could not connect using the transport client having NoNodeAvailableException as error message.
Settings settings = Settings.builder()
.put("path.home", "target/elasticsearch")
.put("transport.type", "local")
.put("http.enabled", false)
.build();
node = new Node(settings).start();
Now in my test I inject node().client() to the repository and it worked.
For whole code, spring boot and ES 5 without spring-data which does not support ES 5:
https://github.com/jomilanez/elastic5
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculating percent change between groups using Dplyr - Stock Data
Simply trying to calculate the percent change across a given time period for each stock. My current code using dplyr is as follows:
stocks_df %>%
filter(Date > now() - days(2)) %>%
group_by(Stock) %>%
mutate(period_return = (Close - first(Close))/ first(Close) * 100) %>%
do(tail(., n=1))
Date Stock Close
2020-02-05 AAPL 308.86
2020-02-04 AAPL 318.85
2020-02-03 AAPL 321.45
2020-02-05 BA 329.55
2020-02-04 BA 317.94
2020-02-03 BA 316
2020-02-05 MSFT 179.9
2020-02-04 MSFT 180.12
2020-02-03 MSFT 174.38
Desired output would be:
AAPL -3.92%
BA 4.29%
MSFT 3.17%
A:
I guess what you are looking for is :
library(dplyr)
df %>%
group_by(Stock) %>%
summarise(period_return = -(last(Close) - first(Close))/ last(Close) * 100)
# Stock period_return
# <fct> <dbl>
#1 AAPL -3.92
#2 BA 4.29
#3 MSFT 3.17
which can be done in base R using aggregate
aggregate(Close~Stock, df, function(x) -(x[length(x)] - x[1])/x[length(x)] * 100)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to call ".done" after the ajax call in Backbone fetch calls
Instead of throwing an error, the RESTful API that I call returns 200 success with a "fault" object as part of the return data when there's an error server side. I can't change the API. To handle this (without Backbone) all ajax calls are wrapped in a class that calls ".done" after the ajax call to handle display of any "fault" that may be included in the response. Also, some callers need to be able to specify settings that indicate where the fault should be displayed, while others rely on the default location.
I want to change the code to use Backbone's sync functionality to save and retrieve my models and collections, but I'm not sure how to inject the desired settings values and .done function. I could override the prototype sync method and change it to call our custom ajax method, but it's a pretty involved function and I'm rather afraid I'd break something. I would much rather find some lighter way to call ".done" on the result of the ajax call, but I'm having difficulty figuring out how.
I see how to inject an additional error handler or success handler by overriding Backbone.Model.prototype.fetch and Backbone.Collection.prototype.fetch, per this post - How to add a default error handler to all Backbone models?. However, that doesn't give me direct access to the actual ajax call return so I don't have anything to call ".done" on, plus "fetch" only covers "get" ajax calls and I need to handle faults for all Backbone ajax calls.
Anyone have an idea how to handle this?
Thanks much!
A:
I decided to override Backbone.ajax.
I found that any properties I set when calling fetch (I assume this will also work for save and destroy, but haven't tested that yet) are passed through by the framework to this method, so they are available to me there as needed. I'm not thrilled about how I'm making assumptions about Backbone's implementation there (i.e. assume the arguments will be passed to Backbone.ajax in a particular format), but this still seemed like the cleanest way.
Here's some of my code, so you can see how I'm reading the errorHandlingSettings argument. Note that the arguments are NOT passed into Backbone.ajax directly - they are stored by Backbone and then referenced there:
Backbone.ajax = function() {
var currentArguments = {};
if(typeof(arguments.callee) != 'undefined'
&& typeof(arguments.callee.arguments) != 'undefined')
currentArguments = arguments.callee.arguments[0];
var errorHandlingSettings = {};
if(typeof(currentArguments.errorHandlingSettings) != 'undefined')
errorHandlingSettings = currentArguments.errorHandlingSettings;
... etc. - store the "successIfNoFaults" variable.
var handleFaults = function(data){
... etc. (custom code using the errorHandlingSettings and successIfNoFaults variables) ...
};
return Backbone.$.ajax.apply(Backbone.$, arguments).done(handleFaults);
};
And here's how I'm passing the errorHandlingSettings argument (inside my view's initialize method):
this.reservationHold.fetch({errorHandlingSettings: {errorPlace:"1",errorPosition:"errorDiv"}, successIfNoFaults:function(){that.render();}});
Note that I also am passing another custom argument, "successIfNoFaults", so that I can avoid calling the "success" callback if a 200 response WITH a fault comes back.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to translate "tutorial"?
I'd like to help translate the Django Girls tutorial to Esperanto. That tutorial is a written step-by-step instruction guiding readers/learners through almost everything needed to build a functional blogging software. Besides the instructions themselves, the tutorial contains some explanations / background information about what is being done or being tried to achieve.
It's designed to be used at workshop-style courses with "coaches" present that help participants follow the guide, but should also be useful for readers learning self-guided on their own.
What Esperanto word should be chosen to translate "tutorial" in the name/title of the tutorial and elsewhere?
Mi volas helpi traduki la "Django Girls tutorial" al Esperanto. Ĉi tiu "tutorial" estas skriba paŝon-post-paŝo-instrukcio, kiu gvidas legantojn/lernantojn tra preskaŭ tuto necesa por konstrui funkcian blogan programaron. Krom la instrukcioj, la "tutorial" enhavas kelkajn klarigojn / foninformon pri kio estas farata por atingi ĝin.
Ĝi estas destinita al metiejo-stilaj kursoj kun "trejnistoj" tie, kiuj helpas partoprenantojn sekvi la gvidilon, sed ĝi devus esti utila ankaŭ al legantoj memlernantaj.
Kiu Esperanta vorto devus esti elektata por traduki "tutorial" en la nomo/titolo de la "tutorial" kaj aliloke?
A:
Ĝenerala esprimo estas „lernilo“ respektive „memlernilo“, sed tiu esprimo havas pli vastan signifon ol filmo, do „lernfilmo“ aŭ „memlernfilmo“, se temas pri simpla filmo, se temas pri interaktiva aplikaĵo, tiam fakte „lernilo“ respektive „memlernilo“ eventuale „interaktiva memlernilo“, se oni volas emfazi. El la vidpunkto de la instruisto, memkompreneble "instruilo" respektive "instrufilmo" ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Open multiple website in a single window in different tabs
I want to open no. of urls and I want to open 1st url in new window and after that others in same window but in new tabs.
I am using c# and its a window application
I use a code provided by Firefox but it is not opening new tab. It opens new window.
here is my code:
private void btnSearch_Click(object sender, EventArgs e)
{
Process.Start("http://google.co.in","2048");
Process.Start("http://google.co.in","2048");
}
thanks in advance.
A:
The problem starts when you don't have you're browser open.
Else it would work perfect without the Thread.Sleep.
Maybe you can try it like this
The "_blank" Opens a new blank page in the same window "So a new tab"
using System.Threading;
private void button1_Click(object sender, EventArgs e)
{
Process.Start("http://www.google.com", "_blank");
Thread.Sleep(2000);
Process.Start("http://www.google.com", "_blank");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
opencv installation on ubuntu 11.10
I'm trying to install OpenCV on Ubuntu11.10 using the terminal. But it gives me the following error. I've not been able to resolve it. Notice the last four lines.
$sudo apt-get install opencv
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
libopencv2.3
The following NEW packages will be installed:
libopencv2.3 opencv
0 upgraded, 2 newly installed, 0 to remove and 2 not upgraded.
Need to get 11.8 MB of archives.
After this operation, 88.7 MB of additional disk space will be used.
Do you want to continue [Y/n]? Y
Get:1 http://ppa.launchpad.net/gijzelaar/opencv2.3/ubuntu/ oneiric/main libopencv2.3 i386 2.3.1-3 [11.5 MB]
Get:2 http://ppa.launchpad.net/gijzelaar/opencv2.3/ubuntu/ oneiric/main opencv i386 2.3.1-3 [264 kB]
Fetched 11.8 MB in 22s (528 kB/s)
(Reading database ... 240623 files and directories currently installed.)
Unpacking libopencv2.3 (from .../libopencv2.3_2.3.1-3_i386.deb) ...
dpkg: error processing /var/cache/apt/archives/libopencv2.3_2.3.1-3_i386.deb (--unpack):
trying to overwrite '/usr/lib/libopencv_highgui.so.2.3.1', which is also in package libopencv-highgui2.3 2.3.1-4ppa1
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Unpacking opencv (from .../opencv_2.3.1-3_i386.deb) ...
dpkg: error processing /var/cache/apt/archives/opencv_2.3.1-3_i386.deb (--unpack):
trying to overwrite '/usr/bin/opencv_createsamples', which is also in package libopencv-core-dev 2.3.1-4ppa1
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Errors were encountered while processing:
/var/cache/apt/archives/libopencv2.3_2.3.1-3_i386.deb
/var/cache/apt/archives/opencv_2.3.1-3_i386.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)
$
A:
For an error like this:
dpkg: error processing /var/cache/apt/archives/AAA (--unpack):
trying to overwrite `/usr/lib/BBB', which is also in package CCC
dpkg-deb: subprocess paste killed by signal (Broken pipe)
Errors were encountered while processing:
AAA
E: Sub-process /usr/bin/dpkg returned an error code (1)
(where AAA,BBB,CCC are placeholder names, in case it wasn’t clear)
do
sudo dpkg -i --force-overwrite AAA
(give full path of AAA), and then run
sudo apt-get -f install
again.
And also, try googling before posting a question cause there are tons of links explaining how to fix this error!
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic Inline form in angular using material
I am trying to build a dynamic form with the help of angular material. The requirement is the I need two input columns in one row and the number of input values can be dynamic. Is there any way such that I can build this form using ng-repeat with two input box in one row.
Thanks. Any help is appreciated.
A:
You can use Flexbox. I am not sure how efficient this solution is, but it will surely give you a start.
CSS
.myrow {
display: flex;
flex-wrap: wrap;
}
.mygrid {
flex: 1;
min-width: 25%;
padding : 10px;
}
HTML
<form name="userFormTwo" novalidate>
<div class="myrow">
<div class="form-group" ng-repeat="user in formDataTwo.users" ng-class="{ 'has-error' : userFieldForm.email.$invalid }">
<div class="mygrid">
<ng-form name="userFieldForm">
<label>{{ user.name }}'s Email</label>
<input type="email" class="form-control" name="email" ng-model="user.email" required>
<p class="help-block" ng-show="userFieldForm.email.$invalid">Valid Email Address Required</p>
</ng-form>
</div>
</div>
</div>
</form>
Demo Plunker
You can also use bootstrap class(row and col-xs-12), but then you'll have to tweak your ng-repeat to loop with the increment of 2, to accommodate a pair of array elements in a single row, which would ultimately require some extra effort on the controller part just for that.
| {
"pile_set_name": "StackExchange"
} |
Q:
MouseMotionListener is not working with Canvas
This is my code so far, what I want to do is to add a new Object every time the mouse is moved, but the system is not even accessing the MouseEvent class after hours of thinking, I still am not able to figure the problem. Please Help!!
My main class:
package testing;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.Random;
public class Wincall extends Canvas implements Runnable {
public static final int HEIGHT = 640, WIDTH = 1080;
private WinTest w;
private Handler handler;
private ME me = new ME(this);
public Wincall(){
handler = new Handler();
w = new WinTest(WIDTH, HEIGHT, "Test", this);
}
public synchronized void run(){
while(true){
long now = System.currentTimeMillis();
this.tick();
this.render();
long after = System.currentTimeMillis();
int tt = (int) (after-now);
if(tt>5)
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Time Taken in millisecs : " + tt);
}
}
public void tick(){
handler.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//render
g.setColor(Color.BLACK);
g.fillRect(0 ,0 ,WIDTH, HEIGHT);
handler.render(g);
//render end
g.dispose();
bs.show();
}
public void addStuff(){
handler.addObject(new TestGO(me.getX(), me.getY(), 32, 32));
}
public static void main(String[] args){
new Wincall();
}
}
My MouseEvent class:
package testing;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class ME implements MouseMotionListener{
private int mx = 0, my = 0;
private Wincall game;
public ME(Wincall game){
this.game = game;
}
public void mouseDragged(MouseEvent e){}
public void mouseMoved(MouseEvent e) {
game.addStuff();
mx = e.getX();
my = e.getY();
System.out.println(mx);
System.out.println(my);
}
public int getX(){
return mx;
}
public int getY(){
return my;
}
}
My window class:
package testing;
import java.awt.Canvas;
import javax.swing.JFrame;
public class WinTest {
private static final long serialVersionUID = -369751247370351003L;
public WinTest(int h, int w, String title, Wincall game){
JFrame f = new JFrame(title);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(h, w);
f.add(game);
f.setVisible(true);
f.requestFocus();
f.setResizable(false);
f.setFocusable(true);
game.addMouseMotionListener(new ME());
game.run();
}
}
A:
Though its not clear what you are trying to do. But you need to add the MouseMotionListener to canvas not to the JFrame. Since you are adding canvas to the JFrame, it is the canvas which should capture MouseEvents. Hence, your Wintest should probably look like this :
public class WinTest extends Canvas {
private static final long serialVersionUID = -369751247370351003L;
public WinTest(int h, int w, String title, Wincall game, ME me) {
JFrame f = new JFrame(title);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(h, w);
f.add(game);
f.setVisible(true);
f.requestFocus();
f.setResizable(false);
f.setFocusable(true);
// f.addMouseMotionListener(me);
game.addMouseMotionListener(me);
game.run();
}
}
Update :
Wincalll Class:
public class Wincall extends Canvas implements Runnable {
public static final int HEIGHT = 640, WIDTH = 1080;
private WinTest w;
// private Handler handler;
private ME me = new ME(this);
public Wincall() {
// handler = new Handler();
w = new WinTest(WIDTH, HEIGHT, "Test", this, me);
}
public synchronized void run() {
while (true) {
long now = System.currentTimeMillis();
this.tick();
this.render();
long after = System.currentTimeMillis();
int tt = (int) (after - now);
if (tt > 5)
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println("Time Taken in millisecs : " + tt);
}
}
public void tick() {
// handler.tick();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
// render
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
// handler.render(g);
// render end
g.dispose();
bs.show();
}
public void addStuff() {
System.out.println("addStuff");
// handler.addObject(new TestGO(me.getX(), me.getY(), 32, 32));
}
public static void main(String[] args) {
new Wincall();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
PKPA to Supercede TLS/AES etc?
I wont give the name of the company, but here's a quote from a white paper they published:
Our innovative Polymorphic Key Progression Algorithm (PKPA) technology is designed to overcome the flaws and inadequacies associated with today’s encryption algorithms.
I know enough about crypto to be dangerous, but my thoughts are that this is a technology that is trying to solve a problem that doesn't exist. They cite numerous hacks, but am I wrong in assuming that such hacks are very seldom the result of the crypto technology, and instead usually the result of someone leaving the keys in the car?
A:
Sounds like snake oil for me.
The phrase you cite can be easily googled and tracked back to a white paper by CipherLoc in which they suggest that AES can be broken by using frequency analysis of english text when reusing the same encryption key for many inputs. In their explanation they deliberately ignore the role of a random IV with AES which should make such attacks infeasible. And their "solution" against this is this "PKPA" thing which somehow scrambles the data before encryption to make such frequency analysis impossible. Apart from that this is not intended to replace AES but instead used additionally to it.
A:
I agree with Steffen Ullrich's answer that this is snake oil and that a random IV would solve this problem. Just to add on to to his answer, the paper makes a number of misleading or outright false claims.
They say on page 2 that
However, with the rapid advances in computing horsepower continuing,
it was clear that the era of DES (and 3DES) encryption was coming to a
close and a new way to secure data was needed.
This is only partially correct. DES was vulnerable to brute force attacks, but not 3DES. 3DES is still secure when properly implemented, but has fallen out of favor for its high complexity and extremely poor performance.
However, with the passage of time, even AES has become susceptible to
the massive amounts of computing horsepower available in today’s world
and the increasing sophistication of cyber criminals
Complete nonsense. AES is perfectly fine when properly implemented with a mode of operation appropriate for the use case. No currently known attacks on AES are feasible.
About the 3 different key sizes, they say the following:
Interestingly, the fact that the standard supports increasingly large
key sizes was perhaps an early indication that the security may not be
entirely scalable – i.e. if AES security was stable, then no change in
key size should in fact be required.
The key size requirements were made by NIST before the AES competition concluded. They have nothing to do with concern over Rijndael; any cipher that won would have those 3 key sizes. Furthermore, this has more to do with the fact that it was a government competition, and the government thinks in terms of "security levels". The thought was you would have a fast, lower security version (AES-128); a medium performance, medium security version (AES-192); and a lower performance, high security version (AES-256). In reality, they're all fast, they're all secure, and there's no reason to split hairs unless you're worried about quantum computing, in which case you'd pick AES-192 or AES-256. See this answer by Thomas Pornin.
After totally ignoring the role of the IV as mentioned above, they go on to suggest something a bit absurd:
As a further protection, it is also possible to use different
encryption algorithms for each segment of data to be secured. For
example, segment A could use AES-256, segment B could use Blowfish,
segment C could use 3DES, etc. In fact, each segment of data could
then be further re-encrypted dozens, hundreds, or even thousands of
times. This is one of the characteristics that makes CipherLoc’s
technology very scalable. As hackers get more sophisticated and
continue to have access to ever-increasing amounts of computing
horsepower, our technology can be easily and quickly scaled to even
greater levels of security through a variety of techniques including,
but not limited to, massive amounts of re-encryption.
This solves nothing that properly applied AES does not already solve, while introducing an absolutely unfathomable amount of complexity. If you're using AES, the weaknesses in your system will not be your cipher. They will be side channel attacks, nonce reuse (if applicable), poor random number generators, fixed IVs, lousy KDFs, wrong modes of operation, lack of authentication, and plenty of other common vulnerabilities, all of which would apply anyway in this scheme. Furthermore, I shudder to think of the performance of a system that re-encrypts thousands upon thousands of times with multiple ciphers.
In summary, this scheme is unnecessary and the paper misleading (and that's being charitable).
| {
"pile_set_name": "StackExchange"
} |
Q:
Difficulty in deciding correct data structure
Two objects are interacting (Object Alpha, Object Beta)
Each contain a point (x,y) which will be used to make comparisons, among other things.
Object Alpha's point (x,y) attribute is dynamic and will change.
Object Beta's point (x,y) attribute is final.
I need to construct a data structure that contains all Object Beta's.
I was thinking of some sort of multidirectional arraylist with an index corresponding to the values of the point attribute so I can simply iterate backward and forwards to find the closest Beta's within a given range, however, how would I construct a datastructure like this?
Perhaps a linked multidimensional array? Although this would be incredibly complex when one adds or removes elements.
Any other thoughts?
Use case - Object Beta essentially is an object occupying an object in real space. Ie, it's point attribute corresponds to it's GPS location. Object Alpha is another object in real space and it's point attribute also corresponds to a GPS location. I want to quickly find the closest x amount of Beta's to Alpha's present location. Also add and remove Beta from this structure without completely redefining the entire structure. There could potentially be 1000+ object Beta's in this data structure.
A:
I recommend using an R-tree (link to Wikipedia). This is the standard data structure that most use for doing this sort of spatial indexing.
R-trees are tree data structures used for spatial access methods, i.e., for indexing multi-dimensional information such as geographical coordinates, rectangles or polygons. The R-tree was proposed by Antonin Guttman in 1984[1] and has found significant use in both theoretical and applied contexts.[2] A common real-world usage for an R-tree might be to store spatial objects such as restaurant locations or the polygons that typical maps are made of: streets, buildings, outlines of lakes, coastlines, etc. and then find answers quickly to queries such as "Find all museums within 2 km of my current location", "retrieve all road segments within 2 km of my location" (to display them in a navigation system) or "find the nearest gas station" (although not taking roads into account). The R-tree can also accelerate nearest neighbor search[3] for various distance metrics, including great-circle distance.[4]
This is a pretty thoroughly explored topic, I recommend reading the entire Wikipedia article linked at the top of the answer.
Implementations in a few different languages:
Java R-Tree
Python R-Tree
C# R-Tree
| {
"pile_set_name": "StackExchange"
} |
Q:
Wix: How to write to 32bit registers on 64 bit machine
I was looking for solution for some time but without success. I must admitt that I am begginer with wix. I have got one project (WPF + caliburn, using Visual Studio 2015) beeing compiled separately for x86 and x64. I use x64 machine to create both MSIs. Unfortunately during installation the setup always writes to 64bit registers which causes problems for the application.
I have created following components, trying to fix it using Win64="no" entry, unfortunately with no success. Can somone please advice correct component configuration?
<DirectoryRef Id="TARGETDIR">
<?if $(var.Platform)="x64"?>
<Component Id="Registry_DefaultStoragePath" Guid="123-456-789" Win64="yes">
<RegistryKey Root="HKLM"
Key="Software\KeyName" Action="createAndRemoveOnUninstall">
<RegistryValue Type="string" Name="DefaultStorageLocation" Value="[DEFAULTSTORAGE]" KeyPath="yes"/>
</RegistryKey>
</Component>
<Component Id="Registry_InstallType" Guid="123-456-789" Win64="yes">
<RegistryKey Root="HKLM"
Key="Software\KeyName" Action="createAndRemoveOnUninstall" >
<RegistryValue Type="string" Name="InstallType" Value="[INSTALLTYPE]" KeyPath="yes"/>
</RegistryKey>
</Component>
<?endif?>
<?if $(var.Platform)="x86"?>
<Component Id="Registry_DefaultStoragePath" Guid="132-456-789" Win64="no">
<RegistryKey Root="HKLM"
Key="Software\KeyName" Action="createAndRemoveOnUninstall">
<RegistryValue Type="string" Name="DefaultStorageLocation" Value="[DEFAULTSTORAGE]" KeyPath="yes"/>
</RegistryKey>
</Component>
<Component Id="Registry_InstallType" Guid="123-456-789" Win64="no">
<RegistryKey Root="HKLM"
Key="Software\KeyName" Action="createAndRemoveOnUninstall" >
<RegistryValue Type="string" Name="InstallType" Value="[INSTALLTYPE]" KeyPath="yes"/>
</RegistryKey>
</Component>
<?endif?>
A:
The main problem is that <?if $(var.Platform)="x64"?> is handled by the preprocessor, so it is evaluated at compile-time, not runtime.
In order to handle x86/x64 runtime you can do this:
<component ....>
<condition>NOT VersionNT64</condition>
<!-- 32 bit component -->
<!-- Add component content here -->
</component>
<component ....>
<condition>VersionNT64</condition>
<!-- 64 bit component -->
<!-- Add component content here -->
</component>
| {
"pile_set_name": "StackExchange"
} |
Q:
SetIntersection size without allocation
Given 2 sets (C++) is there a convenient way to get the size of the intersection without any alocations (as std::set_intersection does)
Sure, I could copy the implementation minus the assignment but I always rather not re-invent the wheel
int count = 0;
while (first1!=last1 && first2!=last2)
{
if (*first1<*first2) ++first1;
else if (*first2<*first1) ++first2;
else {
count++; ++first1; ++first2;
}
}
I was considering using std::set_intersection and pass a "counting" interator...?
A:
With some help from Boost Iterator library and C++14's generic lambdas:
#include <set>
#include <algorithm>
#include <iostream>
#include <boost/function_output_iterator.hpp>
int main()
{
std::set<int> s1 { 1,2,3,4 };
std::set<int> s2 { 3,4,5,6 };
int i = 0;
auto counter = [&i](auto){ ++i; }; // C++14
// auto counter = [&i](int ){ ++1; }; // C++11
// pre C++11, you'd need a class with overloaded operator()
std::set_intersection(
s1.begin(), s1.end(), s2.begin(), s2.end(),
boost::make_function_output_iterator(counter)
);
std::cout << i;
}
Output is 2.
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue with datepicker in ios xcode project objective c off by a day
I have a program that works fine with datepicker except when I go forward to print days in which I will be alive. It skips a day so goes 0 on birthday 0 next day and then one. When I go backwards for days alive it goes 0 1 2 ect. Can anyone help with where I went wrong? To clarify it is a simple program in a beginner level class with 2 buttons. one makes an alert box with the day of the week. The other does the same for how many days you have passed or need to pass until you will be born.
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
- (IBAction)tapBtn:(id)sender;
- (IBAction)aliveBtn:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// day of the week
- (IBAction)tapBtn:(id)sender {
NSDate *date = [self.datePicker date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"The day is" message:[dateFormatter stringFromDate:date] delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles: nil];
[alertView show];
}
//days alive or will be alive from selected birthday
- (IBAction)aliveBtn:(id)sender {
NSDate *date1 = [NSDate date];
NSDate *date2 = [self.datePicker date];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
if(numberOfDays < 0){
numberOfDays *= -1;
NSLog(@"You have been alive %d days.", numberOfDays);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Days alive" message:[NSString stringWithFormat:@"You have been alive %d days.",numberOfDays] delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles: nil];
[alertView show];
}else{
NSLog(@"you will be alive in %d days.", numberOfDays);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Days will be alive in" message:[NSString stringWithFormat:@"You will be alive in %d days.",numberOfDays] delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles: nil];
[alertView show];
}
}
@end
A:
Okay! So the problem you are seeing is when you move the date picker forward exactly ONE day, your aliveBtn: method returns 0 days until the user will be born, correct? While debugging, did you try moving the minutes forward by one? It would make the aliveBtn: method return 1 day until birth.
So, this problem stems from the math you do in aliveBtn:
int numberOfDays = secondsBetween / 86400;
Just between the time I moved the day forward, secondsBetween was equal to 86394.30585...
The problem is that you declared numberOfDays as an int. An integer can only be whole numbers; so computing 86394.30585/86400 is equal to 0.99999 which in turn, since we are speaking in integers only, becomes 0.
To fix this problem, we use one of the math functions from C called ceil(double). Simply changing
int numberOfDays = secondsBetween / 86400;
to
int numberOfDays = ceil(secondsBetween / 86400);
Will fix your problem.
Good luck, I hope this fixes your problem. If it does, please mark this answer as accepted :)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I trim the bottom of an image?
I'm trying to cut off the bottom of a image so the next row of images an fit. I've tried to trim the bottom but it hasn't worked. I want to bottom edge to be in line with the image next to it.
Here is the current page: My Page
img.left {
padding: 0 12px 0 0;
height: auto;
float: left;
width: 33.33%;
}`
What it currently looks like
A:
You could put the images into a div and control the size of that div with height, width and overflow attributes in css. A bit like this;
<div class="control" style="height: 600px;overflow: hidden; width: 100%;">
<img class="big" src="images/35473299826_50c6ced1ec_k.jpg" alt="boy
with ferry">
<img class="right" src="images/34628953174_408fac96c3_z.jpg"
alt="flowers">
<img class="left" src="images/34702862403_ddf655f873_z.jpg" alt="One of
my pictures">
</div>
The output looks like this for me; enter image description here
| {
"pile_set_name": "StackExchange"
} |
Q:
Am I likely to need multiple pairs of boots on the Appalachian Trail?
Reading up on a hiking boot size question, I came across this review from Silver Spring, Maryland for a wide hiking boot.
This boot has a "lifespan" of 400 miles. Is that typical of a hiking boot? Since the Appalachian Trail (AT) is over 2,000 miles long, should I expect one or more pairs of boots to wear out and become unusable during the course of a through-hike?
Also, if my feet do change size over the course of the hike-- or if a pair of shoes does wear out-- how do I get a new, better-fitted pair while on the trail?
A:
Do boots really last (only) 400 miles?
In short, yes. If you are a hard-man/woman, you might stretch one pair of boots to half the AT. Normal people go through quite a few pairs - I used 10-ish pairs of trail runners on the PCT (Pacific Crest Trail), partially because my feet grew 2 sizes and I didn't realize that was why I was suddenly getting blisters from my previously comfortable shoes. So if you know what's up, I think 6-8 pairs for the AT would be reasonable. Boots last a bit longer (as Kevin said, 400 miles maybe), so you might only need 4-5 pairs.
The trouble with boots in that situation is that you generally need to break them in, and a large number of thru-hikers end up with bigger feet within a few hundred miles of starting. So, you can't really buy ahead until you know whether you are the "feet grow" or "feet don't grow" type of person. Thus, using runners is pretty normal - they wear out faster but don't need breaking in.
Logistically, how do you get more boots as you hike?
On the AT, because of it's popularity, you should be able to identify some gear/shoe stores around the 200-400 miles-in corridor where you could go to try on more boots in a variety of sizes. Alternatively, and what I've done many times, is to only buy one pair before you start hiking.
If your feet stay the same size for the first month, you are probably safe, so have someone at home buy enough pairs for the rest of the trail, and mail them to you via General Delivery at post offices along the trail.
If your feet change sizes, and continue to change, order a range of sizes-widths via the internet (or someone at home) and again, have them delivered via a Post Office. Return all pairs that don't fit. Big sites like Zappos.com will do this no problem (including delivering to post offices and free returns). So once you establish your new size, you walk another 300 miles in your new boots, then order the next pair to the next PO you'll reach. Repeat until done :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why don't membrane proteins move?
I understand that based on their tertiary structure, intrinsic proteins have hydrophobic non-polar R-groups on their surface and that they 'interact with the hydrophobic core of the cell membrane to keep them in place'.
But how does the hydrophobicity of both the protein and the cell membrane prevent the protein from moving?
A:
Proteins can move around the membrane.
Most proteins do move within the membrane. The membrane is a liquid crystal and has fluid behaviour. Specifically, this is due to the membrane being in a gel-state. This gel state allows phase behaviour which means that the protein is able to move around on the surface. This results in an effect that is often referred to as the fluid mosaic model.
Proteins tend not to move out of the membrane.
The protein doesn't leave the membrane as a result of the transmembrane helix being very hydrophobic. This hydrophobicity and the hydrophobicity of the lipid tails means that they self-associate. A better way of describing it is that they fiercely dissociate from the water. A molecular dynamics simulation showed that even in simulations the membrane will readily self-assemble as a result of the hydrophobicity.
This is achieved by a few properties of the TMH sequence. There is a large amount of hydrophobic residues like leucine. At either end of the helix are large aromatic residues called the aromatic belt. Further is the electrostatic satisfaction offered by Gunnar von Heijne's famous positive inside rule and the recently identified negative-outside rule present in helices with evolutionary pressure to optimise anchorage.
(Image source: Baker et al., 2017)
Cymer et al. published a study showing the free energies associated with each part of the transmembrane protein helix (figure below). The overall ΔG for a transmembrane helix in the membrane is ~-12kcal mol−1. This means that the association of the helix in the membrane is typically spontaneous.
(Image source: Cymer et al., 2015)
A:
No other answer has mentioned this so I created an account just to say this.
Some membrane proteins do not move. This is because they are fixed in that position in the membrane due to the cytoskeleton. Erythrocytes are a good example of this.
The main protein that is immobilised in erythrocyte membrane is Band 4.1 protein, and its immobilised by Spectrin.
Spectrin forms a tetramer(2 dimers together) that acts like a chain/rope connecting membrane proteins and locking them in place. Spectrin connects to the Band 4.1 protein (also to actin, but less important).
Spectrin also binds to Band 3 protein (via ankyrin, just a protein that connects spectrin to band 3). Band 3 is an anion channel (for HCO3- and Cl-, which is important for red blood cells to function. you want these band 3 proteins to remain evenly spaced out, so they are fixed in the membrane to make sure)
It is important for some membrane proteins not to move. Otherwise the cell will lose its function in some cases(like intestinal epithelial cells), imagine if SGLUT-1 (glucose + galactose transporter) moves from the luminal side(facing lumen) to the basolateral side(the other side)... what do you think happens to its ability to take in glucose from intestinal lumen?
Finally as a bonus, some membrane proteins are also fixed in the plasma membrane in plants (does not move around) by cell wall.
Anyway, if you are bored of someone immediately saying "fluid mosaic model means proteins always move around!" then read my answer
A:
There are two types of proteins that are present in a membrane, because you have not been specific about which type of protein you are talking about I will consider that you are talking about Integral membrane proteins.
For more clarity I will begin by explaining to you what are these proteins present in the membrane.
As I said there are two types of proteins 1.
Integral membrane proteins - these are proteins that are present inside the membrane.
Peripheral membrane proteins - These are the proteins present outside the membrane on either side linked through weak electrostatic interactions with the lipids or the integral membrane proteins.
As it is clear from the diagram given below.
[2]
You have not been clear about which type of protein you are talking about so I assume that you are talking about Integral proteins.
You stated in a nutshell that protein is hydrophilic so it should move out of the membrane as the membrane is hydrophobic. ( correct me if I am wrong here).
You are highly mistaken here. Yes there are R groups present on the protein but when the protein undergoes transitions to secondary and tertiary structure these hydrophilic R groups move to the innermost in the protein structure and hydrophobic groups are outside facing the lipid sea, so they can establish hydrophobic interactions with the lipids.
Integral proteins Do not move out of the membrane because of the strong hydrophobic interactions.
But they do move inside the membrane. As the membrane structure is fluid mosaic. Imagine of proteins as floating in a sea of lipids.
https://www.ncbi.nlm.nih.gov/books/NBK26878/
1 = Principles of Biochemistry Lehninger.
[2] = http://cbc.arizona.edu/classes/bioc462/462a/NOTES/LIPIDS/Membranes.html for the image.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find database name of \data\base postgres folders?
I have a large folder of 70 GB in my postgres installation under:
D:\Program Files\PostgreSQL\9.5\data\base\130205
Question: how could I find out which database is based on that folder?
I have like 10 databases running on the same server, and most of them having a tablespace on a different drive.
But probably I'm missing a mapping somewhere, maybe a large index or kind of. How can I find out the "causing" database of these amounts of data?
A:
Thanks to the hint of @a_horse, the following statement shows the oid and table names:
SELECT oid,* from pg_database
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't link known file extensions to custom editor classifier
I am working on an editor classifier extension for classic Visual Basic source files (module- and class files). The project has been created using the editor classifier project template from the Visual Studio 2012 SDK. The wizard created three code files: one for the classifier, one for the classifier-format and -provider and another one containing classification definitions. I made the following changes to the last one in order to link *.bas and *.cls files to my custom classifier...
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
internal static class MyEditorClassifierClassificationDefinition
{
[Export(typeof(ClassificationTypeDefinition))]
[Name("MyEditorClassifier")]
internal static ClassificationTypeDefinition MyEditorClassifierType = null;
[Export]
[Name("custom")]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyContentDefinition = null;
[Export]
[FileExtension(".bas")]
[ContentType("custom")]
internal static FileExtensionToContentTypeDefinition MyModuleFileExtensionDefinition = null;
[Export]
[FileExtension(".cls")]
[ContentType("custom")]
internal static FileExtensionToContentTypeDefinition MyClassFileExtensionDefinition = null;
}
The problem is, that Visual Studio does not invoke my classifier for files having *.bas, or *.cls extensions, instead the built-in editor for Visual Basic is used. I already tested my editor classifier using a custom file extension; in that case the classifier works as expected. I would like to know, if it's possible to change the classifier for known file extensions.
A:
I found an intresting solution for classifying keywors are already classifyed by a language service. It's description says it uses a Tagger to enhance code highlighting. Maybe it can help you: KeywordClassifier
Older version of the linked project used a classifier mentioned in the description.
You can get the name of the loaded document, also the extension with ITextDocumentFactoryService or maybe there is a way to bind the tagger also to extensions not only to the content type of Basic (instead of code). FileExtensionAttribute may help.
| {
"pile_set_name": "StackExchange"
} |
Q:
How could the person in Luke 9:49 cast out demons without Jesus' mandate?
Luke 9:49 (ESV):
John answered, “Master, we saw someone casting out demons in your name, and we tried to stop him, because he does not follow with us.”
The 12 (and later the 70) only started healing people and casting out demons AFTER Jesus "gave them power and authority over all devils, and to cure diseases."
The Holy Spirit had not been sent yet, so with what authority was this person acting?
I am not questioning the good will of the anonymous healer. Was he an imposter Jesus would have stated so.
What I'm really wondering is that people didn't need a direct command (or mandate) from Jesus to act in His name?
A:
DEV--Don's Edited Version
The answer to your question comes from Jesus, and also from the words of John in the verse you quoted.
John's words: John assumed that because the unnamed exorcist was not in the inner circle of the Twelve that his exorcism could not therefore be on the "up and up."
Jesus' words: In essence, Jesus told John (and all the other disciples who were present during the "Who is the greatest?" incident),
"Hey [he didn't say 'Hey'], if that person you speak of exorcised demons in my name successfully, then he must be one of us, even though he is not a member of this particular group of twelve disciples."
I think many Christians (and I count myself among that number) assume that the only disciples who performed miracles in Jesus' name were those whom Jesus sent out (or commissioned, as in Mark 6:7, Luke 9:2 and 10:1) to precede him and pave the way for him by preaching the kingdom and by performing miracles such as exorcisms and perhaps other works of healing. This assumption may not be warranted, particularly in light of Jesus' words; namely,
"'Do not hinder him [i.e., the man who cast out demons], for he who is not against you is for you'" (Luke 9:50)
In other words, Jesus could very well have commissioned this man on a one-to-one basis. Perhaps for whatever reason this man could not "follow along with"--as John put it--the Twelve or some other recognizable group of Jesus-followers (e.g., "the 70" in Luke 10:1), so Jesus permitted him to heal people in Jesus' name.
I think it unwise to assume, for example, that this man was a nonbeliever (similar to Simon Magus in Acts 8:9 ff.) and a "Lone Ranger" who was performing miracles without Jesus' sanction. Jesus could very well have sanctioned him to perform these miracles. Moreover, as I've suggested above, Jesus seems to have assumed that since the man performed miracles "in Jesus' name," that he was indeed "one of us"--meaning the Twelve and all his other disciples, even if John did not recognize him as such.
In conclusion, there is no reason of which I am aware why this "lone wolf exorcist" was any more in need of the sending authority of the Holy Spirit than were the Twelve. After all, the Holy Spirit did not commission the Twelve (and others); Jesus did. On the authority of Jesus, the Twelve and this unnamed disciple were given the ability to heal. The power to do so undoubtedly came from the Holy Spirit, but the disciples were not even aware at this point that there was such a person called the "Holy Spirit." That awareness came later (e.g., in John 15).
Additional Thought/Addendum
Jesus had a way of surprising--shocking even--his closest followers and disciples. Example par excellence: Jesus' conversation with the Samaritan woman at the well of Sychar, in John 4:4-45. This woman had a number of strikes against her, at least from the disciples' perspective:
She was a she. In other words, she was a second- or third-class citizen, as were most women in those days (with a few exceptions, to be sure).
She was a member of a despised people group, the Samaritans, whom the Jews considered to be a bunch of religious half-breeds--which was partly true, since after the divided kingdom and the subsequent exile of Israeli Jews, Samaria was "seeded" with the importation of foreign colonists who brought their own syncretistic views of religion to Palestine. Consider Wayne Brindle's comments:
"The development of Samaritanism and its alienation from Judaism was a process that began with the division of the kingdom of Israel, and continued through successive incidents which promoted antagonism, including the importation of foreign colonists into Samaria by Assyria, the rejection of the new Samaritan community by the Jews, the building of a rival temple on Mt. Gerizim, the political and religious opportunism of the Samaritans, and the destruction of both the Samaritan temple and their capital of Shechem by John Hyrcanus during the second century B:C. The Samaritan religion at
the time of Jesus had become Mosaic and quasi-Sadducean, but strongly anti-Jewish. Jesus recognized their heathen origins and the falsity of their religious claims."
She was a woman of questionable morals. (Today, a bigot would probably label her a slut!)
She was alone with Jesus and conversed with him in a give-and-take discussion, which could have lasted an hour or more. Pious Jewish men simply did not talk with women in public, let alone have a religious confabulation. Unthinkable!
She gave Jesus a drink of water from her own bucket, which to the Jews of Jesus' day would be unthinkable (just think of the ritual uncleanness of it all!).
Nevertheless, Jesus, John tells us, "had to pass through Samaria" (4:4). Why? Because a Samaritan woman had a divine appointment with her soon-to-be Savior and Lord! Jesus could have bypassed Samaria as he travelled from northern Israel to southern Israel, as did his fellow Jews, but he was never one to depart from the path his Father had chosen for him. Furthermore, his Father and he shared a love for outcasts, outsiders, the foreigner, the stranger, and the alien. Why else would the Law of Moses contain so many instructions regarding the humane treatment of non-Hebrews with whom the Israelis interacted.
My point is this: John--and perhaps the other disciples--did not realize at the time he registered his opinion about the "interloper" who was casting out demons in Jesus' name
that Jesus' compassionate heart had room for outsiders and interlopers, such as the Samaritan woman at the well, and also the Syro-Phoenician woman whose daughter was plagued by a demon:
"Then Jesus went thence, and departed into the coasts of Tyre and Sidon. And, behold , a woman of Canaan came out of the same coasts, and cried unto him, saying , 'Have mercy on me, O Lord, thou Son of David; my daughter is grievously vexed with a devil.' But he answered her not a word. And his disciples came and besought him, saying , 'Send her away; for she crieth after us.' But he answered and said, 'I am not sent but unto the lost sheep of the house of Israel.' Then came she and worshipped him, saying, 'Lord, help me.' But he answered and said, 'It is not meet to take the children's bread, and to cast it to dogs.' And she said, 'Truth, Lord: yet the dogs eat of the crumbs which fall from their masters' table.' Then Jesus answered and said unto her, 'O woman, great is thy faith: be it unto thee even as thou wilt.' And her daughter was made whole from that very hour'" (Matthew 15:21-28 KJV).
In conclusion, the people to whom Jesus reached out may not have fit the mold of "disciple material" which was in John's (and others') mind, but then Jesus was not big on molds. Jesus was more interested in people's hearts, and he was an equal opportunity Savior, Healer, and Lord, and not just to "the lost sheep of the house of Israel."
| {
"pile_set_name": "StackExchange"
} |
Q:
Integrals of $\int^\infty _2 \frac{x}{x^3 -2\sin x}dx$
How do I calculate the convergence of $\int^\infty_2\frac{x}{x^3 -2\sin x}dx$ ?
I know in generally, integration of (n-dimentional polynomial)/(n+2-dimentional polynomial) will be converge.
A:
$$\left|\int^2_\infty \frac{x}{x^3 -2\sin x}dx\right| \leq \int_2^\infty \left|\frac{x}{x^3 -2\sin x}\right|dx \leq \int_2^\infty \frac{x}{|x^3 -2\sin x|}dx=\int_2^\infty \frac{x}{x^3 -2x}dx=\dfrac{1}{2\sqrt{2}}\ln\dfrac12(2+\sqrt{2})^2$$
Note:
$$|x^3 -2\sin x|\geq|x^3| -2|\sin x|\geq|x^3| -2|x|=x^3-2x$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving Plancherel's theorem using Cauchy integral formula
Plancherel's theorem says that
$f(x) = \frac{1}{2\pi} \int^\infty_{-\infty} F(k) e^{ikx} dk$
where
$F(k) = \int^\infty_{-\infty} f(x)e^{-ikx}dx$.
I'm wondering if we can prove this using Cauchy's integral formula somehow like this.
$f(x) = \frac{1}{2\pi} \int^\infty_{-\infty} \int^\infty_{-\infty} f(x')e^{-ikx'} dx' e^{ikx} dk$
$= \frac{1}{2\pi} \int^\infty_{-\infty} \int^\infty_{-\infty} e^{ik(x-x')} dk f(x') dx'$
$= \lim_{k_0\rightarrow\infty} \frac{1}{2\pi} \int^\infty_{-\infty} \frac{1}{i(x-x')} (e^{ik_0(x-x')}-e^{-ik_0(x-x')}) f(x') dx'$
$= \lim_{k_0\rightarrow\infty} -f(x)+f(x)$
$=0$
where I used Cauchy's integral formula in the next to last equality. I did contour integral over a upper half-circle and assumed f(x) goes to 0 at large x. However I got 0 instead of $f(x)$ at the last equality. I believe there are some problems in my understanding of complex analysis, so please let me know them!
A:
Observe that
$$\begin{align}
\frac{1}{2\pi} \int\limits^\infty_{-\infty} \int\limits^\infty_{-\infty} \textstyle f\left(x'\right)\,\exp\left({-\text{i}kx'}\right)\, \text{d}x'\, \exp({\text{i}kx})\, \text{d}k
&=\lim_{k_0\rightarrow\infty}\, \frac{1}{2\pi}\, \int\limits^{+\infty}_{-\infty} \textstyle\frac{\exp\big({+\text{i}k_0\left(x-x'\right)}\big)-\exp\big({-\text{i}k_0\left(x-x'\right)}\big)}{\text{i}(x-x')} \,f\left(x'\right)\, \text{d}x'
\\
&=\lim_{k_0\rightarrow\infty}\,\frac{1}{2\pi\text{i}}\,\int\limits^{+\infty}_{-\infty}\textstyle \,\frac{\exp\big({\text{i}k_0\left(x'-x\right)}\big)}{x'-x} \,\big(f\left(x'\right)+f\left(2x-x'\right)\big) \,\text{d}x'\,.
\end{align}$$
Furthermore, your contour goes about the pole at $x$ half a turn. Hence, we have that
$$\lim_{k_0\rightarrow\infty}\,\frac{1}{2\pi\text{i}}\,\int\limits^{+\infty}_{-\infty} \,\frac{\exp\big({\text{i}k_0\left(x'-x\right)}\big)\big)}{x'-x}\, \big(f\left(x'\right)+f\left(2x-x'\right)\big)\, \text{d}x'=\frac{1}{2}\big(f(x)+f(x)\big)=f(x)\,.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Linear regression. Lowering response maintaining equal independent variable.
I have put some data together and modelled the behaviour of the response ($y$) as function of three independent variables $x_1$, $x_2$ and $x_3$. A simple multi-linear regression. The model looks like:
$y = k + a*x_1 + b*x_2 + c*x_3 + e$
Up to this point everything is OK. But now I want to lower the response by a $15%$. Like reducing some commissions or costs. The only idea I came across is to multiply the responses by $0.85$ and readjust the whole model. Recalculate $a$, $b$ and $c$ with the new values. I have been trying to find another way of doing this without touching the data samples. Just changing and adjusting the coefficients $a$, $b$ and $c$. Does anybody know how this should be done? An idea you come across with would be okay.
A:
The regression coefficients are given by:
$\hat{\beta} = (X'X)^{-1}X'Y$
Thus, if you scale $Y$ values by $0.85$ then this is effectively equivalent to the following:
$Y_{\text{new}} = 0.85e' Y $
where,
$e$ is a vector of ones.
Thus, the new estimate is given by
$\hat{\beta}_{\text{new}} = (X'X)^{-1}X' (0.85 e'Y)$
Thus, you get the following relationshiop:
$\hat{\beta}_{\text{new}} = 0.85 \hat{\beta}$
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I have Gmail overwrite a known email with my contact info when a name is not supplied?
I have to admit I was a little confused when I asked this question, as I thought that it was my Gmail where names and email addresses were connected.
But of course, it's not the local Gmail client that attaches a name to an email for display when receiving, it's whether or not the sender has a name attached to their email, as explained in the answer.
Okay... but, can I set Gmail up in a way so that it will replace a known email address with the name I have for them in my contacts in situations when someone sends me an email with no name set? Or, even better, over rides their name with the one I have set in any case (since I think of them by the name I have set, not what they have set)?
This is standard practise when it comes to phone numbers - when someone calls my Android phone, I see the name that I have set in my contact list. Hopefully this could be done with emails as well.
A:
Currently still no, and probably never. The name that is displayed when you receive an email is the name embedded into that emails from:header. BUT there are two workarounds that I can think of, hopefully one will help you!
Use Filters
One workaround solution is to filter the email address and apply a label to it. This can help if their name is causing any confusion (eg. I have 4 people called Mike)
The Pros of using this is that it will sync across all your computers and devices.
Use a Script
There is a script called DisplayName gmail that takes the contacts name (the one you have set in your contacts list) and displays that instead of their from: name.
You will need to install tampermonkey (Chrome) or greasemonkey (Firefox) and then you can install the script DisplayName gmail (tested and working with chrome).
The cons of using a script is that its not going to work across multiple computers - you would need to install the script on each computer you use. And this also work on your phone.
| {
"pile_set_name": "StackExchange"
} |
Q:
iOs: How to change color of "more" back button when having more than 5 tabs
I have an application with 6 tabs, so the system automatically generates the first 4 tabs and a fifth tab called "Altro" ("More" in italian) that contains the previous fifth and sixth tab content.
This is ok. The problem is that i don't know how to change the color of the back button when going through the "altro" tab. Any advice?
Some screenshot for a better explanation of the problem:
A:
UIImage *buttonImage = [UIImage imageNamed:@"back_btn.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, buttonImage.size.width/2, buttonImage.size.height/2);
[button addTarget:self action:@selector(backPressed) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customBarItem;
Try this.......once
| {
"pile_set_name": "StackExchange"
} |
Q:
Does my "hollow list" structure exist already?
I came up with an implementation in c for arrays which can be extremely large yet only use an amount of memory proportional to how much data you have written to it. What I want to know is if there is a name for this kind of list or structure. Here is my code in C for the structure and example use:
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
typedef struct hollow_list hollow_list;
struct hollow_list{
unsigned int size;
void *value;
bool *written;
hollow_list *children;
};
//Creates a hollow list and allocates all of the needed memory
hollow_list hollow_list_create(unsigned int size){
hollow_list output;
output = (hollow_list) {.size = size, .value = (void *) 0, .written = calloc(size, sizeof(bool)), .children = calloc(size, sizeof(hollow_list))};
return output;
}
//Frees all memory of associated with a hollow list and its children
void hollow_list_free(hollow_list *l, bool free_values){
int i;
for(i = 0; i < l->size; i++){
hollow_list_free(l->children + i, free_values);
}
if(free_values){
free(l->value);
}
free(l);
}
//Reads from the hollow list and returns a pointer to the item's data
void *hollow_list_read(hollow_list *l, unsigned int index){
if(index == 0){
return l->value;
}
unsigned int bit_checker;
bit_checker = 1<<(l->size - 1);
int i;
for(i = 0; i < l->size; i++){
if(bit_checker & index){
if(l->written[i] == true){
return hollow_list_read(l->children + i, bit_checker ^ index);
} else {
return (void *) 0;
}
}
bit_checker >>= 1;
}
}
//Writes to the hollow list, allocating memory only as it needs
void hollow_list_write(hollow_list *l, unsigned int index, void *value){
if(index == 0){
l->value = value;
} else {
unsigned int bit_checker;
bit_checker = 1<<(l->size - 1);
int i;
for(i = 0; i < l->size; i++){
if(bit_checker & index){
if(!l->written[i]){
l->children[i] = hollow_list_create(l->size - i - 1);
l->written[i] = true;
}
hollow_list_write(l->children + i, bit_checker ^ index, value);
break;
}
bit_checker >>= 1;
}
}
}
int main(){
int a = 221;
int b = 222;
int c = 9;
int d = 89;
hollow_list h;
h = hollow_list_create(30);
hollow_list_write(&h, 221999999, &a);
hollow_list_write(&h, 9999, &b);
hollow_list_write(&h, 22999999, &c);
hollow_list_write(&h, 1, &d);
printf("%d\n", *((int *) hollow_list_read(&h, 221999999)));
printf("%d\n", *((int *) hollow_list_read(&h, 9999)));
printf("%d\n", *((int *) hollow_list_read(&h, 22999999)));
printf("%d\n", *((int *) hollow_list_read(&h, 1)));
printf("\n");
printf("\n");
printf("\n");
printf("%d\n", a);
printf("%d\n", b);
printf("%d\n", c);
printf("%d\n", d);
c = 56;
printf("%d\n", *((int *) hollow_list_read(&h, 22999999)));
}
These lists seem to be really useful alternatives to linked lists, and fast too: the worst case scenario for a read or write to a list is O(log n) for a list of n elements. I'd be surprised if this kind of structure didn't already exist, but I would simply like to know what it is called so I could refer to it by it's proper name haha.
A:
This is a sparse array data structure, but I haven't seen this exact data structure before. It looks like your code builds a balanced binary tree, but with a particularly clever representation in memory.
One difference between other balanced binary trees is that the running time of your approach is $O(\lg m)$ where $m$ is the largest index written, whereas other balanced binary tree data structures (e.g., red-black trees) have a $O(\lg n)$ running time where $n$ is the number of indices written to. Since $m \ge n$, in principle your approach might be slower if $n$ is small (few elements have been written) but the indices are large. However in practice I don't expect this to make much difference, ordinarily.
| {
"pile_set_name": "StackExchange"
} |
Q:
Derive asymptotic behavior of inverse of the normal cdf with respect to 2^n
I have a normal distribution $\mu = 0$ and $\sigma = 0.58n$ where $n > 0 $ and I am trying to derive the asymptotic behavior of the following equation:
$$\Phi\left(\frac{x}{0.58n}\right)\;=\;2^{1-n}$$
Follows:
$$
\DeclareMathOperator\inverfc{inverfc}
x = -0.58 \sqrt{2}n \inverfc{({2^{2 - n}})}
$$
So I want to find $O( n\inverfc{({2^{2 - n}})}) $.
More specifically I want to confirm my suspicion that it is in $O(n \log{n})$. However since Inverf is a special function I can't wrap my mind around to analyse it. I gave complete context since another derivation might be more helpful here.
A:
When $z\to+\infty$, $\Phi(-z)\sim1/(z\mathrm e^{z^2/2}\sqrt{2\pi})$. Since $2^{1-n}\to0$, this is the regime of interest. The solution of $\Phi(-z_n)=b\mathrm e^{-cn}$ with $b=2$ and $c=\log2$ solves $b\sqrt{2\pi}z_n\mathrm e^{z_n^2/2}\sim\mathrm e^{cn}$, that is,
$$
z_n^2+2\log z_n=2cn-\log(2\pi)-2\log b+o(1),
$$
in particular $z_n\sim\sqrt{2cn}$.
The question asks about $x_n=-anz_n$ with $a=0.58$ hence $x_n\sim -an\sqrt{2cn}$, in particular $x_n=\Theta(n\sqrt{n})$ hence $x_n=\Omega(n\sqrt{n})$ and $x_n=O(n\sqrt{n})$.
If need be, the equivalent in the first paragraph yields more precise estimates, for example, one has $z_n=\sqrt{2cn}-\log n/\sqrt{8cn}+o(\log n/\sqrt{n})$ hence, introducing $\alpha=a\sqrt{2c}$ and $\beta=a/\sqrt{8c}$,
$$
x_n=-\alpha n\sqrt{n}+\beta\sqrt{n}\log n+o(\sqrt{n}\log n).
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
MariaDB Galera Cluster, Force Sync
I have three servers in a multi-master Galera cluster. I've imported some old databases recently, and noticed that the tables were being created across all three, but the data wasn't being replicated. It turns out I wasn't paying attention, and these old databases were all using MyISAM tables. So I know that in the future, I'll need to convert these to InnoDB before bringing them in to make them work.
However, I'm not having any luck finding an official way to sync up the existing data. Running ALTER TABLE to convert the existing tables to InnoDB doesn't sync up the existing data.
My thought was to dump the table (now that it's been converted) with mysqldump, then bring it back in with mysql -u user -p db < db.sql. I don't see any reason why that wouldn't work, but I'm wondering if there's a better way.
A:
I was not able to find an official way to handle this, so I went with the idea of dumping the tables individually and reimporting them. Not wanting to do it by hand, I whipped a PHP script to do it for me. I'm posting it here in case anyone else finds this useful.
/*
* InnoDB Convert
* Converts existing non-InnoDB tables to InnoDB, then re-imports the
* data so that it's replicated across the cluster.
*/
// Configuration
$_config['db'] = array(
'type' => 'mysql',
'host' => 'localhost',
'username' => 'user',
'password' => 'password'
);
// Establish database connection
try {
$pdo = new PDO(
$_config['db']['type'] . ':host=' . $_config['db']['host'],
$_config['db']['username'],
$_config['db']['password']
);
} catch ( PDOException $e ) {
echo 'Connection failed: ' . $e->getMessage();
}
// Get list of databases
$db_query = <<<SQL
SHOW DATABASES
SQL;
$db_result = $pdo->prepare( $db_query );
$db_result->execute();
while ( $db_row = $db_result->fetch( PDO::FETCH_ASSOC )) {
// Look through databases, but ignores the ones that come with a
// MySQL install and shouldn't be part of the cluster
if ( !in_array( $db_row['Database'], array( 'information_schema', 'mysql', 'performance_schema', 'testdb' ))) {
$pdo->exec( "USE {$db_row['Database']}" );
$table_query = <<<SQL
SHOW TABLES
SQL;
$table_result = $pdo->prepare( $table_query );
$table_result->execute();
while ( $table_row = $table_result->fetch( PDO::FETCH_ASSOC )) {
// Loop through all tables
$table = $table_row["Tables_in_{$db_row['Database']}"];
$engine_query = <<<SQL
SHOW TABLE STATUS WHERE Name = :table
SQL;
$engine_result = $pdo->prepare( $engine_query );
$engine_result->execute( array(
':table' => $table
));
$engine_row = $engine_result->fetch( PDO::FETCH_ASSOC );
if ( $engine_row['Engine'] != 'InnoDB' ) {
// Engine is not equal to InnoDB, let's convert it
echo "Converting '$table' on '{$db_row['Database']}' from '{$engine_row['Engine']}' to InnoDB:\n";
echo "Modifying engine...";
$change_query = <<<SQL
ALTER TABLE $table ENGINE=InnoDB
SQL;
$change_result = $pdo->prepare( $change_query );
$change_result->execute();
echo "done!\n";
echo " Exporting table...";
exec( "mysqldump -h {$_config['db']['host']} -u {$_config['db']['username']} -p{$_config['db']['password']} {$db_row['Database']} $table > /tmp/dump-file.sql" );
echo "done!\n";
echo " Re-importing table...";
exec( "mysql -h {$_config['db']['host']} -u {$_config['db']['username']} -p{$_config['db']['password']} {$db_row['Database']} < /tmp/dump-file.sql" );
echo "done!\n";
unlink( '/tmp/dump-file.sql' );
echo "done!\n";
}
}
}
}
I successfully used it to convert hundreds of tables across a couple dozen databases in about two minutes.
| {
"pile_set_name": "StackExchange"
} |
Q:
number of distinct object types in a list
I am using C#, Silverlight, Visual Studio for Windows Phone 7.
I currently have a List that contains the generic UIElement, and I can put things like TextBlock or Grid or StackPanel into the List.
For example:
List<UIElement> UIList= new List<UIelement>();
UIList.Add(someUIObject as UIElement);
My question is, is there an efficient way to count the number of object types in my list? For example, if there are 8 TextBlocks and 4 Grids, I would like to know that there are 2 object types in the List. Or if there is 1 TextBlock, 1 Grid, and 1 StackPanel, I would like to know that there are 3 types of objects.
I'm looking for something that is better than O(n^2) performance. My current solution compares each element type to the rest of the element types in the List, something similar to BubbleSort.
A:
To get the number of different types in the collection, I would use LINQ to first select the type of each object, then took only distinct types and counted those:
int numberOfTypes = UIList.Select(x => x.GetType()).Distinct().Count();
All of this will be O(n), because Distinct() uses a hash table.
A:
try out
var loader = loaders.OfType<Elementtype>().Count();
A:
var types = UIList.GroupBy(ui => ui.GetType())
.Select(g => new { Type = g.Key, Count = g.Count() })
.ToList();
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this argument of AGGREGATE function doing in my formula?
I need to understand this part ($B$1:$B$15<>"") in the following formula used to represent a column of data with blank cells removed:
=IFERROR(INDEX($B$1:$B$15,AGGREGATE(15,6,(ROW($B$1:$B$15)-ROW($B$1)+1)/($B$1:$B$15<>""),ROWS(C$1:C1))),"")
This formula was given on another site for the question Remove Blanks from a Column with Formula, but I could not find more info about it.
I especially want to know what this part does: ($B$1:$B$15<>"").
I can guess it is a range not "", but I cannot figure it out its usage in that formula.
Can someone help me on this matter?
Thank you.
A:
The part you queried is doing as you say:
$B$1:$B$15<>""
That returns an array of TRUE/FALSE values, FALSE if each cell is blank and TRUE if it's not. In the formula an array of the relative row numbers is divided by that array - when you divide by TRUE that acts as a 1 so you just get the row number, when you divide by FALSE that acts like zero so you get a #DIV/0! error.
AGGREGATE function is set to ignore errors so it finds the kth smallest row where B1:B15 is not blank
......then INDEX returns the actual value for that cell.
In cell one - C1 ideally - k = 1 so you get the first non-blank value then ROWS function increments as you copy down so you get each subsequent non-blank value
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting "application not configured for implicit grants" error trying to setup website
I had a developer setup StackExchange auth for a site last year and that still works fine. I have cloned that site and am in the process of changing out all of the relevant names and keys to the new site, hoping that it would Just Work. But alas, I am getting this error:
I haven't changed very much from the flow that i said was working for the other site, just trying to swap out the keys and such. Here is the JS code:
SE.init({
clientId: <?php echo STACKAPPS_CLIENT_ID; ?>,
key: '<?php echo STACKAPPS_KEY; ?>',
channelUrl: '<?php echo STACKAPPS_CHANNEL; ?>',
complete: function (data) {
//console.log(data);
}
});
// Attach click handler to login button
$('#soLo').click(function() {
// Make the authentication call, note that being in an onclick handler
// is important; most browsers will hide windows opened without a
// 'click blessing'
SE.authenticate({
success: function(data) {
$.get('sign-in.php?seat='+data.accessToken,function() {
location.reload();
});
//$('#soLo').hide();
},
error: function(data) {
//alert('An error occurred:\n' + data.errorName + '\n' + data.errorMessage);
},
networkUsers: false
});
});
And the PHP that button press redirects to:
if ($_REQUEST['seat']) {
//check if seUser is real;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.stackexchange.com/2.1/me?key=".STACKAPPS_KEY."&site=stackoverflow&order=desc&sort=reputation&access_token=".$_REQUEST['seat']."&filter=default");
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = json_decode(curl_exec($ch));
curl_close($ch);
if ($output->items[0]->account_id) {
$_SESSION['seUser'] = $output->items[0]->account_id;
$_SESSION['displayName'] = $output->items[0]->display_name;
$_SESSION['seReputation'] = $output->items[0]->reputation;
$params = array(
'className' => 'users',
'query' => array(
'so_id'=> (string) $_SESSION['seUser']
),
'limit' => '1',
);
$request = json_decode($parse->query($params));
$user = $request->results[0]->username;
$_SESSION['login'] = 'stack';
if ($user) {
$_SESSION['curUser'] = $user;
$_SESSION['logout'] = true;
} else {
$_SESSION['saveSo'] = true;
}
}
session_write_close();
die();
}
Does anything look out of place here? I looked at the auth documentation and it looks like I am following the implicit path.
A:
Yes, it can be annoying that the API docs, the javascript SDK, and the settings pages use the terms:
"Explicit"
"Implicit"
"Server side"
"Client side"
a little interchangeably. (The first 2 are roughly synonymous with the last two.)
From the javascript SDK docs:
Your application must have the client side OAuth flow enabled, and must not have the desktop application redirect uri disabled. Both of these settings are available on an applications edit page.
Go to your apps list (visible only to you).
Click on your app.
Check your settings. See the picture, below:
Enable Client Side OAuth Flow ==> checked
Disable Desktop Application OAuth Redirect Uri ==> not checked
OAuth Domain ==> stackexchange.com
Application Name ==> (not blank and no error message)
Description ==> (not blank and no error message)
Application Website ==> https://stackapps.com/ (Not critical for this kind of auth.)
Optional: If you want write access, Stack Apps Post must be set to a valid post that you own.
EG, https://stackapps.com/questions/5017/ works for the user that owns that post.
The post must legitimately have either the app or the script tag.
Then:
| {
"pile_set_name": "StackExchange"
} |
Q:
How to go to implementation by vsvim + r#
I want to use r# and vsvim to go to implementation in visual studio. Like command "gd", but maybe "gi".
Can i do it?
A:
Yes, you can.
Assuming that you already have a vsvimrc customization file, you just need to add:
map gi :vsc Edit.GoToImplementation<CR>
FYI my full vsvimrc is here, with many other tricks, such as:
map gk :vsc Edit.PreviousMethod<CR>
map gj :vsc Edit.NextMethod<CR>
map gr :vsc Edit.FindAllReferences<CR>
map <Leader>k :vsc Window.PinTab<CR>
noremap + :vsc Edit.CommentSelection <return>
noremap - :vsc Edit.UncommentSelection <return>
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a quick way to report database metadata in SQL Server 2005?
Are there any system stored procs to report the stats and metadata of a database itself in SQL Server 2005?
What I need is a quick way to output a list of tables, the size of each table, the number of rows in each table and so on. Stored procs for individual tables and metadata would also be useful.
Advice appreciated.
A:
Yes, the data dictionary tables will let you do this. The main tables in the data dictionary are sys.objects, sys.columns, sys.indexes, sys.foreign_keys and sys.sql_modules. For an example of a variety of queries that use the system data dictionary to reverse-engineer a database to an SQL script, take a look at this stackoverflow posting.
Getting space usage is a bit more convoluted to do from the data dictionarybut sp_spaceused will do it for a single table. You can wrap this with sp_msforeachtable to iterate over a set of tables and get the report for all of the tables.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML encoding escaping problems
I'm doing an Android app in which I make a query to a webservice, get a JsonObject and after getting the desired String I find strings like: est&aacute;
I've tried this two:
StringEscapeUtils.escapeHTML4(text);
With the result of transforming &aacute into &amp;aacute
Html.escapeHtml(test));
Which does nothing.
Any ideas how too transform this into á or the corresponding character?
A:
You stated you had used the following:
StringEscapeUtils.escapeHTML4(text);
Instead try this:
StringEscapeUtils.unescapeHTML4(text);
You were re-encoding the HTML entitites;
Documentation here:
https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringEscapeUtils.html
// import commons http://commons.apache.org
import org.apache.commons.lang3.StringEscapeUtils;
public static String stripHtml(String str) {
return StringEscapeUtils.unescapeHtml4(str.replaceAll("<[A-Za-z/].*?>", "")).trim();
}
In addition, you can use this to decode other encoded types (JSON, XML, etc) or use it to encode.
This isn't what you asked but may also be useful for URL decoding:
String result = URLDecoder.decode(url, "UTF-8");
API reference here:
http://docs.oracle.com/javase/7/docs/api/java/net/URLDecoder.html
| {
"pile_set_name": "StackExchange"
} |
Q:
White screen when I fetch data from MySQL on PHP into an Array
I'm taking values from MySQL(PHPMyAdmin) to PHP and after that, I send them to an echo for taking those values on Ionic. I don't know why but when I add a specific value (Bio field from MySQL) inside the array and execute the .php file thows me a white screen.
Here is my code:
json-tecnico.php
<?php
require_once('connect.php');
$consulta = "SELECT
idTecnico,
nombre,
apellido,
cedula,
genero,
telefono,
usuario,
correo,
ubicacion,
bio,
rate,
catg.descripcion Categoria_Descripcion,
subcat.descripcion Subcategoria_Descripcion
FROM
tecnico AS tec
INNER JOIN categoria AS catg
ON
tec.categoria = catg.idCategoria
INNER JOIN subcategoria AS subcat
ON
subcat.idCategoria = catg.idCategoria AND subcat.idSubcategoria = tec.subcategoria
WHERE categoria = '".$_GET['categoria']."'";
if(isset($_GET['subcategoria'])){
$consulta = $consulta . " AND subcategoria = '".$_GET['subcategoria']."';";
}
$resultado = mysqli_query($conexion, $consulta);
while($columna = mysqli_fetch_assoc($resultado)){
$data[] = array(
'id' => $columna['idTecnico'],
'nombre' => $columna['nombre'],
'apellido' => $columna['apellido'],
'cedula' => $columna['cedula'],
'genero' => $columna['genero'],
'usuario' => $columna['usuario'],
'ubicacion' => $columna['ubicacion'],
'bio' => $columna['bio'],
'rate' => $columna['rate'],
'subcategoria' => $columna['Subcategoria_Descripcion']
);
}
if(!empty($data)){
echo json_encode($data);
}
else{
$data[] = array(
'success' => 'No se encontro usuarios con el criterio de busqueda dado',
'workers' => false
);
echo json_encode($data);
}
mysqli_close($conexion); ?>
The white screen shows when I put the '007' value on $_GET['subcategoria'] and when I put the line 'bio' => $columna['bio'].
On MySQL, bio is varchar(500). Why is this happening?
A photo of the "tecnico" table on PHPmyAdmin
A:
Well, I already dig into the problem, just was an Encoding error.
Using utf8_encode() on all the String variables solved my problem.
You can use this if you're getting encoding problems:
I got the Answer from here!
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} elseif (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
and after that:
echo json_encode(utf8ize($data));
| {
"pile_set_name": "StackExchange"
} |
Q:
change route in scroll reactjs
I have a question, but I do not even know how to solve it, I'm looking for if I scroll down, show me the following routes and scroll up to show me the previous routes
I hope some guide
class Routes extends Component {
render() {
return (
<Router history={browserHistory}>
<Route path='/' component={HomeLayout}>
<IndexRoute component={HomeComponent} />
</Route>
<Route path='aps' component={AppServiceLayout}>
<IndexRoute />
</Route>
<Route path='portfolio' component={portfolioLayout}>
<IndexRoute />
</Route>
<Route path='about_us' component={aboutUsLayout}>
<IndexRoute />
</Route>
<Route path='*' component={HomeLayout}>
<IndexRoute component={NotFoundComponent} />
</Route>
</Router>
);
}
}
A:
There's an onScroll event that you can use as a trigger, here's a post on how to determine whether they scrolled up or down:
How can I determine the direction of a jQuery scroll event?
And here's a link on how to programatically change the React Route:
Programmatically navigate using react router
So when they scroll, check whether it's up or down, then push the next/previous route accordingly. I dunno if there's anything built in to just get the route immediately before/after a certain route, so you may just need a list of them somewhere as reference
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I validate unique field with struts framework and hibernate?
I am new in struts2 and hibernate. I want to validate mobile no with data base for uniqueness. How can I validate a unique field with struts framework and hibernate?
A:
Add the validation.
You want to validate to no store some field in DB.
// annotations
@NotNull
private Integer someField;
validation api GA in Hibernate validation.
Regards.
| {
"pile_set_name": "StackExchange"
} |
Q:
leaflet javascript - how to clearTimeout a setTimeout on a marker?
I am adding markers like this to my map:
map.addLayer(l), setTimeout(function() {
map.removeLayer(l)
}, 1e4),
which removes after 10 seconds each marker again. Now I would like to achieve that when the user clicks during those 10 seconds on a marker that the market stays visible on the map. So far I have:
l.on('click', function(e) {
console.log(e);
console.log(e.layer._leaflet_id);
console.log(l);
clearTimeout(e.layer._leaflet_id);
});
But it does now work. Any idea how I can achieve this?
A:
You need to cancel the setTimeout by calling the clearTimeout using the relevant ID.
var myVar;
timeout_init();
function timeout_init() {
myVar = setTimeout(function(){
$('.marker').hide();
},5000);
}
$( ".marker" ).click(function() {
clearTimeout(myVar);
});
See example Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I only select images using reddit json?
I am trying to get a list of images from a specific reddit and send them to the user randomly. Is there a way to only get the json that lists a url?
I try to just get to this path down below, but it ends up throwing an error sense it is a nested array
"kind": "Listing",
"data": {
"modhash": "2l53o1urucfcc06e46b02a400997e1d810b258af76c74bce9d",
"dist": 25,
"children": [
{
"kind": "t3",
"data": {
"thumbnail": "https://b.thumbs.redditmedia.com/AihwJOuW0jmGvdJqd71rVCQCA7nJYc4KoyclJttNn_c.jpg",
I want it to return a random image from the huge array. again my attempts threw in error about formatting the parser
every post is in the array of children, I want to access the lot of thumbnails and list them
I get the json from reddit.com/r/pics/top.json
I use request
console.log(parsedData["data"]["children"]...)
I do not know how to get past that to data without throwing an error
A:
parsedData.data.children.forEach(imageUrl => {
console.log(imageUrl.data.thumbnail)
})
| {
"pile_set_name": "StackExchange"
} |
Q:
Select with Contains parameter not working with null
With my select below, if blank string is passed in I get the following error: Null or empty full-text predicate
in my DBAdapter when fetching rows from the database. If I provide a value, such as Well, I do not get results when I should as Well is in the r.[Desc] column. If I pass in Well One, I get: Syntax error near 'one' in the full-text search condition 'Well one'.
If I pass in One, I get nothing.
I've read similar questions here and have not seen a pattern where the value passed in can be nothing, the beginning of the column data, a word in the middle of the column data or more than one word in any order of the column data. I thought Contains returns the row if the column contains the value or part of the value passed in.
What am I doing wrong?
if @Drawing = ''
set @Drawing = null
if @ItemName = ''
set @ItemName = null
if @CF3 = ''
set @CF3 = null
if @Desc = ''
set @Desc = null
if @Design = ''
set @Design = null
if @MaxPSI = 0
set @MaxPSI = null
Select distinct
,r.[DRAWING]
,r.[DESC]
,r.[OP_PSI]
,r.[MAX_PSI]
,r.[MAX_TEMP]
,r.[Insulated]
,r.[DESIGN]
From Ref r
inner join Eng e on e.[DRAWING] = r.[DRAWING]
where r.SurveyNumber = @SurveyNumber
And (rtrim(@Drawing) is NUll or rtrim(r.DRAWING) like rtrim(@Drawing) + '%')
And (rtrim(@Design) is NUll or rtrim(r.DESIGN) like rtrim(@Design) + '%')
And (rtrim(@MaxPSI) is NUll or rtrim(r.MAX_PSI) like rtrim(@MaxPSI) + '%')
And (rtrim(@CF3) is NUll or rtrim(e.CF3) like rtrim(@CF3) + '%')
And (rtrim(@ItemName) is NUll or rtrim(e.ITEM_NAME) like rtrim(@ItemName) + '%')
AND ((@Desc = '""') OR CONTAINS( (r.[Desc]), @Desc))
A:
I think you can try checking for empty as follows:
AND ((@Desc = '""' OR @Desc = '') OR CONTAINS( (r.[Desc]), @Desc))
I suspect the empty predicate may be getting passed as '' instead of "".
Have not used Contains much but from section in the doc [here][1] it seems you either need operators between the words or need to wrap expression in double quotes "". So what you can do is try passing params like this:
AND ((@Desc = '""' OR @Desc = '') OR CONTAINS( (r.[Desc]), '"'+@Desc+'"'))
| {
"pile_set_name": "StackExchange"
} |
Q:
Black Screen with UIViewControllerAnimatedTransitioning
I have created a transition and it is working fine except that I get sometime black corners in the simulator. Additionally in iPad Pro I get a completely black screen if I run the simulator in full resolution. The resized resolutions work fine. Do you have an idea what might be the problem?
Another thing that I recognized is that the content behind the black screen is there and responds to touches. E.g. on a touch I reload the cell of a collectionview. Then this cell is visible while the rest of the collectionview is black.
class ZoomInCircleViewTransition: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
var transitionContext: UIViewControllerContextTransitioning?
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.6
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
guard let toViewController: UIViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else {
return
}
guard let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) else { return
}
guard let fromViewTransitionFromView = fromViewController as? TransitionFromViewProtocol else {
return
}
let imageViewSnapshot = fromViewTransitionFromView.getViewForTransition()
let endFrame = CGRectMake(-CGRectGetWidth(toViewController.view.frame)/2, -CGRectGetHeight(toViewController.view.frame)/2, CGRectGetWidth(toViewController.view.frame)*2, CGRectGetHeight(toViewController.view.frame)*2)
if let containerView = transitionContext.containerView(){
containerView.addSubview(fromViewController.view)
containerView.addSubview(toViewController.view)
containerView.addSubview(imageViewSnapshot)
}
let maskPath = UIBezierPath(ovalInRect: imageViewSnapshot.frame)
let maskLayer = CAShapeLayer()
maskLayer.frame = toViewController.view.frame
maskLayer.path = maskPath.CGPath
toViewController.view.layer.mask = maskLayer
let quadraticEndFrame = CGRect(x: endFrame.origin.x - (endFrame.height - endFrame.width)/2, y: endFrame.origin.y, width: endFrame.height, height: endFrame.height)
let bigCirclePath = UIBezierPath(ovalInRect: quadraticEndFrame)
let pathAnimation = CABasicAnimation(keyPath: "path")
pathAnimation.delegate = self
pathAnimation.fromValue = maskPath.CGPath
pathAnimation.toValue = bigCirclePath
pathAnimation.duration = transitionDuration(transitionContext)
maskLayer.path = bigCirclePath.CGPath
maskLayer.addAnimation(pathAnimation, forKey: "pathAnimation")
let hideImageViewAnimation = {
imageViewSnapshot.alpha = 0.0
}
UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: hideImageViewAnimation) { (completed) -> Void in
}
let scaleImageViewAnimation = {
imageViewSnapshot.frame = quadraticEndFrame
}
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: scaleImageViewAnimation) { (completed) -> Void in
// After the complete animations hav endet
imageViewSnapshot.removeFromSuperview()
}
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if let transitionContext = self.transitionContext {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
// return the animataor when presenting a viewcontroller
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
// return the animator used when dismissing from a viewcontroller
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
}
A:
You need remove mask layer once your are done with custom transition animations.
toViewController.view.layer.mask = nil
Please use this updated code:
class ZoomInCircleViewTransition: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
var transitionContext: UIViewControllerContextTransitioning?
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.6
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
guard let toViewController: UIViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else {
return
}
guard let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) else { return
}
guard let fromViewTransitionFromView = fromViewController as? TransitionFromViewProtocol else {
return
}
let imageViewSnapshot = fromViewTransitionFromView.getViewForTransition()
let endFrame = CGRectMake(-CGRectGetWidth(toViewController.view.frame)/2, -CGRectGetHeight(toViewController.view.frame)/2, CGRectGetWidth(toViewController.view.frame)*2, CGRectGetHeight(toViewController.view.frame)*2)
if let containerView = transitionContext.containerView(){
containerView.addSubview(fromViewController.view)
containerView.addSubview(toViewController.view)
containerView.addSubview(imageViewSnapshot)
}
let maskPath = UIBezierPath(ovalInRect: imageViewSnapshot.frame)
let maskLayer = CAShapeLayer()
maskLayer.frame = toViewController.view.frame
maskLayer.path = maskPath.CGPath
toViewController.view.layer.mask = maskLayer
let quadraticEndFrame = CGRect(x: endFrame.origin.x - (endFrame.height - endFrame.width)/2, y: endFrame.origin.y, width: endFrame.height, height: endFrame.height)
let bigCirclePath = UIBezierPath(ovalInRect: quadraticEndFrame)
let pathAnimation = CABasicAnimation(keyPath: "path")
pathAnimation.delegate = self
pathAnimation.fromValue = maskPath.CGPath
pathAnimation.toValue = bigCirclePath
pathAnimation.duration = transitionDuration(transitionContext)
maskLayer.path = bigCirclePath.CGPath
maskLayer.addAnimation(pathAnimation, forKey: "pathAnimation")
let hideImageViewAnimation = {
imageViewSnapshot.alpha = 0.0
}
UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: hideImageViewAnimation) { (completed) -> Void in
}
let scaleImageViewAnimation = {
imageViewSnapshot.frame = quadraticEndFrame
}
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: scaleImageViewAnimation) { (completed) -> Void in
// After the complete animations hav endet
imageViewSnapshot.removeFromSuperview()
toViewController.view.layer.mask = nil
}
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if let transitionContext = self.transitionContext {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
// return the animataor when presenting a viewcontroller
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
// return the animator used when dismissing from a viewcontroller
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Navigate through form with arrow keys
I have a html form, which is created like a table (with rows and columns). Basically it looks like excel.
And now I would like to navigate just like in excel with the arrow keys. Is that possible?
<table>
<tr>
<td/>
<td/>
</tr>
<tr>
<td/>
<td/>
</tr>
</table>
A:
Yes, it was easy, once I got your tips. This is my solution:
var UP = 38;
var DOWN = 40;
var LEFT = 37;
var RIGHT = 39;
var TAB = 9;
$('#tab-columns').on('keydown', 'input', function (event) {
var $focused = $(':focus');
var id = ($focused.parents("td").attr('id'));
if (id.startsWith("field_")) {
idArr = id.replace("field_", "").split("_");
row = Number(idArr[0]);
col = Number(idArr[1]);
newId = id;
switch (event.which) {
case UP:
newId = "field_"+(row-1)+"_"+col;
break;
case DOWN:
newId = "field_"+(row+1)+"_"+col;
break;
case TAB:
case RIGHT:
newId = "field_"+row+"_"+(col+1);
break;
case LEFT:
newId = "field_"+row+"_"+(col-1);
break;
default:
// nothing
}
$("#"+newId).find("input").focus();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving Cauchy-Schwarz with Arithmetic Geometric mean
I understand common proofs for Cauchy-Schwarz, but not sure about the first step in this one, which is proof 4 from here
Let $A = \sqrt{a_1^2 + a_2^2 + \dots + a_n^2}$ and $B = \sqrt{b_1^2 + b_2^2 + \dots + b_n^2}$. By the arithmetic-geometric means inequality (AGI), we have
$$
\sum_{i=1}^n \frac{a_ib_i}{AB} \leq \sum_{i=1}^n \frac{1}{2} \left( \frac{a_i^2}{A^2} + \frac{b_i^2}{B^2} \right) = 1
$$
so that
$$
\sum_{i=1}^na_ib_i \leq AB \leq \sqrt{\sum_{i=1}^na_i^2} \sqrt{\sum_{i=1}^n b_i^2}
$$
Which is Cauchy-Schwarz. Now this is all quite elegant, but how is the first equation RHS equal to 1? And how is it AGI? Shouldn't it be in this form:
$$
\sqrt[n]{\prod_{i=1}^n x_i} \leq \frac{1}{n} \sum_{i=1}^n x_i
$$
There's probably something simple I'm missing...
A:
First,
$$\sum_{i=1}^{n} \frac{a_i^2}{A^2} = \frac{1}{A^2}\sum_{i=1}^{n} a_i^2 = \frac{A^2}{A^2} = 1.$$
Similar could be said about the second term in the summation.
Second, the proof uses the following two-variable AM-GM inequality: $$xy = \sqrt{x^2 y^2} \le \frac{x^2+y^2}{2}.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
What is a profiler measuring and how is that different from TTFB?
I am using the magento profiler and it gives a reading of how long it took for the PHP code to run, I think.
What I have found that the TTFB - time to first byte value is much higher (sometimes double) than the profiler time.
What else is forming part of the TTFB value?
Here is the profiler time below:
Here is the TTFB for the same request:
A:
The profiler is not including the magento/lib code execution.
You should use a PHP debugger instead of the magento one.
| {
"pile_set_name": "StackExchange"
} |
Q:
Microsoft Access - Using the In Clause in a Query over a Network
So right now, we have a setup where ui.mdb and database.mdb are two separate access files. I am querying the database using the IN clause (ie "SELECT * FROM USERS IN 'DB\example_db.mdb'") and it works great on my local machine. The problem is that people are accessing the file over a public share in the network (ie "\computername\example_ui.mdb"). Once people try to use that query with the IN clause, they get the error:
c:\users\username\documents\db\example_db.mdb is not a valid path. Make sure the path name is spelled correctly and that you are connected to the server on which the file resides.
I did some research and I found this http://support.microsoft.com/kb/167452, but frankly, I don't really understand it. Does anyone have any familiarity with solving this issue?
A:
You should use a full path, not a partial one. If you are 100% sure that everybody in the company has the same mappings, you can use comething like IN "X:\myFOlder\myFile.mdb".
This is using a mapping.
If mapping is not reliable, you can state a full absolute address using UNC (Universal Naming Convention): IN '\\MyServer\myShare\myFolder\myFile.mdb'
| {
"pile_set_name": "StackExchange"
} |
Q:
Android ViewPager ZoomOut animation
I have a ViewPager that look like this:
I need the previews on the sides to ZoomOut when you swipe and only maintain the size of the center view, something like this:
I already tried some examples with ViewPager.PageTransformer() but those examples are always with a fade animation(That I don't need) and not showing previews(Wich I need).
A:
final int paddingPx = 300;
final float MIN_SCALE = 0.8f;
final float MAX_SCALE = 1f;
viewPager.setClipToPadding(false);
viewPager.setPadding(paddingPx, 0, paddingPx, 0);
viewPager.setPageTransformer(false, transformer);
This makes pages smaller than viewpager width:
Here is my Transformer:
PageTransformer transformer = new PageTransformer() {
@Override
public void transformPage(View page, float position) {
float pagerWidthPx = ((ViewPager) page.getParent()).getWidth();
float pageWidthPx = pagerWidthPx - 2 * paddingPx;
float maxVisiblePages = pagerWidthPx / pageWidthPx;
float center = maxVisiblePages / 2f;
float scale;
if (position + 0.5f < center - 0.5f || position > center) {
scale = MIN_SCALE;
} else {
float coef;
if (position + 0.5f < center) {
coef = (position + 1 - center) / 0.5f;
} else {
coef = (center - position) / 0.5f;
}
scale = coef * (MAX_SCALE - MIN_SCALE) + MIN_SCALE;
}
page.setScaleX(scale);
page.setScaleY(scale);
}
};
The difficult thing about this is position parameter of transformPage method. When pages are fill viewpagers width this param changes from 0 to 1. But when pages are smaller this param is tricky.
position is value of left side of the view. Page width equals to 1. position equals to 0 when pages left side is on the left side of viewpager. So position can be more than 1, depends on page width.
First you need to find viewpagers center (relatively to position parameter). Then scale down page if page moves to left or to rigth from center. In my implementation I scale down view on half page distance from center.
Here is result:
Page width can be controlled via padding.
Extra margin between pages can be added throught viewPager.setPageMargin(value) method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Could the Russian fleet go via northern route to Port Arthur instead of via Cape of Good Hope?
Was there a route via the north of Russia that Admiral Rozhestvensky could have passed (maybe during the summer months) instead of the seven month odyssey of going through Cape of Good Hope around Africa and then through Indian Ocean and South China Sea to reach Vladivostok and eventually Port Arthur.
A:
Absolutely no. The first time when the North-East passage was made in one navigation (that is in less that one year) was in 1932 using icebreakers.
And this was just an experimental expedition. In 1905 Russia had no enough icebreakers of sufficient power, not even mentioning other difficulties, like coaling stations on the way.
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple neural network "calibration" (python)
I'm getting started with neural networks and this kind of stuff, I understood how a perceptron works and the logic behind feed-forward and backpropagation mechanisms and I am now trying to write a simple multi-layer network with 3 neurons (2 in a hidden layer and 1 as output) which should be enough to execute a xor operation.
I implemented it in Python (using v3.6.1 now) this way:
import numpy as np
class Neuron():
def __init__(self, n, w = None, b = None):
#np.random.seed(46144492)
#np.random.seed(23)
self.weights = 2 * np.random.random((n)) - 1 if w == None else np.array(w)
self.bias = 2 * np.random.random() - 1 if b == None else b
self.learning_rate = 0.1
self.weights_error = []
for i in range(n):
self.weights_error.append(0)
self.bias_error = 0
def learning_factor(self, output):
return output * (1 - output)
def fire(self, x):
return 1 / (1 + np.exp(-x))
def __call__(self, inputs):
weighted = []
for i in range(len(inputs)):
weighted.append(inputs[i] * self.weights[i])
weighted = np.array(weighted)
return self.fire(weighted.sum() + self.bias)
def adjust(self, n_weights):
for i in range(n_weights):
self.weights[i] -= self.weights_error[i]
self.bias -= self.bias_error
class HiddenNeuron(Neuron):
def calc_error(self, inputs, output, next_layer, number_in_layer):
error = 0
for n in range(len(next_layer)):
error += next_layer[n].delta * next_layer[n].weights[number_in_layer - 1]
derivative = self.learning_factor(output)
self.delta = error * derivative
self.weights_error = []
for i in range(len(inputs)):
self.weights_error.append(self.delta * inputs[i] * self.learning_rate)
self.bias_error = self.delta * self.learning_rate
class OutputNeuron(Neuron):
def calc_error(self, inputs, output, expected):
error = output - expected
derivative = self.learning_factor(output)
self.delta = error * derivative
self.weights_error = []
for i in range(len(inputs)):
self.weights_error.append(self.delta * inputs[i] * self.learning_rate)
self.bias_error = self.delta * self.learning_rate
# Network
n1, n2 = HiddenNeuron(2), HiddenNeuron(2)
n3 = OutputNeuron(2)
# Training data
training_set_in = [[0, 0], [0, 1], [1, 0], [1, 1]]
training_set_out = [0, 1, 1, 0]
# Training cycles
for i in range(10000):
for i in range(len(training_set_in)):
# Feed-forward
n1_out = n1(training_set_in[i])
n2_out = n2(training_set_in[i])
n3_in = [n1_out, n2_out]
n3_out = n3(n3_in)
# Backpropagation
n3.calc_error(n3_in, n3_out, training_set_out[i])
n2.calc_error(training_set_in[i], n2_out, [n3], 2)
n1.calc_error(training_set_in[i], n1_out, [n3], 1)
n1.adjust(2)
n2.adjust(2)
n3.adjust(2)
# "New" cases (test)
for new in [[0, 0], [0, 1], [1, 0], [1, 1]]:
print(n3([n1(new), n2(new)]))
As you can see I use the sigmoid function as activation function and I haven't implemented the momentum yet (I have still to get how it works).
The network works, in most cases. But I found some cases in which it outputs some strange values (see for example the two random seeds I commented in the Neuron class constructor). This two cases are solved if I increase the Neuron.learning_rate (for example set it to 10), but still some other exceptions come up (couldn't find seeds for these, I'm sorry... But they're quire frequent, just run the code for 10 or 20 times and you'll see some).
The question is: Why is this happening? Is my network too "small"/simple? I thought 3 neurons would be enough. Or is it just a problem of "calibration" (don't know how this is called, I mean the process of adjusting the learning rate factor and the momentum, which here is absent)? Or did I even commit any mistakes? I can't really figure out.
EDIT: I'm training the net with all possible cases and then trying it with the same cases just to verify if it works correctly.
A:
I think it's OK as neural network's performance depends on its initial state, that is, the weights and biases. In your case, the weights and biases start out randomised, and thus depend on the seed. There are even special techniques1 to reduce this effect, such as weight normalisation (also google this, there are some interesting papers on this topic).
link taken from http://neuralnetworksanddeeplearning.com/chap5.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Sprite-Kit: Two different gravity vectors in one scene?
I'd like to have two objects in one scene, one which is pulled downwards, and one which is pulled upwards, but I can only specify one gravity vector which is applied to all objects in the physics world.
If there is no way to do this with gravity, how do I best go about it without it?
A:
All right, so I ended up doing what rickster proposed: regularly applying a constant vector to my objects.
var pullDown = SKAction.runBlock({self.pullBirdDown()})
var pullUp = SKAction.runBlock({self.pullBirdUp()})
var wait = SKAction.waitForDuration(0.01)
bird1.runAction(SKAction.repeatActionForever(SKAction.sequence([pullDown, wait])))
bird2.runAction(SKAction.repeatActionForever(SKAction.sequence([pullUp, wait])))
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I add css to a line like document.write(text[0]);
I've already tried this:
document.write(<div class="line01"> + text[0] + </div>);
A:
That looks ok as far as the CSS goes, but the elements to output should be in a string:
Change this:
document.write(<div class="line01"> + text[0] + </div>);
To this:
document.write('<div class="line01">' + text[0] + '</div>');
More on document.write can be found here
| {
"pile_set_name": "StackExchange"
} |
Q:
Suitability of Mathematica as platform for engineering calculations and programs
I am considering using Mathematica with Wolfram Workbench as a standard platform for calculations and programs in a large engineering department. I am looking for a solution that would provide better validation, documentation and revision control than Excel spreadsheets with VisualBasic macros. Additional benefits would be to use built-in functionality to reduce development effort and to allow engineers to use code interactively instead of in a black-box mode.
I have used Mathematica and WebMathematica for individual projects in the past, and am familiar with the various customer examples that Wolfram advertises. However, I don't have experience or examples of using Mathematica across a large engineering department.
I expect that we would develop packages for various back end functionality (likely on the order of 20,000+ lines of code), and users would access it either directly in the notebook, through CDF applications or through WebMathematica depending on the application.
Is Mathematica suitable for this type of use? Can average users learn Mathematica without too much trouble and become productive quickly? Is there a better solution you would suggest evaluating?
A:
I'm late and most of what I'll write has in one or another form already been said in some of the comments. Nontheless I can't resist to provide an answer. I might add that I'm working for a german based engineering service provider (SmartCAE) and we are using Mathematica as one of our main tools for almost 15 years, so we do have some experience in the field.
Here are the answers to your specific questions from my point of view:
From a pure technical point of view, Mathematica would definitely be suitable, and much more so than Excel.
Learning Mathematica can very well be seen as a lifetime's task. On the other hand I think it's possible to get ready to solve typical engineering tasks within a day, depending a lot on prior knowledge about mathematics and other tools or programming languages. But Mathematica is quite different than many other systems/languages, so at some point many people start to struggle. It needs a "positive attitude" to get past that point, and only after that one will reach the full productivity that it can provide. I would expect only a fraction of the engineers in a large departement to reach that point, everyone else will learn enough to get their jobs done but probably not enough to recognize/appreciate the added power that Mathematica could provide.
Considering engineering applications, I think there are alternatives, but I think they either do suffer from roughly the same weaknesses as Mathematica or are very (too) limited to what they were made for, which might or might not be a problem for your departement. Some of them might be more well known among engineers and thus have a lower acceptance threshold. From the pure technical point of view I'd consider Mathematica to be a good choice when compared to the alternatives.
For engineering applications both Mathematica and Excel do only provide a relatively low level platform, so you will probably need some additional tools to make your engineers productive. This could be a (or some) DSL as Leonid suggests, but maybe also just some other tools which will help the engineers to do their job without necessarily become software engineers and Mathematica experts. We have developed such tools for our internal usage, and without them would have a hard time to provide our services within the given cost limits. Actually I'd consider it necessary to provide such additional tools for Excel as well, but there some knowledge is implicitly expected from everyone working with a computer and people will happily (?) use and accept it as it is. That might be unfair but is a fact that simply can't be overseen.
That said, I think whether Mathematica can successfully be introduced in a larger departement which uses Excel at the moment is not so much a question of technical suitability. I'd rather see it as a "social task": Such a transition will force everyone to learn new things and will make experienced personell feel like beginners. Only if you can convince the key users ("tool providers") and a majority of the engineers that such a transition makes sense you can expect them to take that hurdle. If only some users with influence will not be convinced, I would expect such a transition to fail. As every software tool Mathematica has weak spots and oddities: these are usually easy to overcome and none of them does actually make Mathematica useless or very hard to use, but it's easy enough to make it look like that would be the case. Unfortunately it doesn't help that you can find such cases for the exisiting tools like Excel just as well, you can't expect people to make fair comparisons in such situations. So I think you'd really need to make sure that you have the support of users and the management. To gain that, you'll probably need to:
Ensure that everyone agrees that there is a problem with using Excel, maybe listing
everything that can't be done with it or has gone wrong in the past.
Persuade that Mathematica will solve those problems without introducing new ones.
Comparison with alternatives
Have ready a plan how the transition could be done
Have ready an estimation on what this will cost and what it might save/add in the future.
Especially the latter will need to be realistic, you'll most probably be cited on that. Costs will of course include training, licenses, expenses for rewriting existing tools, additional IT administration, etc.
A set of real world examples will help a lot, unfortunately many of the examples you'll find on WRI's pages are rather showing the principles, but don't really qualify as "real world" (IMHO). In many cases that's just because they avoid the "simple" things like importing and exporting data, providing numbers with units etc., in other cases they just don't provide all the parameters as inputs that you'd need to run real world examples. So you'd probably need to provide some examples yourself.
All in all that might be a big project. On the other hand, and that has also been mentioned in the comments, you could just as well try to introduce Mathematica as a tool in a less official way by just starting to provide useful stuff written with it. If you manage these tools to run in the CDF-Player, you could even give them away to your colleagues without causing additional costs. I think many "modern" tools have been introduced in such an "informal" way in large companies (I know some examples from german automotive companies, but unfortunately that hasn't happened to Mathematica in a larger scale (yet?)).
Of course that's only possible if your employer allows it.
A:
First comes a disclaimer that I don't have experience in introducing Mathematica to a large department, so you can take all I say with a grain of salt. That out of the way,
I think, the answer depends on the level of preparation and willingness to learn new things of the average user in your department, but, given that you anyway plan to deploy a rather large code base, I would recommend to create a framework or DSL on top of Mathematica, which would isolate the average user from the full complexity of Mathematica.
If you make a DSL, you can as well code it in Mathematica, and make it strongly typed. This assumes a separation between users and developers of such custom language. Once the users request some new feature, it is implemented in the language and made available to them. After a while, they may get used to the DSL and overall Mathematica workflow enough to be able to use parts of Mathematica directly.
As to learning and using Mathematica directly, this is also possible IMO, but your company will probably have to allocate a lot of resources, either sending the employees to WRI courses, or creating some in-house training courses. This will also probably require a really high motivation from the average user. I've heard many statements of how easy it is to learn Mathematica. Sadly, I only find this partly true - there are many subtleties, from which a beginner is not isolated and which can take a while to digest. I think it also depends on how "far" are the majority of tasks from what is already available in Mathematica.
So, to summarize: my opinion is that Mathematica definitely has a potential to cut your costs and save your department lots of time, but you will either have to make an effective learning system at your department, or implement some framework or language which would, at least during the initial stage of adoption, shield the new users from the complexity of the full Mathematica language. My two cents.
A:
I can’t speak directly about introducing Mathematica into engineering firms, but on the basis that many economists are wannabe engineers who couldn’t handle the maths, perhaps my observations will have some relevance. In my field, Mathematica is definitely a minority taste; Excel, eViews and Matlab dominate for different tasks.
Mathematica is not a data storage solution, whereas Excel is often used as one. Ideally, you should consider you data management strategy in conjunction with your choice of tools. People will be more comfortable adopting Mathematica if they are comfortable with where the end results are stored. You might need to write some convenience functions to get data in and out of databases or spreadsheets. If you use spreadsheets to store data (and I’m guessing that you do given the workflows you describe), you will need to specify some protocols on how those spreadsheets are set up. That way you will be able to automate some of those data access tasks more easily and robustly.
Different groups within the organisation will have different levels of sophistication and therefore need different tools. The Mathematica family of products is ideal for accommodating this: the maintainer of the custom functions and packages would do so using Wolfram Workbench; mainstream and sophisticated end-users would use vanilla Mathematica with the custom functions installed; management and less-sophisticated users can interact with CDF reports and applications in Player or Player Pro.
I endorse Leonid’s recommendation to create a Domain-Specific Language on top of Mathematica. I have even seen this done for APL (in another organisation, not where I currently work), so it can definitely be done for Mathematica. If you have someone who can maintain the underlying packages, and they are allowed to take the time to do so, then this can work fine. If the packages are in the Autoload directory, users don’t even need to be aware that they are using an add-on.
At the risk of offending Infix and Postfix fans, in my experience, new users often find the “normal” syntax of function[arguments] to be more accessible; Map (/@) and Apply (@@) are usually the next bit of syntax they learn to handle. It will therefore help to design the user-facing functionality to use a more limited syntax, and hide things requiring replacement rules, Thread, Fold etc away behind custom functions. We used a simplified Mathematica syntax in the web front end for a database application, to define calculations. People actually warm to the idea that [] is for functions, {} is for lists, and () is for grouping.
You will need to provide training, especially for any users who have experience with Matlab, Fortran or any other language that encourages loop-itis.
You will also need to provide good documentation of any of the custom functions you create, but fortunately Mathematica allows that documentation to be integrated in the normal help in a relatively seamless way.
To encourage users to adopt the functionality, I would suggest leveraging Mathematica’s visualisation capabilities, including Manipulate. If you can create a “cool” Manipulate in a CDF that the management can use and need to look at (e.g. a key model or management report), you will get buy-in from the top - and that can be half the battle.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use QUdpSockets wo polling or custom classes in Qt?
Here is a short UDP server example in Qt below which does work but what I don't like is that I'm polling to see if new data is available. I've come across some examples of a readyRead() but they all seem to introduce a qt class. Do I need to use a qt class in order to take advantage of the readyRead() signal?
Here is the working but simple UDP server implemented entirely in main:
#include <QDebug>
#include <QUdpSocket>
#include <QThread>
int main(int argc, char *argv[])
{
QUdpSocket *socket = new QUdpSocket();
u_int16_t port = 7777;
bool bindSuccess = socket->bind(QHostAddress::AnyIPv4, port);
if (!bindSuccess) {
qDebug() << "Error binding to port " << port << " on local IPs";
return a.exec();
}
qDebug() << "Started UDP Server on " << port << endl;
QHostAddress sender;
while (true) {
while (socket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(),datagram.size(),&sender,&port);
qDebug() << "Message From :: " << sender.toString();
qDebug() << "Port From :: "<< port;
qDebug() << "Message :: " << datagram.data();
}
QThread::msleep(20);
}
return 0;
}
Here is an example of the readyRead() signal:
https://www.bogotobogo.com/Qt/Qt5_QUdpSocket.php
I haven't really figured out how to get this to work yet. I must be doing something wrong. Here is the UDP connection code i'm trying:
#include "myudp.h"
MyUDP::MyUDP(QObject *parent) : QObject(parent) {
}
void MyUDP::initSocket(u_int16_t p) {
port = p;
udpSocket = new QUdpSocket(this);
bool bindSuccess = udpSocket->bind(QHostAddress::LocalHost, port);
if (!bindSuccess) {
qDebug() << "Error binding to port " << port << " on local IPs";
return;
}
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}
void MyUDP::readPendingDatagrams() {
QHostAddress sender;
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &port);
qDebug() << "Message From :: " << sender.toString();
qDebug() << "Port From :: " << port;
qDebug() << "Message :: " << datagram.data();
}
}
myudp.h
#include <QObject>
#include <QUdpSocket>
class MyUDP : public QObject
{
Q_OBJECT
public:
explicit MyUDP(QObject *parent);
void initSocket(u_int16_t p);
u_int16_t port;
QUdpSocket *udpSocket;
signals:
public slots:
void readPendingDatagrams();
};
new main.cpp
int main(int argc, char *argv[])
{
MyUDP *myUDP = new MyUDP(0);
myUDP->initSocket(port);
while (true) {
usleep(1000);
}
return 0;
}
I am testing with:
netcat 127.0.0.1 -u 7777
{"cid"="0x1234123412341", "fill_level"=3245 }<cr>
A:
What you're doing wrong is that you're not letting Qt's event loop run. i.e. this is incorrect:
int main(int argc, char *argv[])
{
MyUDP *myUDP = new MyUDP(0);
myUDP->initSocket(port);
while (true) {
usleep(1000);
}
return 0;
}
... instead, you should have something like this:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// connect needs to occur after QCoreApplication declaration
MyUDP *myUDP = new MyUDP(0);
myUDP->initSocket(port);
return app.exec();
}
... it is inside the app.exec() call where a Qt application spends most of its time (app.exec() won't return until Qt wants to quit), and there is where Qt will handle your UDP socket's I/O and signaling needs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Storing a web project (in my case joomla) on SVN - how to do this properly
I have made a joomla component that I want to put on SVN. The problem is that Joomla components have bits and pieces scattered all over the place. What is the best way to handle this with SVN considering I still want to be able to version the application, without including all the core joomla code website code?
UPDATE
I ended up using symlinks in Window 7 like Linux has
http://www.howtogeek.com/howto/windows-vista/using-symlinks-in-windows-vista/
And a nice utility for making linking really easy
http://schinagl.priv.at/nt/hardlinkshellext/hardlinkshellext.html
You can have the project exactly as you would have it in the installer and link the directories and language files to their respective place in the Joomla hierarchy. This also allows you to have multiple Joomla version installed and using a single repository your can test them all! Works great :)
A:
This is how I organise my component files within my svn. Assume that my component name is comname.
repository/components/comname/trunk/
comname
comname_admin
com_comname.xml
com_comname-1.0.zip
license.txt
comname_userguide.doc
comname_userguide.pdf
All your front end code should be in comname folder while all your admin code should be in comname_admin. This is the standard way in which to layout a Joomla component structure.
You can then tag your versions and keep them in repository/components/comname/tags/1.0 for example.
Hope that helps. Cheers
| {
"pile_set_name": "StackExchange"
} |
Q:
How To Implement Responsive Grid Ui in Bootstrap 3
I am facing problem during creating following UI:
How can I implement this kind of design?
A:
Since Bootstrap 3 is "mobile-first", start with your desired layout for the smallest device ("screen 4") using the xs classes, and then go up from there.
Here is an example to get you started: http://bootply.com/129266
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is the external JavaScript file not responding to AngularJS?
This angularJS file does not display the value of the expression as" Full Name: John Doe"; instead it displays "Full Name: {{firstName + " " + lastName}}". What might I have missed?
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div ng-app="" ng-controller="personController">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script src="C:\Users\Vincent\Documents\Python\angularjs\StraightAngularJS\personController.js"></script>
</body>
</html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div ng-app="" ng-controller="personController">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script src="personController.js"></script>
</body>
</html>
End of AngularJS file
Below is its external javaScript file: personController.js
function personController($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe",
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
}
}
A:
This is likely because you're including your script tag to the app <script src="personController.js"></script> outside of the scope of the div containing your ng-app.
As shown in this JSfiddle, the code does work correctly, so there's nothing else wrong.
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Datomic Pro bin/run no suitable driver found
I'm trying to run Datomic Pro with the following command:
./bin/run -m datomic.peer-server -h localhost -p 8998 -a myaccesskey,mysecret -d demo,"datomic:sql://jdbc:mysql://localhost:3306/datomic?user=datomic&password=datomic"
But every time I run that command it throws:
Exception in thread "main" java.sql.SQLException: No suitable driver
Any thoughts?
ps: I've already added mysql connector jar to ./lib.
A:
Gabriel,
You need to provide a database name to the peer-server command. You'll want to start a datomic peer against your running transactor and create the database first. For this example I created the "test" db.
(require '[datomic.api :as d])
(def uri "datomic:sql://test?jdbc:mysql://localhost:3306/datomic?user=datomic&password=datomic")
(d/create-database uri)
That create DB should return true. Once created your URI string will look like:
./bin/run -m datomic.peer-server -h localhost -p 8998 -a myaccesskey,mysecret -d demo,"datomic:sql://test?jdbc:mysql://localhost:3306/datomic?user=datomic&password=datomic"
Cheers,
Jaret
| {
"pile_set_name": "StackExchange"
} |
Q:
Fadeout validation error messages in WooCommerce checkout page
When placing an order, WooCommerce does validate all required user fields inputs. If not, the checkout-errors messages appear like if the first name is missing and so on.
I want those error validation messages to fade out after a given time.
So, I injected this jQuery code:
(function($) {
var wooError = $('.woocommerce-error');
wooError.delay(4000).fadeOut(160);
})
(jQuery);
As long the .woocommerce-error class is not within form.checkout, it works fine, like on login or register for example. But it does not work on checkout page.
The class .woocommerce-error is correct (it's there), but the fadeOut isn't triggered.
So, I went on searching the web. Found an other approach, to wait for checkout_error checkout page event, like so:
$( document.body ).on( 'checkout_error', function(){
var wooError = $('.woocommerce-error');
wooError.delay(4000).fadeOut(160);
})
(jQuery);
But it doesn't work.
Can someone tell me, why I can not trigger the .woocommerce-error class to fadeout as long it's inside the checkout form?
How to trigger the fadeOut on checkout error validation messages?
A:
Try the following code using setTimeout() instead of delay(), that will fade out any error message on checkout page with a delay of 4 seconds and a duration of 160 mili-seconds:
// Checkout JS
add_action( 'wp_footer', 'checkout_fadeout_error_message');
function checkout_fadeout_error_message() {
// Only on front-end and checkout page
if( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script>
jQuery(function($){
$(document.body).on( 'checkout_error', function(){
var wooError = $('.woocommerce-error');
setTimeout(function(){
wooError.fadeOut(160);
}, 4000);
})
});
</script>
<?php
endif;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
| {
"pile_set_name": "StackExchange"
} |
Q:
pass event and object to function in react
I'm new to react trying to implement Redux I'm trying to update state when a text-input gets updated. I'm able to extract the e.target.value but it also needs to be aware of what object was changed
For example my data might be something like:
{ name: 'Penny', namePlural: 'Pennies', label: '1¢', value: .01, sum: 0 },
{ name: 'Nickel', namePlural: 'Nickels', label: '5¢', value: .05, sum: 0 },
{ name: 'Dime', namePlural: 'Dimes', label: '10¢', value: .10, sum: 0 },
{ name: 'Quarter', namePlural: 'Quarters', label: '25¢', value: .25, sum: 0 }
I need to update the sum for a particular denomination.
Here is what I have for my presentation component
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class DenomInput extends Component {
constructor(props) {
super(props);
this.state = {
denom: props.denom
}
}
handleKeyUp = (e) => {
this.props.onDenomChange(e.target.value);
}
render() {
return (
<div className="input-group denom">
<span className="input-group-addon">{this.state.denom.label}</span>
<input
type="text"
className="form-control"
onChange={this.handleKeyUp}
value={this.state.denom.sum} />
<span className="input-group-addon">{this.state.denom.count | 0}</span>
</div>
);
}
}
DenomInput.PropTypes = {
denom: PropTypes.object.isRequired
}
export default DenomInput;
With this I'm able to get the value of the input field, but how could I pass up which denomination I'm currently on as well?
A:
Mayank's comment is correct, you can modify your props.onDenomChange function to accept a denom as the second argument. But in order for your handleKeyUp function to access component state, you'll need to explicitly bind the handler. So your input JSX should look like this:
<input
type="text"
className="form-control"
onChange={this.handleKeyUp.bind(this)}
value={this.state.denom.sum} />
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I return to previous areas in Hidden Folks?
I accidentally advanced to the next level in Hidden Folks before finding every target in the area.
How can I return to previous areas to find people I missed?
A:
You can return to any level from the main menu.
On the bottom bar, scroll all the way to the left, open the Options menu, then select Menu.
| {
"pile_set_name": "StackExchange"
} |
Q:
.NET: When are large heap objects garbage collected?
I have a program that requests HTML from a webservice, modifies the HTML to highlight search terms and then displays the HTML in a WebBrowser component. Sometimes the HTML I receive will be quite large causing my "Mem Usage" and "VM Size", as displayed in task manager, to blow up to ~600 Meg. If I do not perform any other operation it seems my app will consume these memory resources indefinitely. If I do a forced GC I can get these resources released but am loathe to do that since I don't really understand why the framework isn't releasing the resources when they are no longer referenced.
I have two questions:
Are "Mem Usage" and "VM Size" dependable metrics for what my program is consuming?
If there are multiple .Net apps running on the same machine will the memory needs of one .Net app cause .Net to free resources from the other .Net applications?
Thanks in advance.
A:
The garbage collector is a heavy operation so it gets done only when the system decides it's necessary (ie there's a memory pressure). The fact that 600MB are "blown up" has no impact as long as the system does not need them for something else.
A:
In addition to coffee_machine' answer: The Large Object Heap is only collected when a full collection is performed. This only happens if the system absolutely needs the resources for something else.
About your seconds question: Of course, if one .NET program needs memory and the runtime request that memory from the operating system, there is memory pressure just like a native program would have requested the memory and the .NET runtime will perform a garbage collection.
| {
"pile_set_name": "StackExchange"
} |
Q:
.Net 2.0 List Issue
Getting an error, hopefully that can be fixed.
I have a Strongly typed list (or at least I am attempting to use one rather...) It only contains 2 properties... NodeName (string), NodeValue(string)
The error I am getting is when trying to add to said list:
_Results.Add(New Calculator01.ResultTyping() With {.NodeName = "Number_Departures_Per_Day", .NodeValue = DC_NDPD.ToString()})
Is producing the following error:
error BC32017: Comma, ')', or a valid expression continuation expected.
Yes, this is an inherited .Net 2.0 website, and no, I cannot upgrade it to a newer version. (I asked the boss already)
I am open to using a different generic collection though, so long as I can strongly type it...
A:
Object Initializers were introduced with Visual Studio 2008 so they were simply not available in .NET 2.
But you can use this syntax:
Dim calculator As New Calculator01()
calculator.NodeName = "Number_Departures_Per_Day"
calculator.NodeValue = DC_NDPD.ToString()
_Results.Add(calculator)
If you want one line you should provide an appropriate constructor which is a good thing in general:
Class Calculator01
Public Sub New(NodeName As String, NodeValue As String)
Me.NodeName = NodeName
Me.NodeValue = NodeValue
End Sub
Public Property NodeName As String
Public Property NodeValue As String
End Class
Now you can use this code:
_Results.Add(new Calculator01("Number_Departures_Per_Day", DC_NDPD.ToString()))
| {
"pile_set_name": "StackExchange"
} |
Q:
Задание ссылки в customizer.php для WP темы
Пытаюсь в настройках WP темы вывести сслыку для кнопки.
В customizer.php создаю секцию и параметры:
// Button Text & Link
$wp_customize->add_section( 'button-custom' , array(
'title' => esc_html__( 'Button', 'my_cat' ),
'priority' => 20,
'description' => esc_html__( 'Customize your button', 'my_cat' ),
'panel' => 'section-custom'
));
// Button Href
$wp_customize->add_setting( 'my_cat_button-href', array(
'capability' => 'edit_theme_options',
'sanitize_callback' => 'themeslug_sanitize_url',
));
$wp_customize->add_control( 'my_cat_button-href', array(
'type' => 'url',
'label' => esc_html__( 'Button Href', 'my_cat'),
'section' => 'button-custom',
'settings' => 'my_cat_button-href',
'input_attrs' => array(
'placeholder' => __( 'http://' )
)
));
А в контенте index.php вывод результата:
<a href=" <?php echo wp_kses_post(get_theme_mod( 'my_cat_button-href' )) ?> " class="btn btn-default">Button Text </a>
Пишу адрес для ссылки типа: https://google.com. Выдает - Неверное значение. И не сохраняется.
Вопрос: как правильно задать редактирование (из админки) ссылки (href="") для кнопки в WP теме в customizer.php? Есть ли возможность задать поле для выбора ссылки из существующих в теме, подобно как для меню (т.е. задать например ссылку на страницу поста\статьи)?
A:
У вас, видимо, не опредена callback-функция themeslug_sanitize_url().
Чтобы дать выбор из списка страниц, следует использовать choices с type => radio или type => select. Пример:
$wp_customize->add_control(
new WP_Customize_Control(
$wp_customize,
'your_setting_id',
array(
'label' => __( 'Dark or light theme version?', 'theme_name' ),
'section' => 'your_section_id',
'settings' => 'your_setting_id',
'type' => 'radio',
'choices' => array(
'dark' => __( 'Dark' ),
'light' => __( 'Light' ),
),
)
)
);
Подробнее в Codex.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to pass variable from one function to another function in php
This is what I'm tying to do.
(When I refer to state and city. I literally mean US states and cities, New York, Texas etc...)
In order for me to display similar dealers on every dealership page I'm going to have to use the state and city variables. In my original function I'm passing the city variable but not the state variable. I've extracted the state variable via a function I've made (syntax below) but this is where I'm running into trouble.
When I extract the state I'm attempting to convert it as a variable but it's not working (syntax below). My question is, how would I convert what I'm extracting (the state) to a variable?
In the below function I'm getting the state from the id that I'm passing.
function get_state_from_the_id($id)
{
$this->db->select('state');
$this->db->where('id',$id);
$result = $this->db->get('dealers');
if ($result->num_rows() > 0){
return FALSE;
} else {
return TRUE;
}
}
This is where I'm running into trouble
$state = $this->Dealer_data->get_state_from_the_id($id); // gets the state
In the above line of code I'm attempting to extract the state as a variable from my function but it's not working. My objective is to extract the state (IE, new york, texas, california etc...) and insert that variable into another function I made. What am I doing wrong? How can I correct my mistakes?
Thanks
A:
You have to return the $result:
if ($result->num_rows() > 0){
return $result;
} else {
return FALSE;
}
A:
This is my practice to provide your reference
Model
function get_state_from_the_id($id) {
$query = $this->db->get_where('dealers', array('id' => $id));
return $query->num_rows();
}
Contoller
$state = ($this->Dealer_data->get_state_from_the_id($id) > 0) ? FALSE : TRUE;
| {
"pile_set_name": "StackExchange"
} |
Q:
apply multiple selected true to option jquery
<select id="testd" name="testd[]" multiple="" style="min-height: 100px;">
<option value="16">test1</option>
<option value="21">test2</option>
<option value="27">test3</option>
<option value="24">test4</option>
</select>
how to apply seleted true to multiple option ,
example 16,24 , want to apply seleted true to option
i tried
var optionsToSelect = ['16,24'];
var select = document.getElementById( 'testd' );
for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
o = select.options[i];
console.log(o);
if ( optionsToSelect.indexOf( o.value ) != -1 )
{
o.selected = true;
}
}
not working perfectly , it will selects all the four options
A:
Change
var optionsToSelect = ['16,24'];
to
var optionsToSelect = ['16','24'];
This is how to define an array of strings. Else your code works fine.
Working Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
GWT RequestFactory - Using a new setter on a proxy object causes IllegalArgumentException
I have a request factory proxy object and the "old" setter methods I can use without a problem. Now I added a new field and a setter for that field (on the backend object). I also defined the method in my proxy object.
But if I call the setter for the new field on the frontend, I get an IllegalArgumentException. I use GWT + Maven. Do I need to clear some kind of cache or some old objects, so the compiler knows about the new field? I tried maven clean, eclipse clean but nochting helped.
My proxy interface looks like this:
@ProxyFor(value = User2.class, locator = EntityLocator.class)
public interface User2Proxy extends EntityProxy{
void setPassword(String password);
}
The backend object looks like that:
public class User2 implements Serializable {
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And I create the proxy object like this:
User2Proxy user = userRequest.create(User2Proxy.class);
user.setPassword("abc")
So the input can not be wrong with a string like "abc"
A:
I found the problem: I need in the proxy object not only the setter-method but also the getter. If that method is provided, it works!
| {
"pile_set_name": "StackExchange"
} |
Q:
Varistor S10K30 for 24-40VDC input?
I was put in charge of redesigning a motor control circuit which accepts 24-40V DC on its input.
As a side note: As far as i know, the existing circuit has been working fine for several years. The redesign aims to make the production cheaper and replace all obsolete THT parts with SMD and optimizing some other stuff.
The current circuit is protected by a 3A fuse and a varistor of type S10K30. Looking at the datasheet (see below), the "30" obviously refers to the \$ V_{RMS} \$ rating.
What bothers me is, that \$ V_{dc} \$ is 38V. I would've chosen the next lager type with a continuous DC voltage rating of at least >40V (more like 44V for +/-10% supply tolerance).
I am trying to understand if this varistor type was a poor choice by the engineer, or if I am missing something (I never had to choose a varistor before).
The data-sheet further specifies \$ V_v=47V \$, but I am not sure how to interpret this parameter.
What does the (1 mA) exactly mean? Does the varistor sink about 1 mA @ 47V? Is this the reason why the original developer was fine with this particular type, because he did not care if the varistor permanently consumes
$$ P = 47V * 1mA = 0,047W $$
Is this bad practice or somehow justified?
How to properly choose the correct varistor for this application?
A:
The data sheets are telling you this: -
The device will conduct 1mA somewhere between 47-10% and 47+10% at 25ºC
At 5A the voltage across the device will be no more than 93V (this is a pulse test)
The max impulse current (based on 8/20us pulse) is 500A at 85ºC
At 85ºC ambient watch out because the operating voltage level drops to 38Vdc
You also need to look at the VI curve for this device: -
The above will tell you what to expect for two conditions. The left hand area marked A is for quiescent conditions (leakage current) and at 40Vdc there may be a current of about 500uA flowing. This is OK for the design unless you are operating super low power. The right hand area is the protection side of the graph - note how the device has a staggered curve where left and right cross-over. This is giving you the 93V max at 5A figure and you can use the curve to predict what the worst case terminal voltage will be clamped at (say) for 1A. To me this looks like 82V.
My conclusion is that it is OK for a 40V supply unless you are operating at a high ambient temperature - this could give a clue about where/how you should mount the device on the PCB - If the PCB is vertical, maybe it's at a low part of the board where temperatures are bound to be lower. Maybe it's near to a fan. You need to make these decisions.
| {
"pile_set_name": "StackExchange"
} |
Q:
2018 Federal Income Tax Deduction for Owner Occupied Rental Property
I live in a 3 bedroom condo in California and decided to rent out 2 of the bedrooms and live in one.
The mortgage is $1M and interest is $4000 per month
HOA is $600 per month
Property tax is $1000 per month
Rental income is $3000 per month
I know HOA, mortgage interest and property tax can all be used to deduct rental income. But in my case, the rental income is less than all those combined. Also, there is a $750,000 limit for mortgage interest deduction for owner occupied house according to the new tax law.
My question is, when I file tax for 2018, how much can I write off my income?
A:
Assuming you were under contract on the house prior to December 16, 2017 and closed prior to April 1, 2018, you are grandfathered in to the $1M limit, so no impact to you unless you're married filing separately.
Since you live there, you cannot claim rental losses (even if you didn't live there, likely no benefit due to AGI, unless you're a real estate professional). You will offset rental income by a percentage of the expenses you listed in addition to depreciation of the rented portion and other expenses like maintenance/repairs. The percentage used is based on how much of the unit is rented. Count 2/3 of any common rooms as rented, and all of any rooms exclusive to tenants as rented. It's acceptable to use room count or square footage in this calculation, likely you'll want to use square footage unless you have a lot of rooms that are exclusive to you (because your rent income is well below rental expenses, you want to minimize rented portion).
If we assume 2/3 is rented, you can use 1/3 of property tax and mortgage interest as itemized deductions.
Using your example numbers you'd have $20,000 in itemized deductions.
On the rental side 2/3 of each expense, so:
Mortgage interest = $2,666
HOA = $400
Property tax = $666
Depreciation = $2020
That's $5,752 in monthly rental expenses (plus maintenance/repairs, insurance, etc.), which fully offsets $3,000/month in rental income leaving you with no tax obligation on the rental side. However, when you sell you will face unrecaptured section 1250 gain even though you're getting no benefit from depreciating the rental portion of your property.
Using whichever method of calculating rented portion that results in a lower percentage would be beneficial to you.
| {
"pile_set_name": "StackExchange"
} |
Q:
What lens should I buy to get better pictures of a one-year old running around a dimly-lit house?
I'm an amateur photographer with a Canon Rebel XS, and I'm trying to figure out what type of lens I should buy to take better photos of my one year old when she is running around in our dimly lit house. I seem to find myself in a lot of situations where there are kids on the move in low light, and my 50mm f/1.8 II just isn't able to do it. Suggestions?
A:
I don't think another lens is necessarily what you need, although since 50mm is a bit narrow indoors on a Rebel XS, you may want to consider something a bit wider. (The question Will a 35mm lens work for great indoor pictures of my kids? asks about Nikon but the answers will apply in general.) A Rebel-series camera has a sensor which is about 22mm wide, which means that the 50mm lens you have acts as a short telephoto. This is great for portraits of stationary subjects, but not so good for fast-moving small children indoors.
Something in the 28mm to 35mm range will be more "normal", a length which gives a convenient, natural perspective in many different circumstances. If you're feeling like it's often difficult to get everything you want in the frame with your current lens, this is something to explore.
For the low-light issue, though, the f/1.8 maximum aperture of your current lens is quite good. You can't go much faster without spending a ton of money. Image stabilization might help if your problem is that you can't stay still enough for longer shutter speeds, but I'm guessing the main problem with movement is in your subject, and nothing in the lens can help that. In fact, a fast lens (one with a wide aperture, like yours) is actually harder to use in this case, since your little one is apt to zoom right out of the narrow area of focus.
So, I think the main thing you need is more light. Since you probably don't want to add stadium floodlights to your house, take a look at Prime lens or flash: which upgrade will most improve baby photos? — with a focus on the "flash" aspect. A better flash provide a lot more illumination than the pop-up flash does, and more importantly, will allow you to bounce light off the ceiling, not just flash it forward, avoiding the harsh light and shadows often associated with amateur flash photography.
Canon's lower-mid-range flash, the Speedlite 430EX II, is a little pricey at $300 — but that's less than a nice lens might cost. It's also very well featured and able to grow with you as you upgrade the rest of your photography. You could also choose a compatible third-party option like the Metz 50 AF-1 ($200) or the more basic (all-automatic only) but very powerful Sigma EF610 DG ST ($150). Or, you can get a much-cheaper all-manual Yongnuo YN-560 ($70!), but that may not be what you want for in-the-moment kid photos.
A:
Creating Memories
I think that what you're trying to do is capture memorable images of your daughter. (Correct me if I'm wrong!). I don't think you're aiming for photographic perfection.
As a result, many compromises - which may sound technically iffy - are fine for this kind of photography.
Bearing that in mind here are a few suggestions...
Don't be afraid to bump up the ISO
Even if the result is very noisy, if you get "the" shot, then nobody will notice the noise.
Slow down the subject
This works differently with different children, but giving them a toy (especially a cute, cuddly, photogenic toy) might make her stop moving for several seconds (!) - enough time for you to snap off a shot. The trick is not to let her see it until you give it to her. You could have a helper do this.
You could place a big cushion in her path and lie in wait. Negotiating the obstacle will present some interesting shots.
When you have no light, any light is good light!
Get a work lamp and put it in the room. I would point it at the ceiling to get good diffused / spread out light.
Set an appropriate white-balance (or shoot in raw).
Also, consider using the pop-up flash on your camera - perhaps dialled down (set the flash exposure compensation to -1 or even -1.5 stops).
| {
"pile_set_name": "StackExchange"
} |
Q:
Encryption / Decryption PHP classes
What is the best encryption / decryption class / functions that can encrypt an array of data or objects and return it as a hash serialized string?
Then, on decryption, the serialized strings can be decrypted back to its original form of values containing objects or array values.
Thanks
A:
Preface: You seem to have a notion that hashing some data would be the same thing as encrypting it. Hashing is NOT encryption and cannot be reversed with a password or keyfile, like encryption can.
PHP comes with several hashing protocols like md5 (md5_file), SHA1 (SHA1_file). It all really depends on what you're doing with this hash and what you're hashing in the first place.
A:
The mcrypt library has a lot of functions to do encryption in as many ways as you can dream. Here's an example using AES:
$secretKey = 'the longer, the better';
$originalString = 'some text here';
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secretKey, $originalString,
MCRYPT_MODE_CBC, $iv);
printf( "Original string: %s\n", $originalString );
// Returns "Original string: some text here"
printf( "Encrypted string: %s\n", $crypttext );
// Returns "Encrypted string: <gibberish>"
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secretKey, $crypttext,
MCRYPT_MODE_CBC, $iv);
// Drop nulls from end of string
$decrypttext = rtrim($decrypttext, "\0");
printf( "Decrypted string: %s\n", $decrypttext );
// Returns "Decrypted string: some text here"
| {
"pile_set_name": "StackExchange"
} |
Q:
Distinct() on Class, anonymus type and SelectListItem
I want to select all categories from a webservice. The webservice does not have a method for that, so I have to get all products, then select all categories that these products are in. When I recieve the data from the webservice, I make WebServiceProduct (ID, Name, etc) and WebServiceCategory (ID, Name, etc) objects of it.
This does not work:
IQueryable<SelectListItem> categories = (from p in webserviceProductRepository.GetProducts()
from c in p.Categories
select new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
}).Distinct().OrderBy(c => c.Text);
But it works when I first select it as a anonymus type:
var foo = (from p in webserviceProductRepository.GetProducts()
from c in p.Categories
select new
{
ID = c.ID.ToString(),
Name = c.Name
}).Distinct().OrderBy(c => c.Name);
IQueryable<SelectListItem> categories = from c in foo
select new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
};
I have also tried with a IEqualityComparer and overrided Equals and GetHashCode to check on WebServiceCategory.ID, but it does not work either.
So my question are, why is Distinct() working better on a anonymus type than on my WebServiceCategory object and SelectListItem?
A:
Anonymous types have value equality. Reference types have reference equality. LINQ to Entities is following the default semantics for the types. But overriding Equals or implementing IEquatable won't work, because LINQ to Entities queries are translated to SQL, and LINQ to Entities cannot translate arbitrary C# code to SQL. Note that the overloads of, e.g., Distinct which take a comparer aren't supported in L2E.
You have one workaround already, in your second code example. Another would be to group by an anonymous type:
var categories = from p in webserviceProductRepository.GetProducts()
from c in p.Categories
group c by new { Id = c.ID, Name = c.Name } into g
order by g.Key.Name
select new SelectListItem
{
Value = g.Key.Id.ToString(),
Text = g.Key.Name
};
| {
"pile_set_name": "StackExchange"
} |
Q:
external hard drive can not copy the data capacity of more than 6GB
I recently bought an external hard drive with 500GB capacity. hard drive is still in new condition and vacant. but when I would copy a file larger than 6GB hard drive can not copy the file. if I copy the file size of less than 6BG, the file can be copied.
what causes it?
A:
Some filesystems (such as FAT32) have a 4GB limit on file sizes
Some cheap hard drives are fake
| {
"pile_set_name": "StackExchange"
} |
Q:
How would I be able to assign a random integer to a variable?
I have been trying to assign a random number to a variable, such as health or luck but it never seems to work as when I print the variable it just says it's not defined. I would greatly appreciate any help with this. Thank you very much.
from random import randint
def ageroll():
age= int(input("How old will you be?"))
if age <= 0:
print("Input a valid number from 1 to 120")
ageroll()
elif age <= 18:
health = randint(1,4)
agility = randint(4,8)
strength = randint(1,2)
luck = randint(1,10)
endurance = randint(2,4)
intelligence = randint(1,5)
charm = randint(1,7)
return(health,agility,strength,luck,endurance,intelligence,charm)
elif age <= 35:
health = randint(4,10)
agility = randint(5,9)
strength = randint(5,10)
luck = randint(1,10)
endurance = randint(4,8)
intelligence = randint(3,10)
charm = randint(4,7)
elif age <= 56:
health = randint(4,8)
agility = randint(3,6)
strength = randint(3,10)
luck = randint(1,10)
endurance = randint(5,8)
intelligence = randint(5,10)
charm = randint(6,10)
elif age <= 78:
health = randint(2,5)
agility = randint(2,5)
strength = randint(2,6)
luck = randint(1,10)
endurance = randint(1,4)
intelligence = randint(6,10)
charm = randint(5,6)
elif age <= 101:
health = randint(1,5)
agility = randint(1,4)
strength = randint(1,4)
luck = randint(4,10)
endurance = randint(3,9)
intelligence = randint(3,10)
charm = randint(4,7)
elif age <= 120:
health = randint(1,2)
agility = randint(1,3)
strength = randint(1,4)
luck = 10
endurance = randint(6,8)
intelligence = randint(10,10)
charm = randint(6,10)
else:
print("Input a valid number from 1 to 120")
ageroll()
A:
You have to return your variables, and assign this return-value to a variable again, to use it:
from random import randint
PROPERTY_RANGES = [
(18, dict(health=(1,4), agility=(4,8), strength=(1,2), luck=(1,10), endurance=(2,4), intelligence=(1,5), charm=(1,7))),
(35, dict(health=(4,10), agility=(5,9), strength=(5,10), luck=(1,10), endurance=(4,8), intelligence=(3,10), charm=(4,7))),
(56, dict(health=(4,8), agility=(3,6), strength=(3,10), luck=(1,10), endurance=(5,8), intelligence=(5,10), charm=(6,10))),
(78, dict(health=(2,5), agility=(2,5), strength=(2,6), luck=(1,10), endurance=(1,4), intelligence=(6,10), charm=(5,6))),
(101, dict(health=(1,5), agility=(1,4), strength=(1,4), luck=(4,10), endurance=(3,9), intelligence=(3,10), charm=(4,7))),
(120, dict(health=(1,2), agility=(1,3), strength=(1,4), luck=(10,10), endurance=(6,8), intelligence=(10,10), charm=(6,10))),
]
def ageroll():
while True:
age = int(input("How old will you be?"))
if 0 < age <= 120:
break
print("Input a valid number from 1 to 120")
for max_age, values in PROPERTY_RANGES:
if age <= max_age:
break
return {k: randint(*r) for k, r in values.items()}
properties = ageroll()
print(properties['health'])
| {
"pile_set_name": "StackExchange"
} |
Q:
Vector SAT MATH 2
If the magnitudes of vectors a and b are 5 and 12, respectively, then the magnitude of vector (b-a) could NOT be:
a) 5
b) 7
c) 10
d) 12
e) 17
The answer is 5. But I am not sure which theorem I should use to go about this problem. Triangle inequality theorem? Help is appreciated!
A:
By triangle inequality:
$$|b|-|a|\le |a-b| \le |a|+|b|\to 7\le |a-b| \le 17$$
| {
"pile_set_name": "StackExchange"
} |
Q:
What sort of datatype is PRIntn for the file strcase.c
Background
I am reworking a plugin for ettercap and hope to find useful information about handling HTTP-RESPONSE´s in the firefox source code.
Question
So I have found this file named
strcase.c
in the directory
nsprpub/lib/libc/src
from mozilla-beta.
So there is a method called PL_strncasecmp(...) which is interesting for me.
Code:
PR_IMPLEMENT(PRIntn)
PL_strncasecmp(const char *a, const char *b, PRUint32 max)
{
const unsigned char *ua = (const unsigned char *)a;
const unsigned char *ub = (const unsigned char *)b;
if( ((const char *)0 == a) || (const char *)0 == b )
return (PRIntn)(a-b);
while( max && (uc[*ua] == uc[*ub]) && ('\0' != *a) )
{
a++;
ua++;
ub++;
max--;
}
if( 0 == max ) return (PRIntn)0;
return (PRIntn)(uc[*ua] - uc[*ub]);
}
And there is this one line which says: return (PRIntn)(a-b);
And I´m curious what sort of datatype PRIntn is.
Output of grep -rnw "typedef PRIntn" :
root@kali:~/Desktop/mozilla-beta# grep -rnw "typedef PRIntn"
security/nss/lib/base/baset.h:72:typedef PRIntn (* nssListSortFunc)(void *a, void *b);
services/crypto/modules/WeaveCrypto.js:152: // typedef PRIntn PRBool; --> int
nsprpub/lib/ds/plhash.h:21:typedef PRIntn (PR_CALLBACK *PLHashComparator)(const void *v1, const void *v2);
nsprpub/lib/ds/plhash.h:23:typedef PRIntn (PR_CALLBACK *PLHashEnumerator)(PLHashEntry *he, PRIntn i, void *arg);
nsprpub/pr/tests/dlltest.c:36:typedef PRIntn (PR_CALLBACK *GetFcnType)(void);
nsprpub/pr/src/pthreads/ptio.c:283:typedef PRIntn pt_SockLen;
nsprpub/pr/include/prinit.h:105:typedef PRIntn (PR_CALLBACK *PRPrimordialFn)(PRIntn argc, char **argv);
nsprpub/pr/include/prprf.h:67:typedef PRIntn (*PRStuffFunc)(void *arg, const char *s, PRUint32 slen);
nsprpub/pr/include/obsolete/protypes.h:18:typedef PRIntn intn;
nsprpub/pr/include/prtypes.h:467:typedef PRIntn PRBool;
nsprpub/pr/include/prio.h:50:typedef PRIntn PRDescIdentity; /* see: Layering file descriptors */
nsprpub/pr/include/prio.h:357:typedef PRIntn (PR_CALLBACK *PRReservedFN)(PRFileDesc *fd);
nsprpub/pr/include/md/_unixos.h:607:typedef PRIntn (*_MD_Fstat64)(PRIntn osfd, _MDStat64 *buf);
nsprpub/pr/include/md/_unixos.h:608:typedef PRIntn (*_MD_Open64)(const char *path, int oflag, ...);
nsprpub/pr/include/md/_unixos.h:609:typedef PRIntn (*_MD_Stat64)(const char *path, _MDStat64 *buf);
From my understanding of the code I would say it is a kind of Integer or Boolean value. But I can´t argue with just my beliefs.
Thanks in advance
Found Answer
PRIntn is really an integer-type
proof:
prtypes.h:400
400 /************************************************************************
401 ** TYPES: PRUintn
402 ** PRIntn
403 ** DESCRIPTION:
404 ** The PRIntn types are most appropriate for automatic variables. They are
405 ** guaranteed to be at least 16 bits, though various architectures may
406 ** define them to be wider (e.g., 32 or even 64 bits). These types are
407 ** never valid for fields of a structure.
408 ************************************************************************/
409 #if PR_BYTES_PER_INT >= 2
410 typedef int PRIntn;
411 typedef unsigned int PRUintn;
412 #else
413 #error 'sizeof(int)' not sufficient for platform use
414 #endif
A:
Found Answer
PRIntn is really an integer-type.
The statement PR_IMPLEMENT(PRIntn) is linking to the file
prtypes.h
so with looking at this file I found the answer.
proof:
prtypes.h:400
400 /************************************************************************
401 ** TYPES: PRUintn
402 ** PRIntn
403 ** DESCRIPTION:
404 ** The PRIntn types are most appropriate for automatic variables. They are
405 ** guaranteed to be at least 16 bits, though various architectures may
406 ** define them to be wider (e.g., 32 or even 64 bits). These types are
407 ** never valid for fields of a structure.
408 ************************************************************************/
409 #if PR_BYTES_PER_INT >= 2
410 typedef int PRIntn;
411 typedef unsigned int PRUintn;
412 #else
413 #error 'sizeof(int)' not sufficient for platform use
414 #endif
| {
"pile_set_name": "StackExchange"
} |
Q:
Cassandra or Hadoop Hive or MYSQL?
I am Developing a Web Crawler,Which is Good for storing data? Cassandra or Hadoop Hive or MySQL?and why?i am having 1TB of Data from past 6 Months in my MySQL DB,i need to index them and i need to get the out put in my search ASAP,and as i think,it will store more amount of DATA,like 10 Peta Byes as my crawler are working fast,i need to get the read/write operation fast,i need to integrate it in my PHP app
A:
That depends on details of your requirements, but I think that in your case HBase would be the best option.
Using HBase as a web-crawler database is well documented and it's HBase's use that is described in BigTable whitepaper.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.