text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Simplify SQL Server Query by Eliminating Views
I am currently working on a very complex view that in turn retrieves data from several other views. I am worried that if someone changes one of my source views, my query will stop working.
Is there a way on how SQL Server can provide me with a query that achieves the same result but uses source tables (instead of views), thus eliminating the need for intermediary views and improving performance by omitting redundant joins?
A:
Look at the view code in design view in SQL server management studio.
Copy the SQL code and assign the select output of a view into a temp table in your SQL Stored procedure. Now you have a copy inside SP and you do not need to depend on view.
Based on my experience I've found that often view has redundant/repeated data columns which need complex calculations and are usually not needed by everything that consumes those views.
Also by removing nesting, you will get a performance gain.
Alternatively, if you are not worried about performance, you can duplicate a view and label it differently too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a natural topology on C(X), if X is infinite-dimensional?
Suppose $X$ is an infinite-dimensional Banach space.
Is there a natural topology on $$C(X)=\{f:X\to\mathbb{R}: \text{ $f$ is continuous}\}?$$
A:
There are a few, one example would be the weak* topology:
http://en.wikipedia.org/wiki/Weak_topology
| {
"pile_set_name": "StackExchange"
} |
Q:
Kerberos term definitions
I am new to kerberos. I found some link but still can't understand it terms fully and how it should be.
Can anybody please make me understand the following terms?
Realm
Kdc
Principal
I want to know how to mention realm name, kdc name should be in krb5.ini?
I setup active directory in windows server 2012. Where can i find the realm name, principal and all in win server system? I want to authenticate it in windows 8 using command line tool kinit.
Give me some idea or example.
Thanks
A:
To make the terms understandable, we can compare the actual technical term with a domain
Example domain: Driving License
Realm:
Authentication administrative domain
Each realm has its own Kerberos database which contains the users and services for
that particular administrative domain.
Example: TamilNadu has separate administration. Rather AndraPradesh is a separate realm.
Principal:
Entries in the Kerberos database. Each user, host or service is given a principal.
Example: Each person who applies for the license.
Kerberos server - KDC:
Database - Contains the user and service entries (user's principal, maximum validity, maximum renewal time, password expiration, etc.)
Example: License Applicant's details.
Authentication Server(AS) - Replies to the authentication requests from the client, when he is not yet authenticated user must insert a password. The AS sends a Ticket Granting Ticket (TGT) back which can be used further on by the user, without re-entering their password.
Example: Who checks the license; If expired, we are insisted to renew the old one.
Ticket Granting Server(TGS) - Distributes service tickets based on the TGT
Example: License issuing authority, issues license to us.
| {
"pile_set_name": "StackExchange"
} |
Q:
VBA: Error 3265 - "Item not found in this collection"
In Access 2016 I'm trying to open a recordset and save data from it in other variables, but I keep getting this error.
The program itself has more parts, but I only get error in this one, it just update data on its database.
This is my code:
Option Compare Database
Option Explicit
Private Sub btnValidateTimesheet_Click()
' Update timesheet to "Justificat"
Dim intIdTimesheet As Integer
If IsNull(cmbDraftTimesheets.Value) Then
MsgBox("You have to select a timesheet that is Borrador")
Exit Sub
End If
intIdTimesheet = cmbDraftTimesheets.Column(0)
DoCmd.SetWarnings False
DoCmd.RunSQL "update Timesheets set estat = ""Justificat"" where id=" & intIdTimesheet
DoCmd.SetWarnings True
End Sub
Private Sub btnValidateTimesheetLines_Click()
' We select the timesheet_lines for employee, project, activity and dates selected
' For each justification, a new "Justificat" Timesheet is generated which hang timesheet_lines
' ------------------------------- Variables -------------------------------
Dim dictTsLines As Object
Set dictTsLines = CreateObject("Scripting.Dictionary")
' Form inputs
Dim intCodTreb As Integer
Dim strCodProj As String
Dim dateInici, dateFi As Date
Dim intExercici As Integer
' Query strings
Dim strSQLFrom, strSQLWhere As String
Dim strSQLCount, strSQLJustAct, strSQLTsLines As String
' Recordsets
Dim rsCount, rsJustAct, rsTimesheets, rsTsLines As Recordset
' Aux and others...
Dim continue As Integer
Dim intIdJustificacio, intIdTs As Integer
Dim strActivitat As String
' --------------------------------------- Main ---------------------------------------------
' Taking form data
intCodTreb = cmbTreballador.Column(0)
strCodProj = cmbProjecte.Column(1)
dateInici = txtDataInici.Value
dateFi = txtDataFi.Value
' We check the dates are correct
If IsNull(dateInici) Or IsNull(dateFi) Then
MsgBox("Dates can't be null")
Exit Sub
End If
If dateFi < dateInici Then
MsgBox("Start date must be earlier or the same as final date")
Exit Sub
End If
If year(dateInici) <> year(dateFi) Then
MsgBox("Dates must be in the same year")
Exit Sub
End If
intExercici = year(dateInici)
' Make of the clause FROM and WHERE of the select query of timesheet_lines
strSQLFrom = " from (timesheet_lines tsl " & _
" left join timesheets ts on tsl.timesheet_id = ts.id) " & _
" left join justificacions j on j.id = ts.id_justificacio "
strSQLWhere = " where ts.estat = ""Borrador"" " & _
" and tsl.data >= #" & Format(dateInici, "yyyy/mm/dd") & "# " & _
" and tsl.data <= #" & Format(dateFi, "yyyy/mm/dd") & "# "
If Not IsNull(intCodTreb) Then
strSQLWhere = strSQLWhere & " and tsl.cod_treb = " & intCodTreb
End If
If Not IsNull(strCodProj) Then
strSQLWhere = strSQLWhere & " and j.cod_proj=""" & strCodProj & """ "
End If
' Alert how much timesheet_lines are going to be validated
strSQLCount = "select count(*) " & strSQLFrom & strSQLWhere
Set rsCount = CurrentDb.OpenRecordset(strSQLCount)
Continue Do = MsgBox( rsCount(0) & " registries are going to be validated" & vbNewLine & _
"Do you want to continue?", vbOKCancel)
If continue <> 1 Then
Exit Sub
End If
' We select the tuples Justificacio, Activitat of timesheet_lines selected
strSQLJustAct = "select distinct ts.id_justificacio " & strSQLFrom & strSQLWhere
Set rsJustAct = CurrentDb.OpenRecordset(strSQLJustAct)
Set rsTimesheets = CurrentDb.OpenRecordset("Timesheets")
' A new timesheet is generated for each tupla
Do While Not rsJustAct.EOF
intIdJustificacio = rsJustAct(0)
strActivitat = rsJustAct(1)
rsTimesheets.AddNew
rsTimesheets!data_generacio = Now()
rsTimesheets!estat = "Justificat"
rsTimesheets!Id_justificacio = intIdJustificacio
rsTimesheets!activitat = strActivitat
rsTimesheets!data_inici = dateInici
rsTimesheets!data_fi = dateFi
rsTimesheets!exercici = intExercici
intIdTs = rsTimesheets!Id
rsTimesheets.Update
' We save the related id of the selected timesheet in a dictionary
dictTsLines.Add intIdJustificacio & "_" & strActivitat, intIdTs
rsJustAct.MoveNext
Loop
' We select all the affected timesheet_lines and we update the related timesheet using the dictionary
strSQLTsLines = "select tsl.id, tsl.timesheet_id, ts.id_justificacio, ts.activitat " & strSQLFrom & strSQLWhere
Set rsTsLines = CurrentDb.OpenRecordset(strSQLTsLines)
With rsTsLines
Do While Not .EOF
.EDIT
intIdJustificacio = !Id_justificacio
strActivitat = !activitat
!timesheet_id = dictTsLines.Item(intIdJustificacio & "_" & strActivitat)
.Update
.MoveNext
Loop
End With
rsTimesheets.Close
Set rsCount = Nothing
Set rsJustAct = Nothing
Set rsTimesheets = Nothing
Set rsTsLines = Nothing
End Sub
Debugger: The error is coming up at the line:
strActivitat = rsJustAct(1)
I checked that the data the recordset is saving exists and it does.
A:
Your recordset contains just one column ("select distinct ts.id_justificacio"), but you are trying to read second column strActivitat = rsJustAct(1)
Add requred column to recordset.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where's error in implementation of minimax algorithm?
There is one little problem with it's implementation for a Tic-Tac-Toe game. For the following combination:
['x', 'o', 'e',
'o', ' e', 'e',
'e', ' e', 'e']
the best choice would be
['x', 'o', 'e',
'o', ' x', 'e',
'e', ' e', 'e']
but it returns as I suppose the nearest suitable one:
['x', 'o', 'x',
'o', ' e', 'e',
'e', ' e', 'e']
And in this case AI loses.
Here is the code:
var board = ['x', 'o', 'e', 'o', 'e', 'e', 'e', 'e', 'e'];
var signPlayer = 'o';
var signAI = (signPlayer === 'x') ? 'o' : 'x';
game = {
over: function(board) {
for (var i = 0; i < board.length; i += 3) {
if (board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {
return board[i] !== 'e' ? board[i] : false;
}
}
for (var j = 0; j < 3; j++) {
if (board[j] === board[j + 3] && board[j + 3] === board[j + 6]) {
return board[j] !== 'e' ? board[j] : false;
}
}
if ((board[4] === board[0] && board[4] === board[8]) ||
(board[4] === board[2] && board[4] === board[6])) {
return board[4] !== 'e' ? board[4] : false;
}
return ( board.every(function(element) {
return element !== 'e';
}))
},
winner: function(board) {
return game.over(board);
},
possible_moves: function(board, sign) {
var testBoard = [],
nextBoard;
for (var i = 0; i < board.length; i++) {
nextBoard = board.slice();
if (nextBoard[i] === 'e') {
nextBoard[i] = sign;
testBoard.push(nextBoard);
}
}
return testBoard;
}
}
function moveScore(board) {
var result = game.winner(board);
if (result === signPlayer) {
return -100;
}
if (result === signAI) {
return +100;
}
return 0;
//Game is a draw
}
function max(board) {
if (game.over(board)) {
return board;
}
var newGame = [];
var bestMove = [];
var score;
var best_score = -Infinity;
var movesArray = game.possible_moves(board, signAI);
for (var i = 0; i < movesArray.length; i++) {
newGame = movesArray[i].slice();
score = moveScore(min(newGame));
if (score > best_score) {
best_score = score;
bestMove = newGame;
}
}
return bestMove;
}
function min(board) {
if (game.over(board)) {
return board;
}
var newGame = [];
var worstMove = [];
var score;
var worst_score = +Infinity;
var movesArray = game.possible_moves(board, signPlayer);
for (var i = 0; i < movesArray.length; i++) {
newGame = movesArray[i].slice();
score = moveScore(max(newGame));
if (score < worst_score) {
worst_score = score;
worstMove = newGame;
}
}
return worstMove;
}
max(board);
A:
There are the following issues:
The over method gives wrong output for some boards, like for instance for this board:
['e', 'e', 'e', 'o', 'o', 'o', 'x', 'x', 'e']
It will actually stop looking after it finds the three e values in the first three elements and return false, i.e. it does not see the win on the second row for o. To fix, change this line:
return board[i] !== 'e' ? board[i] : false;
to:
if (board[i] !== 'e') return board[i];
This will make the function continue with the other checks if it finds three e in a row. Similar fixes are necessary in the other loops (except the very last one).
Although the minimax algorithm visits the nodes in the search tree succesfully, it does not carry the found leaf-score (0, -100 or 100) back up in the search tree. Instead you recalculate each position's score by just looking at a static board configuration, ignoring the best/worst score you could get from the recursive call. To fix this, let the min and max function not only return the best move, but also the score associated with it. So replace this:
return bestMove;
with:
return [best_score, bestMove];
And then you pick up the score from the recursive call, if you replace this:
score = moveScore(min(newGame));
with:
score = min(newGame)[0];
You need to do a similar change for the case where the game is over. Replace this:
if (game.over(board)) {
return board;
}
with:
if (game.over(board)) {
return [moveScore(board), []];
}
Note that this is the only right moment to call moveScore. The second element of the array should be the best move, but as there is no move, it is better to just use an empty array for that.
This is a minor issue: you don't actually use the best move you get from the main call to max. With the above change, you could get both the best move and its score in the main call:
[score, nextBoard] = max(board);
Here is your corrected code, with some additional code at the end to allow a game to be played by clicking on a 3x3 grid. For that purpose I have changed the code e to a space, as it looks better on a printed board:
var board = ['x', 'o', ' ', 'o', ' ', ' ', ' ', ' ', ' '];
var signPlayer = 'o';
var signAI = (signPlayer === 'x') ? 'o' : 'x';
var game = {
over: function(board) {
for (var i = 0; i < board.length; i += 3) {
if (board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {
//return board[i] !== ' ' ? board[i] : false;
if (board[i] !== ' ') return board[i];
}
}
for (var j = 0; j < 3; j++) {
if (board[j] === board[j + 3] && board[j + 3] === board[j + 6]) {
//return board[j] !== ' ' ? board[j] : false;
if (board[j] !== ' ') return board[j];
}
}
if ((board[4] === board[0] && board[4] === board[8]) ||
(board[4] === board[2] && board[4] === board[6])) {
//return board[4] !== ' ' ? board[4] : false;
if (board[4] !== ' ') return board[4];
}
return ( board.every(function(element) {
return element !== ' ';
}))
},
winner: function(board) {
return game.over(board);
},
possible_moves: function(board, sign) {
var testBoard = [],
nextBoard;
for (var i = 0; i < board.length; i++) {
nextBoard = board.slice();
if (nextBoard[i] === ' ') {
nextBoard[i] = sign;
testBoard.push(nextBoard);
}
}
return testBoard;
}
}
function moveScore(board) {
var result = game.winner(board);
if (result === signPlayer) {
return -100;
}
if (result === signAI) {
return +100;
}
return 0;
//Game is a draw
}
function max(board) {
//if (game.over(board)) {
// return board;
//}
if (game.over(board)) {
return [moveScore(board), []];
}
var newGame = [];
var bestMove = [];
var score;
var best_score = -Infinity;
var movesArray = game.possible_moves(board, signAI);
for (var i = 0; i < movesArray.length; i++) {
newGame = movesArray[i].slice();
//score = moveScore(min(newGame));
score = min(newGame)[0];
if (score > best_score) {
best_score = score;
bestMove = newGame;
}
}
//return bestMove;
return [best_score, bestMove];
}
function min(board) {
//if (game.over(board)) {
// return board;
//}
if (game.over(board)) {
return [moveScore(board), []];
}
var newGame = [];
var worstMove = [];
var score;
var worst_score = +Infinity;
var movesArray = game.possible_moves(board, signPlayer);
for (var i = 0; i < movesArray.length; i++) {
newGame = movesArray[i].slice();
//score = moveScore(max(newGame));
score = max(newGame)[0];
if (score < worst_score) {
worst_score = score;
worstMove = newGame;
}
}
//return worstMove;
return [worst_score, worstMove];
}
// Extra code for adding a simple GUI
var board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
var score = null;
var tds = Array.from(document.querySelectorAll('td'));
var table = document.querySelector('table');
var span = document.querySelector('span');
function display(board, score) {
board.forEach( (v, i) => tds[i].textContent = v );
span.textContent = score;
}
display(board);
table.onclick = function (e) {
var i = tds.indexOf(e.target);
if (i == -1 || board[i] !== ' ' || game.over(board)) return;
board[i] = signPlayer;
display(board);
[score, board] = max(board, 1);
display(board, score);
}
td { border: 1px solid; width: 20px; text-align: center; cursor: hand }
tr { height: 25px; v-align: middle }
<table>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
</table>
<div>
Score: <span></span>
</div>
Final note
I have just made the corrections to make it work, but note there are several ways to improve the efficiency. This you can do by using an alpha-beta search, tracking scores for already evaluated boards, while mapping similar boards by translations (turning, mirroring), and mutating boards instead of creating a new board each time you play a move.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pass environment variable to bash script, called from within a function
I mean to have:
A bash script scr.sh that takes positional parameters
#!/bin/bash
echo "Params = $@"
echo REMOTE_SERVER=${REMOTE_SERVER}
A bash function f defined in another script scr2.sh
#!/bin/bash
f() {
REMOTE_SERVER=s001
scr.sh "${@}"
}
I would first
$ source scr2.sh
and then have f available for calling at the command line, but not leaving a trace of what I did with REMOTE_SERVER. For instance, I want
$ f par1 par2
par1 par2
s001
$ echo REMOTE_SERVER=${REMOTE_SERVER}
REMOTE_SERVER=
(actually, if REMOTE_SERVER was set before using f, I want it to keep that value). I couldn't attain this last objective. I always end up with REMOTE_SERVER set.
I tried using multiline commands separated with a semicolon, enclosing commands inside f with parenthesis, but it didn't work.
How can I do that?
A:
If you want to set a variable only for a command, prefix the assignment to the command:
REMOTE_SERVER=s001 scr.sh "${@}"
Alternately, use a subshell for the function (then variable assignments won't affect the parent shell). You can create a subshell by wrapping commands in ( ... ) (parentheses), or using parentheses instead of braces for the function body. For example, with:
foo () (
REMOTE_SERVER=s001
)
bar () {
REMOTE_SERVER=s001
}
foo; echo "REMOTE_SERVER=$REMOTE_SERVER"; bar; echo "REMOTE_SERVER=$REMOTE_SERVER";
My output would be:
REMOTE_SERVER=
REMOTE_SERVER=s001
| {
"pile_set_name": "StackExchange"
} |
Q:
Emotion roll from center to right using Android animation
I want my ImageView roll from center of screen to right. I use this code at the moment, but it doesn't roll the image.
final AnimationSet rollingIn = new AnimationSet(true);
Animation moving = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -1f, Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
Animation.RELATIVE_TO_PARENT, 0);
moving.setDuration(5000);
rollingIn.addAnimation(moving);
A:
try
final AnimationSet rollingIn = new AnimationSet(true);
Animation moving = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 5, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
moving.setDuration(1000);
final Animation rotating = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotating.setDuration(1000);
rollingIn.addAnimation(rotating);
rollingIn.addAnimation(moving);
| {
"pile_set_name": "StackExchange"
} |
Q:
Loop inside "heredoc" in shell scripting
I need to execute series of commands inside an interactive program/utility with parameterized values. Is there a way to loop inside heredoc ? Like below .. Not sure if eval can be of any help here. Below example doesn't seem to work as the interactive doesn't seem to recognize system commands.
#!/bin/sh
list="OBJECT1 OBJECT2 OBJECT3"
utilityExecutable << EOF
for i in $list ; do
utilityCommand $i
done
EOF
A:
Instead of passing a here-document to utilityExecutable,
the equivalent is to pipe the required text to it. You can create the desired text using echo statements in a for-loop, and pipe the entire loop output to utilityExecutable:
#!/bin/sh
list="OBJECT1 OBJECT2 OBJECT3"
for i in $list; do
echo "utilityCommand $i"
done | utilityExecutable
| {
"pile_set_name": "StackExchange"
} |
Q:
Showing that $\mu^{*}(B)\leq\mu'(B),$ where $\mu'(B)=\inf\{\mu(A):B\subset A\in\mathcal{A}\}$
Let $X$ a set, $\mathcal{A}$ an algebra of subsets in $X$, and $\mu $ a measure in $\mathcal{A}.$
If $B\subset X$, we define $\mu'(B)=\inf\{\mu(A):B\subset A\in\mathcal{A}\}$. I already showed that $\mu'(E)=\mu(E)$ for all $E\in\mathcal{A}$, and now I want to prove that, for all $B\subset X, \mu^{*}(B)\leq\mu'(B),$ where $\mu^{*}(B)=\inf\sum_{n=1}^{\infty}\mu(E_{j}),$ where the infimum is taken by every sequence $(E_{j})\in\mathcal{A}$ such that $B\subset\bigcup_{j=1}^{m}E_{j}.$ Moreover, if $X$ is a countable union of sets with finite $\mu-$measure, $\mu^{*}(B)=\mu'(B).$
My problem is that I can't really see the diference between $\mu^{*}$ and $\mu'$.
(i) If $(E_{j})$ is a sequence of sets in $\mathcal{A}$ with $B\subset\bigcup_{j=1}^{\infty}E_{j},$ I need to show that exists a set $A\in\mathcal{A}$ such that $B\subset A$ and $\mu(A)\leq \sum_{j=1}^{\infty}\mu(E_{j})$. If this is true, I can prove that $\mu^{*}(B)\leq\mu'(B)$.
(ii) On another hand, if $A\in\mathcal{A}$ is a set such that $B\subset A$, so we can define the sequence $(E_{j})\in\mathcal{A}$ by $E_{1}=A$ and $E_{j}=\emptyset$ for all $j>1.$ So $\mu(A)\leq \sum_{j=1}^{\infty}\mu(E_{j}).$ So, I can prove that $\mu'(B)\leq\mu^{*}(B)$.
So, I conclude that $\mu'(B)=\mu^{*}(B).$
How can I prove (i) ? And what was my mistake in (ii)?
A:
To prove $\mu^*(B) \leq \mu'(B),$ we suppose $A \in \mathcal{A}$ such that $B \subseteq A$ and then define $E_1 = A$ and $E_i = \emptyset$ for any $i \geq 2,$ where we note $E_i \in \mathcal{A}$ for every $i$ and $B \subseteq A = \bigcup_{i=1}^\infty E_i.$ This allows us to write
$$\mu^*(B) \leq \sum_{i=1}^\infty \mu(E_i) = \mu(A)$$
Since $A \in \mathcal{A}$ such that $B \subseteq A$ was arbitrary, we can now take the infimum to show $$\mu^*(B) \leq \inf \{\mu(A) : A \in \mathcal{A}, B \subseteq A\} = \mu'(B)$$
As I stated in the comments, the reason why we cannot use the above logic to show $\mu'(B) \leq \mu^*(B)$ is that the choice of $E_i \in \mathcal{A}$ was not arbitrarily chosen such that $B \subseteq \bigcup E_i$ but rather it was a very particular choice dependent on the original $A.$
| {
"pile_set_name": "StackExchange"
} |
Q:
Mutating list in python
I want to define a function which can mutate the inputted list by adding 1's([1,1,1,...]) in to it.
But, I don't want to use loops to perform this simple operation.
# input - a list (empty list)
# - number of elements to initialize
# output- None
# - But it will have to mutate the inputted (list)
def initialize_one(empty_lis, n):
# Do nothing if e_lis is a non-empty list
if len(empty_lis) is not 0:
return
else:
temp = [1] * n
# empty_lis = temp will not mutate
# And I don't want to use loops to append
# because if n = 100,000
# it will have to loop for 100,000 times
lis = []
n = 10
initialize_one(lis, n)
print lis
# expected output
# >>>[1, 1, 1, 1, 1, 1, 1, 1, 1]
A:
def initialize_one(seq, n):
if not seq:
seq[:] = [1] * n
| {
"pile_set_name": "StackExchange"
} |
Q:
RegEx for matching all chars except for comma separated digits
I have an input that I want to apply validation to. User can type any integer (positive or negative) numbers separated with a comma. I want to
Some examples of allowed inputs:
1,2,3
-1,2,-3
3
4
22,-33
Some examples of forbidden inputs:
1,,2
--1,2,3
-1,2,--3
asdas
[]\%$1
I know a little about regex, I tried lots of ways, they're not working very well see this inline regex checker:
^[-|\d][\d,][\d]
A:
You can use
^(?:-?[0-9]+(?:,(?!$)|$))+$
https://regex101.com/r/PAyar7/2
-? - Lead with optional -
[0-9]+ - Repeat digits
(?:,(?!$)|$)) - After the digits, match either a comma, or the end of the string. When matching a comma, make sure you're not at the end of the string with (?!$)
A:
As per your requirements I'd use something simple like
^-?\d+(?:,-?\d+)*$
at start ^ an optional minus -? followed by \d+ one or more digits.
followed by (?:,-?\d+)* a quantified non capturing group containing a comma, followed by an optional hyphen, followed by one or more digits until $ end.
See your updated demo at regex101
Another perhaps harder to understand one which might be a bit less efficient:
^(?:(?:\B-)?\d+,?)+\b$
The quantified non capturing group contains another optional non capturing group with a hyphen preceded by a non word boundary, followed by 1 or more digits, followed by optional comma.
\b the word boundary at the $ end ensures, that the string must end with a word character (which can only be a digit here).
You can test this one here at regex101
| {
"pile_set_name": "StackExchange"
} |
Q:
ListView in Objective-C Cocoa
I used for some time the .net framework, especially Wpf. Now I need to develop an application for Os X using cocoa. In wpf I have the ListView object where each element can be what object I want. I need to use an alternative in cocoa that allows me to scroll I list of personal "user control".
Is there such alternative?
A:
The alternative of List-view in OS X is TableView, you can refer to the Apple documentation for the reference.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/TableView
| {
"pile_set_name": "StackExchange"
} |
Q:
SSIS 2008 Script in C#: need to convert Y2K string to date format and use it to populate variable
I am trying to get records from an AS400 system into Dynamics CRM programatically. To achieve this i have pushed the AS400 records into a SQL table and am able to push those records to CRM by referencing the CRM 4 web service endpoints in a SSIS 2008 C# script.
The problem is one of the fields is in Y2K date string format. In order to get it into a date field (D.O.B) in CRM i believe i will need to convert it to a date format then reference resulting value in a variable.
I do not know how to do this.
This question/answer (http://stackoverflow.com/a/4880021/1326443) may help with part of the question but i do not know how to use this into my script to get a value (haven't done any scripting for a number of years and new to C#)
Script snippet:
public class ScriptMain : UserComponent
{
private CrmService service = null;
public override void PreExecute()
{
base.PreExecute();
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "DevOrg";
service = new CrmService();
service.Url = "http://crm/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
public override void PostExecute()
{
base.PostExecute();
}
public override void LeadInput_ProcessInputRow(LeadInputBuffer Row)
{
lead cont = new lead();
if (!Row.TITL20_IsNull)
{
cont.salutation = Row.TITL20;
}
if (!Row.DOBI20_IsNull)
{
cont.new_birthdate = Row.DOBI20;
}
....
....
service.Create(cont);
}
}
}
{ cont.new_birthdate = Row.DOBI20; } throws:
cannot implicitly convert type 'string' to .....CrmSdk.CRMDateTime
A:
Just had a look at the documentation for CRMDateTime (http://msdn.microsoft.com/en-us/library/bb928935.aspx)
This states that you can set this using the Value property (http://msdn.microsoft.com/en-us/library/bb928944.aspx)
So you might like to try:
cont.new_birthdate.Value = Row.DOBI20
Edit
In response to your comments, try the following
string ConvertDate(string dateToConvert)
{
dateToConvert= dateToConvert.PadLeft(7, '0');
int c;
int.TryParse(dateToConvert.Substring(0,1), out c);
c = (c * 100) + 1900;
int y;
int.TryParse(dateToConvert.Substring(1,2), out y);
return (c+y).ToString() + dateToConvert.Substring(3,4);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I use the [Bind(Include="")] attribute on complex nested objects?
I'm creating an inventory of locks, each lock has a serial number (Title), an associated school (SchoolCode), and 5 associated Combinations (having Number, Combination, and IsActive). We're using Ncommon and linq and have set them up as nested entities (Lock Has Many Combinations).
On the form, I'm using JQuery Templates to dynamically build the form. Where SchoolCode and Title are basic form elements, Combinations[index].Number and Combinations[index].Combination are the sub-elements.
<form method="post" action="/Lockers.aspx/Locks/Add">
<input type="hidden" name="SchoolCode" value="102">
Lock S/N: <input type="text" name="Title" value=""><br>
<div id="combinations">
<input type="hidden" name="Combinations[0].Number" value="1">
<input type="text" name="Combinations[0].Combination" value="">
<input type="radio" value="1" name="ActiveCombination"><br>
<input type="hidden" name="Combinations[1].Number" value="2">
<input type="text" name="Combinations[1].Combination" value="">
<input type="radio" value="2" name="ActiveCombination"><br>
<input type="hidden" name="Combinations[2].Number" value="3">
<input type="text" name="Combinations[2].Combination" value="">
<input type="radio" value="3" name="ActiveCombination"><br>
<input type="hidden" name="Combinations[3].Number" value="4">
<input type="text" name="Combinations[3].Combination" value="">
<input type="radio" value="4" name="ActiveCombination"><br>
<input type="hidden" name="Combinations[4].Number" value="5">
<input type="text" name="Combinations[4].Combination" value="">
<input type="radio" value="5" name="ActiveCombination"><br></div>
<input type="submit" id="add" value="Add »"> <br>
</form>
When I run this without the Bind attribute, model binding works fine. Once I add the bind, I can't seem to have it bind to any of the Combinations.
[HttpPost]
public ActionResult Add([Bind(Include = "SchoolCode,Title,Combinations.Combination,Combination.Number,Combinations[2].Combination")] LockerLock @lock, [Range(1, 5)] int ActiveCombination)
{
...
}
A:
From what I can tell I need to tell it to bind to the property of a lock called Combinations, from there I can't further choose to include or exclude properties to bind on the sub-object. Instead I would need to specify the bind attribute on the Domain model object itself.
[HttpPost]
public ActionResult Add([Bind(Include = "SchoolCode,Title,Combinations")] LockerLock @lock, [Range(1, 5)] int ActiveCombination)
{
...
}
The Bind attribute is then included on the Combination object...
[Bind(Include = "Number,Combination")]
private class LockerLockCombination
{
[Required]
string Number { get; set; }
[Required]
string SchoolCode { get; set; }
}
For consistency, I'll probably just include the bind on the original lock model...
Just to contrast, here's my final solution. I just added the BindAttribute to the domain model in both cases:
namespace Project.Web.Models
{
[MetadataType(typeof(LockerLock.Validation))]
public partial class LockerLock
{
[Bind(Include = "SchoolCode, Title, Combinations")]
private class Validation
{
[Required]
string Title {get; set;}
[Required]
string SchoolCode {get; set;}
}
}
}
namespace Project.Web.Models
{
[MetadataType(typeof(LockerLockCombination.Validation))]
public partial class LockerLockCombination
{
[Bind(Include = "Number, Combination")]
private class Validation
{
[Required]
string Number { get; set; }
[Required]
string Combination { get; set; }
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Taking a Shower after the Mikvah
Is there any problem with taking a shower after dipping in the Mikvah? I once heard there was.
A:
The source for this is Shabbos 14a and Yorah Deah 201:75 Rama.
http://www.dailyhalacha.com/displayRead.asp?readID=1814
As in many Halachos there is a
Machlokes. In summary according to the
custom of the Ashkenazim, a woman
should not bathe or shower after
immersing in the Mikveh. Sepharadim,
however, do not follow this custom,
and thus Sephardic women may bathe or
shower immediately after immersion
without any concern.
A:
There is a story of a great Rav (no official source) who would shower after the mikvah. When asked about his custom he answered:
Before going into the mikvah I shower
because of the mitzvah "ואהבת לרעך".
When coming out I shower because of
"כמוך".
| {
"pile_set_name": "StackExchange"
} |
Q:
Basic attack strategy for Civilization 5
I'm new to the Civilization franchise and was just wondering if conquering early game is worth it. Should I upgrade my civilization and unleash my fury when I have everything unlocked or is there some merit to conquering a civ here or there when still in the medieval era. I ask this because (I'm playing right now) I personally don't see the benefit in just wasting early game units when I can just upgrade everything and unleash hell later on when I have all the fun stuff :)
A:
There is significant advantage to conquering in the early game. Your Civ's power is almost always directly related to the size of your empire, except for the hit to happiness due to size, and potentially income drain if you don't build your economy properly.
Thus, the earlier you get big, the more of an advantage you will have. I tend to try to time my conquering with the advent of new siege units. Usually this means I will go on my first conquering spree when Catapults come along. This is pretty early in the game by any standard.
Trebuchets are a small improvement by comparison, but when Cannons and Artillery enter the game, these are both times to start picking fights.
Artillery in particular start with Indirect Fire and one additional point of range compared to previous siege units. If you get there first and have a strong lead by this point in the game, it's pretty much game over for the AI.
The siege units allow you to down cities quickly and with minimal losses to your army. If you're ahead technologically, taking these units into battle will almost always end in a decisive victory for your side.
Do note that these siege units should be trailing behind whatever front-line infantry is modern at the time you start your attack. By themselves, they're fairly weak and won't stand up to melee attacks.
Once you've conquered a single neighbor, chances are you're going to be ahead in most meaningful metrics. Thus, you'll get to the next siege unit milestone earlier, and can more easily conquer your next foe. This snowball effect means that the earlier you start, the quicker you win.
Finally, if you get to the point where you're playing for score, the earlier you finish the game, the higher your score will be. The fastest way to win is by far conquering the other Civs and taking their capitals. Thus, it's a solid strategy when playing for score to conquer early and conquer often.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display all nested list elements according to input text search?
I'm creating a web application that returns an NBA player's name and jersey number when a user searches for a player (and the match is found).
I can return the name that has been searched, but I cannot return the jersey number.
I've tried setting style.display = true, which works for the name node, but I can't get this to work on the jersey node.
Here's how my HTML has been created with DOM manipulation from a JSON:
function searchPlayer() {
let input, filter, ul, li, playerName, i;
input = document.getElementById("search-bar");
filter = input.value.toUpperCase();
li = document.getElementById("player-list").getElementsByTagName("li");
Object.keys(li).forEach(function(name) {
playerName = li[name].innerHTML;
if (playerName.toUpperCase().indexOf(filter) > -1) {
li[name].style.display = true;
} else {
li[name].style.display = "none";
}
})
}
<div id="player-list-section">
<ul id="player-list">
<li id="player">
<li id="full-name">Alex Abrines</li>
<li id="jersey">Jersey: 8</li>
</li>
<li id="player">
<li id="full-name">Quincy Acy</li>
<li id="jersey">Jersey: 13</li>
</li>
</ul>
</div>
<input id="search-bar" />
<button onclick="searchPlayer()">Search</button>
I know I can access the child node of player using e.g. li[name].childNode[1] (which returns the jersey li), but I can't call anything on this, such as .innerHTML or .style.display.
How can I return both the name and the jersey?
A:
You need to use list-item instead of true if you want to show the list items after hidding them using display:none and use .closest(".player") to toggle the display of the parent instead:
if (playerName.toUpperCase().indexOf(filter) > -1) {
li[name].closest(".player").display = 'block';
} else {
li[name].closest(".player").display = "none";
}
NOTE 1: You need to validate your structure li can't be a parent of another li, check my updated HTML format.
NOTE 2: You need also to replace the duplicate id by common classes since the identifier must be unique in the same document.
function searchPlayer() {
let input, filter, ul, li, playerName, i;
input = document.getElementById("search-bar");
filter = input.value.toUpperCase();
li = document.querySelectorAll("#player-list .full-name");
Object.keys(li).forEach(function(name) {
playerName = li[name].innerHTML;
if (playerName.toUpperCase().indexOf(filter) > -1) {
li[name].closest(".player").style.display = 'list-item';
} else {
li[name].closest(".player").style.display = "none";
}
})
}
<input id="search-bar" oninput='searchPlayer()'>
<div id="player-list-section">
<ul id="player-list">
<li class="player">
<ul>
<li class="full-name">Alex Abrines</li>
<li class="jersey">Jersey: 8</li>
</ul>
</li>
<li class="player">
<ul>
<li class="full-name">Quincy Acy</li>
<li class="jersey">Jersey: 13</li>
</ul>
</li>
</ul>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Recursive Karatsuba multiplication not working?
I'm trying to implement Karatsuba multiplication through recursive calls. The code below should work, but I keep getting the wrong answer. Any thoughts?
public static long karatsuba(long x, long y){
//base case:
if (x < 10 || y < 10) return x * y;
//length of digits:
int xSize = String.valueOf(x).length();
int ySize = String.valueOf(y).length();
int N = Math.max(xSize, ySize);
//split each number in half (by length of digits):
long numX_hi = Long.valueOf((String.valueOf(x).substring(0, N/2)));
long numX_lo = Long.valueOf((String.valueOf(x).substring(N/2, xSize)));
long numY_hi = Long.valueOf((String.valueOf(y).substring(0, N/2)));
long numY_lo = Long.valueOf((String.valueOf(y).substring(N/2, ySize)));
//solve multiplications recursively:
long z0 = karatsuba(numX_lo,numY_lo);
long z1 = karatsuba((numX_hi+numX_lo),(numY_hi+numY_lo));
long z2 = karatsuba(numX_hi,numY_hi);
//answer:
return (long)(z2 * Math.pow(10,N)) + (long)((z1-z2-z0) * Math.pow(10,(N/2))) + (z0);
}
Here are a few test cases:
1) karatsuba(1234,5678) >>> 6952652
*should be 7006652
2) karatsuba(4589, 7831) >>> 34649459
*should be 35936459
3) karatsuba(911, 482) >>> 44722
*should be 472842
A:
There are two distinct problems with your method.
Firstly, you should split starting from the last (least significant) digit, not the first. So if you've got these two numbers:
1234
567890
You currently split them like this:
123 4 (123*1000+4)
567 890 (567*1000+890)
This gets you the wrong result because 1234 != 123*1000+4
You should instead split them like this:
1 234 (1*1000+234)
567 890 (567*1000+890)
The second error I discovered happens when you add things back together.
return (long)(z2 * Math.pow(10,N)) + (long)((z1-z2-z0) * Math.pow(10,(N/2))) + (z0);
Will return an incorrect result for odd Ns, as N/2 will be rounded up down and therefore N != ((N/2)*2)
I've combined the two fixes and now I get the correct results:
public static long karatsuba(long x, long y){
//base case:
if (x < 10 || y < 10) return x * y;
//length of digits:
int xSize = String.valueOf(x).length();
int ySize = String.valueOf(y).length();
int halfN = Math.max(xSize, ySize) / 2; // store N/2 instead of N
int splitX = xSize - halfN; // count the split point from xSize down
int splitY = ySize - halfN; // count the split point from ySize down
//split each number in half (by length of digits):
long numX_hi = Long.valueOf((String.valueOf(x).substring(0, splitX)));
long numX_lo = Long.valueOf((String.valueOf(x).substring(splitX)));
long numY_hi = Long.valueOf((String.valueOf(y).substring(0, splitY)));
long numY_lo = Long.valueOf((String.valueOf(y).substring(splitY)));
//solve multiplications recursively:
long z0 = karatsuba(numX_lo,numY_lo);
long z1 = karatsuba((numX_hi+numX_lo),(numY_hi+numY_lo));
long z2 = karatsuba(numX_hi,numY_hi);
//answer:
return (long)(z2 * Math.pow(10,halfN*2)) + (long)((z1-z2-z0) * Math.pow(10,halfN)) + (z0);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find file with string
I currently using grep til find files which has some relations to ax.
The way i am currently searching is by
grep -ril "ax" .
But this also finds files with ax as a substring like words such as
max, axis and so on.
How do i ensure the the word I am looking for only have ax in it .. and isn't a substring of some sort?
A:
You can use -w option in grep to find the same.
grep -w 'ax' *
output
l.txt:ax
above command will search exactly for the word "ax" in path then it prints the filename and string searched for.
If you need line number with filename you can use below command
grep -win 'ax' *
l.txt:1:ax
| {
"pile_set_name": "StackExchange"
} |
Q:
Netbeans wizard to generate php classes
I want a wizard where I insert the database connection, and with some settings it generates the PHP classes. The wizard can use (internally) a template already created.
Is that posible? Does that already exists? If not, any ideas of how to do it?
Thanks!
Edit
I'm looking for something wich let me make my own class template or set it up.
A:
NetBeans rocks!
NetBeans has strong MySql support, however, there are no native tools to generate classes from tables.
There is a plug-in called db2php, check it out here. It will allow you to generate classes, basically ORM. Great if you are not using frameworks. If you are using Zend framework, search Zend Framework support on NetBeans site or right click project and go to Zend -> Run Zend Command.
Also, for easy connections and code generation use ALT + Insert, saves a lot of time. The context changes depending on what is defined in you document.
Edit on Oct 1, 2010
There is no software out there that has custom templating system for database table creation. People try to convert to more standardized and sql free way, in other words ORM. Doctrine is one of them, but there is learning curve.
Solution # 1
You might want to look into standard NetBeans templating system. If you go to [Tools->Templates->Under PHP Section] you will be able to add templates and then create new classes from your the template via [Right Click->New -> Other -> Your Template]. Extending PHP Class might do it for you. Here is Sun's blog showing how to use templates, also do a little searching on Google.
Solution # 2
Inheritance might be the answer for you. Create BaseTable that has the connection and common methods, then create ChildTable that enherits (extends) from BaseTable.
You can create Data Access Layer (DAL) to create common data access methods or create Table objects.
Below is an example of DAL
abstract class DALBase {
/**
* Database connection
* @var <type>
*/
protected $_connection = null;
/**
* Name of table
* @var string
*/
protected $_tbl = null;
/**
* Name of primary key column
* @var string
*/
protected $_key = null;
/**
* Default Init
*/
public function __construct() {
$this->_tbl = 'table_name';
$this->_key = 'primary_key';
}
/**
* Gets the connection
*
* @return <type>
*/
private function _getConnection() {
if (!$this->_connection) {
$this->_connection = mysqli_connect('localhost', 'zend101', '', 'zend101', '3306');
if (!$this->_connection) {
throw new Exception('Could not connect to MySQL: ' . mysqli_connect_error());
}
}
//
return $this->_connection;
}
/**
* Executes the query
*/
public function executeQuery($query) {
$conn = $this->_getConnection();
return mysqli_query($conn, $query);
}
/**
* Loads item by primary key
*
* @param mixed $id
* @return object
*/
public function getByID($id) {
//
$query = "SELECT * FROM $this->_tbl WHERE $this->_key = $id";
//
$conn = $this->_getConnection();
$result = $this->executeQuery($query);
//
$item = mysql_fetch_object($query);
//
return $item;
}
/**
* Loads a list
*
* @return array
*/
public function loadList() {
//
$data = array();
//
$result = $this->executeQuery("SELECT * FROM $this->_tbl");
if ($result) {
// Scan through the resource
while ($row = mysql_fetch_object($result)) {
// put row object into the array
$data[] = $row;
}
}
//
return $data;
}
}
/**
* Car table
*/
class DALCar extends DALBase {
/**
*
*/
public function __construct() {
$this->_tbl = 'car';
$this->_key = 'vin';
}
}
/**
* Client table
*/
class DALClient extends DALBase {
/**
*
*/
public function __construct() {
$this->_tbl = 'client';
$this->_key = 'id';
}
}
// Usage
$dal = new DALClient();
$clients = $dal->loadList();
$client1 = $dal->getByID(1);
$client5 = $dal->getByID(5);
You can rewrite the parent class and make it table generic where you have all your fields and save method, delete method, etc... and then child classes will extend it and make it table specific.
It is not a good practice to copy your code, use template everywhere. It is better to extend classes, if you decide to make a change you will have to change it in 1 place. But if you have dozens of tables and you used template, you might need to do dozens of changes.
Just run into an interesting topic, might help you Which database patterns (ORM, DAO, Active Record, etc.) to use for small/medium projects?
| {
"pile_set_name": "StackExchange"
} |
Q:
Function to check data in environment - R
I know this in a environment issue but I need help to figure out where I am going wrong.
I have the need to check data exists in the a knit environment (Rmd). I'd like to write a function that can be used inside other functions:
## Function to check x exists in some environment
data_check_fun <- function(x, e = parent.frame()) {
## Use substitute so I can pass in unquoted variable
df_name <- deparse(substitute(x))
## Check env looking in
print("looking in env: ")
print(e)
exists(df_name, envir = e)
}
## Create df in Global env
df <- data.frame()
## Try function (works)
> data_check_fun(x = df)
[1] "looking in env: "
<environment: R_GlobalEnv>
[1] TRUE
> data_check_fun(x = not_df)
[1] "looking in env: "
<environment: R_GlobalEnv>
[1] FALSE
## Create new env: knit_env
knit_env <- new.env()
## Put df in knit_env
knit_env$knit_df <- data.frame()
## Check df is in knit_env
> ls(knit_env)
[1] "knit_df"
## Try function (works)
> data_check_fun(x = knit_df, e = knit_env)
[1] "looking in env: "
<environment: 0xda4ac60>
[1] TRUE
> data_check_fun(x = not_df, e = knit_env)
[1] "looking in env: "
<environment: 0xda4ac60>
[1] FALSE
## Create new function e.g. to plot, which calls data_check fun
plot_function <- function(plot_data, env) {
data_check_fun(x = plot_data, e = env)
}
## Pass data from knit_env into plot function (does not work)
> plot_function(plot_data = knit_df, env = knit_env)
[1] "looking in env: "
<environment: 0xda4ac60>
[1] FALSE
I think it is because data_check_fun inside plot_function is looking for something now called plot_data which doesn't exist. Is there a way I could do this. Ideally I don't want to quote the argument being passed into plot_function.
A:
It would be a lot easier if the first argument of data_check_fun were simply defined to be a character string. Using non-standard evaluation, as in the question, tends to require significant additional effort but if you really want to do it without explicitly quoting the arguments then capture the call, build up the new call and evaluate it yourself like this:
plot_function2 <- function(plot_data, env) {
mf <- match.call()
m <- match(c("plot_data", "env"), names(mf), 0L)
mf <- mf[c(1L, m)]
names(mf)[m] <- c("x", "e")[m > 0]
mf[[1L]] <- quote(data_check_fun)
eval.parent(mf)
}
# test
plot_function2(plot_data = knit_df, env = knit_env)
See the source code for lm for another examqple.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to read content of an xml file in Java
I have created an XML file and DTD which can be found at the HERE.
I have written a code, but it works till one level, then it doesnot works properly. I have also created certain objects to store the value of the xml file. But i am only able to traverse till sheet tag of the xml, then it doesnot works properly.
Recon recon = new Recon();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(configFile);
doc.getDocumentElement().normalize();
System.out.println("Root Element : " + doc.getDocumentElement().getNodeName());
String outputPath = doc.getDocumentElement().getAttribute("outputPath");
String withCompareFilePath = doc.getDocumentElement().getAttribute("withCompareFile");
String toCompareFilePath = doc.getDocumentElement().getAttribute("toCompareFile");
recon.setOutputPath(outputPath);
recon.setToCompareFile(new File(toCompareFilePath));
recon.setWithCompareFile(new File(withCompareFilePath));
NodeList sheetNodeList = doc.getElementsByTagName("sheet");
List<ReconSheet> reconSheets = new ArrayList<ReconSheet>();
for(int i = 0; i< sheetNodeList.getLength() ; i++) {
Node tempNode = sheetNodeList.item(i);
ReconSheet reconSheet = new ReconSheet();
NamedNodeMap attMap = tempNode.getAttributes();
Node sheetNode = attMap.getNamedItem("sheetNumber");
String sheetNumber = sheetNode.getNodeValue();
reconSheet.setSheetNumber(Integer.parseInt(sheetNumber));
NodeList list = tempNode.getChildNodes();
for(int j = 0; j< list.getLength(); j++) {
Node inNode = list.item(j);
System.out.println(inNode);
}
}
A:
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You could map your XML directly to your domain model using a JAXB implementation. JAXB requires Java SE 5, and a JAXB implementation is included in Java SE 6.
Recon
Your Recon class would look something like:
package forum7673323;
import java.io.File;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Recon {
@XmlAttribute
private String outputPath;
@XmlAttribute
@XmlJavaTypeAdapter(FileAdapter.class)
private File withCompareFile;
@XmlAttribute
@XmlJavaTypeAdapter(FileAdapter.class)
private File toCompareFile;
@XmlElement(name="sheet")
private List<ReconSheet> reconSheets;
}
ReconSheet
package forum7673323;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
@XmlAccessorType(XmlAccessType.FIELD)
public class ReconSheet {
@XmlAttribute
int sheetNumber;
}
FileAdapter
Since a JAXB implementation can not interact with a java.io.File object directly we will use a JAXB adapter to handle this conversion. The use of this adapter is specified on the Recon class using the @XmlJavaTypeAdapter annotation:
package forum7673323;
import java.io.File;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class FileAdapter extends XmlAdapter <String, File>{
@Override
public String marshal(File file) throws Exception {
if(null == file) {
return null;
}
return file.getPath();
}
@Override
public File unmarshal(String path) throws Exception {
return new File(path);
}
}
Demo
package forum7673323;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Recon.class);
File xml = new File("src/forum7673323/input.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Recon recon = (Recon) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(recon, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recon toCompareFile="h:\work\two.xls" withCompareFile="h:\work\one.xls" outputPath="h:/work">
<sheet sheetNumber="1"/>
</recon>
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I include a mPDF file?
I have no problem creating PDF with mPDF as bellow:
$html = '
// Here's the HTML table code
';
$mpdf->WriteHTML($html,2);
But how can I include files here?
$html = '
include(files.php)
';
OR
$mpdf->WriteHTML(file.php,2);
where file.php file has HTML and php codes
A:
You could use following to retrieve the html from the target php file and write it to PDF:
<?php
ob_start();
include "files.php";
$html = ob_get_clean();
$mpdf->WriteHTML($html, 2);
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Error Finding Method in DLLImport
I have a C++ assembly that I am importing using DLLImport.
I am attempting to call its method:
namespace Testing
{
class Test{
int Run(char* filePath, bool bEntry, double duration){//code}
};
}
by
[DllImport(dllName, CharSet = CharSet.Auto)]
public static extern int Run(string filePath, bool bEntry, double duration)
);
When I call its method, I get the error message:
Unable to find an entry point named Run in dll
A:
The "Run" looks to be a non-static class method. Although, it's possible to call such methods from C# this is not the primary use-case. It would be way easier to consume it from .NET if you expose it via COM, or at-least as a plain C interface:
extern "C" __declspec(dllexport) void* Testing_Test_Create();
extern "C" __declspec(dllexport) void Testing_Test_Destroy(void* self);
extern "C" __declspec(dllexport) int Testing_Test_Run(void* self, char* filePath, bool bEntry, double duration);
And here is a sample how to call C++ class methods from C#:
// Test.cpp in NativeLib.dll
namespace Testing
{
class __declspec(dllexport) Test
{
public:
explicit Test(int data)
: data(data)
{
}
int Run(char const * path)
{
return this->data + strlen(path);
}
private:
int data;
};
}
// Program.cs in CSharpClient.exe
class Program
{
[DllImport(
"NativeLib.dll",
EntryPoint = "??0Test@Testing@@QAE@H@Z",
CallingConvention = CallingConvention.ThisCall,
CharSet = CharSet.Ansi)]
public static extern void TestingTestCtor(IntPtr self, int data);
[DllImport(
"NativeLib.dll",
EntryPoint = "?Run@Test@Testing@@QAEHPBD@Z",
CallingConvention = CallingConvention.ThisCall,
CharSet = CharSet.Ansi)]
public static extern int TestingTestRun(IntPtr self, string path);
static void Main(string[] args)
{
var test = Marshal.AllocCoTaskMem(4);
TestingTestCtor(test, 10);
var result = TestingTestRun(test, "path");
Console.WriteLine(result);
Marshal.FreeCoTaskMem(test);
}
}
Entry point names might be different for your build configuration/compiler, so use dumpbin utility to obtain them. Again, this is just a proof of concept, in real code it would be better to use COM.
| {
"pile_set_name": "StackExchange"
} |
Q:
Make [off-topic] on-topic
Here in Meta IPS, we have off-topic and scope
off-topic has only 10 questions, while scope has 40 questions. Thus, it makes sense to merge off-topic to scope.
What do you say?
A:
Done.
I haven't seen on-topic or allowed-questions show up here (yet), but if they do, they should be merged, too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does everybody recommend Dban over more fundamental methods?
When people ask on how to wipe a drive, it almost seems as if the default answer is DBAN and I am not really sure why. Especially when doing commands like
dd if=/dev/zero of=/dev/sda
dd if=/dev/urandom of=/dev/sda
dcfldd pattern="00" of=/dev/sda
dcfldd pattern="FF" of=/dev/sda
shred /dev/sda
wipe /dev/sda
cat /dev/sda | cat > /dev/sda
etc
All of these will do the exact same thing and using a tool like hdparm to execute a secure-erase command will be much better than all of the above. Given that it will also erase those blocks on the glist,
So what makes Dban so good and so recommended. Is there a technical reason why it is recommended? To me it seems like a waste of bandwidth and a blank cd.
A:
The technical reason is it's much more straightforward. When trying to erase data, the last thing you want to do is make a mistake, which is far more likely with a series of commands than running a single program. You might target the wrong drive, or get distracted halfway through, or not perform the steps in the best order. With DBAN, you know for sure that all the drives connected to the machine will be securely erased.
A:
I think mostly because dban actually gives you a GUI and progress bar. DD works, but for some people it could be nerve-wrecking to just type and not see anything happens, until it does. Technically speaking, I think dban has enough features to wipe a drive safely.
A:
I use it for all the reasons already stated, but I have one BIG additional one. My auditors KNOW what it is and have approved it for fulfilling the secure disposal requirement. Being able to say "We use DBAN" and the auditor going "Ok, lets move on" is worlds better than "I use this custom script" which would trigger, ok let me see it work, Explain each of these commands, wipe a disk and give to me to audit. That's 30 seconds compared to what could be hours and still the possibility of it not getting their ok.
| {
"pile_set_name": "StackExchange"
} |
Q:
React CRA - Images Ecosystem
When using create-react-app, in what directory should my images folder be?
in src or public?
Will one or the other present issues when I'm ready to run yarn build?
I heard that only files placed in public directory will be loaded after a build. True or False?
I guess this comment by the react team on index.html has me confused.
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder
during the build.
Only files inside the `public` folder can be referenced from
the HTML.
Unlike "/favicon.ico" or "favicon.ico",
"%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
EDIT: After reading the comments below this is how structured my images folder inside the src folder.
Can you please tell me if this is a good/best practice?
**Images Component**
import Foo from "./images/foo.jpg";
import Bar from "./images/bar.jpg";
import './styles/Images.css';
export const Logo = () => (
<img src={Foo} alt="bla bla" />
)
export const Profile = () => (
<img src={Bar} alt="bla bla" />
)
A component that I want to use the images.
import { Logo, Profile } from './Images';
const Home = () => (
<div>
<Logo/>
<Profile/>
</div>
)
A:
You should create a folder under src for the images. Then just use
import './myImage.png' as imageThatIsMine to import them into a .js file.
In a .css you would use
.myClass {
background-image: url('./myImage.png')
}
Doing it this will insure that webpack correctly moves the file to the build folder and appends the correct paths.
See the docs for more info.
If you place anything outside of the src folder and try to import you will get an error telling you to use src.
You can place items in the ;public' folder but it is not recommend. See docs
If you do use the public folder you will need to prefix with %PUBLIC_URL% when you use them.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pandas date ranges and averaging the counts
I have the below pandas dataframe
stdate enddate count
2004-01-04 2004-01-10 68
2004-01-11 2004-01-17 100
2004-01-18 2004-01-24 83
2004-01-25 2004-01-31 56
2004-02-01 2004-02-07 56
2004-02-08 2004-02-14 68
2004-02-15 2004-02-21 81
2004-02-22 2004-02-28 68
2004-02-29 2004-03-06 76
I want to take an average of the count based on the month:
that is I wanted it like:
date count
2004-01 (306/25-4)
2004-02 (349/28-01)
for example the second month as the enddate 3, (I need help in aggregarting this counts using pandas)
A:
It's not that complicated, but there is a bit of work, and I think you should ditch pandas for most of the calculation, and build a dataframe right at the end.
Suppose you have two datetime objects, b and e. The difference between them in days is
(e - b).days
This gives you how the count of a row is divided by days.
Also, given a month, you can find the last day of the month using the calendar module.
So, you could do the following:
counts_per_month = {}
def process_row(b, e, count):
...
# Find how count splits between the months,
# update counts_per_month accordingly
Now call
df.apply(lambda r: process_row(r.stdate, r.enddate, r.count), axis=1)
at which point counts_per_month will contain your data. Finish off by calling pd.DataFrame.from_dict.
| {
"pile_set_name": "StackExchange"
} |
Q:
Chai-Http always returns 404 error code
So basically, I have this rest api written off Node and Express using Typescript. I am trying to use chai, chai-http and mocha to get the api endpoints tested. But whichever test runs, I always get a 404 not found. Here is my code:
app.ts:
let mongodbURI;
if (process.env.NODE_ENV === "test") {
mongodbURI = process.env.MONGODB_TEST_URI;
} else {
mongodbURI = process.env.MONGODB_URI;
}
mongoose.Promise = global.Promise;
const mongodb = mongoose.connect(mongodbURI, { useMongoClient: true });
mongodb
.then(db => {
setRoutes(app);
if (!module.parent) {
app.listen(app.get("port"), () => { });
}
})
.catch(err => {
console.error(err);
});
export { app };
routes.ts:
export default function setRoutes(app) {
const router = express.Router();
const userCtrl = new UserCtrl();
router.post('/register', userCtrl.createUser);
{ .... }
app.use('/api/v1', router);
}
user.spec.ts:
const should = chai.use(chaiHttp).should();
describe("Users", () => {
it("should create new user", done => {
const user = new User({
name: "testuser",
email: "[email protected]",
mobile: "1234567890",
password: "test1234"
});
chai
.request(app)
.post("/api/v1/register")
.send(user)
.end((err, res) => {
res.should.have.status(200);
done();
});
});
});
Not alone this but any route I try, I get a 404 error. What am I doing wrong here?
EDIT: Hope it doesn't matter but I use mocha for running tests.
A:
It looks as though you're establishing your routes asynchronously (they are only established after your mongodb instance has been connected). This is likely to be part of the problem, I'd recommend moving the setRoutes(app) part outside of the promise chain, and instead you can allow each route to await for the mongodb connection:
app.ts
let mongodbURI;
if (process.env.NODE_ENV === "test") {
mongodbURI = process.env.MONGODB_TEST_URI;
} else {
mongodbURI = process.env.MONGODB_URI;
}
mongoose.Promise = global.Promise;
const mongodb = mongoose.connect(mongodbURI, { useMongoClient: true });
mongodb
.then(db => {
if (!module.parent) {
app.listen(app.get("port"), () => { });
}
})
.catch(err => {
console.error(err);
});
// setRoutes goes here, not inside a Promise
setRoutes(app);
export { app };
| {
"pile_set_name": "StackExchange"
} |
Q:
In C#, how can I serialize System.Exception? (.Net CF 2.0)
I want to write an Exception to an MS Message Queue. When I attempt it I get an exception. So I tried simplifying it by using the XmlSerializer which still raises an exception, but it gave me a bit more info:
{"There was an error reflecting type
'System.Exception'."}
with InnerException:
{"Cannot serialize member
System.Exception.Data of type
System.Collections.IDictionary,
because it implements IDictionary."}
Sample Code:
Exception e = new Exception("Hello, world!");
MemoryStream stream = new MemoryStream();
XmlSerializer x = new XmlSerializer(e.GetType()); // Exception raised on this line
x.Serialize(stream, e);
stream.Close();
EDIT:
I tried to keep this a simple as possible, but I may have overdone it. I want the whole bit, stack trace, message, custom exception type, and custom exception properties. I may even want to throw the exception again.
A:
I was looking at Jason Jackson's answer, but it didn't make sense to me that I'm having problems with this even though System.Exception implements ISerializable. So I bypassed the XmlSerializer by wrapping the exception in a class that uses a BinaryFormatter instead. When the XmlSerialization of the MS Message Queuing objects kicks in all it will see is a class with a public byte array.
Here's what I came up with:
public class WrappedException {
public byte[] Data;
public WrappedException() {
}
public WrappedException(Exception e) {
SetException(e);
}
public Exception GetException() {
Exception result;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream(Data);
result = (Exception)bf.Deserialize(stream);
stream.Close();
return result;
}
public void SetException(Exception e) {
MemoryStream stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, e);
Data = stream.ToArray();
stream.Close();
}
}
The first test worked perfectly, but I was still concerned about custom exceptions. So I tossed together my own custom exception. Then I just dropped a button on a blank form. Here's the code:
[Serializable]
public class MyException : Exception, ISerializable {
public int ErrorCode = 10;
public MyException(SerializationInfo info, StreamingContext context)
: base(info, context) {
ErrorCode = info.GetInt32("ErrorCode");
}
public MyException(string message)
: base(message) {
}
#region ISerializable Members
void ISerializable.GetObjectData(SerializationInfo info,
StreamingContext context) {
base.GetObjectData(info, context);
info.AddValue("ErrorCode", ErrorCode);
}
#endregion
}
private void button1_Click(object sender, EventArgs e) {
MyException ex = new MyException("Hello, world!");
ex.ErrorCode = 20;
WrappedException reply = new WrappedException(ex);
XmlSerializer x = new XmlSerializer(reply.GetType());
MemoryStream stream = new MemoryStream();
x.Serialize(stream, reply);
stream.Position = 0;
WrappedException reply2 = (WrappedException)x.Deserialize(stream);
MyException ex2 = (MyException)reply2.GetException();
stream.Close();
Text = ex2.ErrorCode.ToString(); // form shows 20
// throw ex2;
}
Although it seemed like all of other exception types that I looked up are marked with the SerializableAttribute, I'm going to have to be careful about custom exceptions that are not marked with the SerializableAttribute.
EDIT: Getting ahead of myself. I didn't realize that BinaryFormatter is not implemented on CF.
EDIT: Above code snippets were in a desktop project. In the CF version, the WrappedException will basically look the same I just need to implement my own BinaryFormater, but I'm very open to suggestions on that one.
A:
I think you basically have two options:
Do your own manual serialization (probably do NOT want to do that). XML serialization will surely not work due to the exact message you get in the inner exception.
Create your own custom (serializable) exception class, inject data from the thrown Exception into your custom one and serialize that.
A:
Commentary:
Serializing exceptions is a common task when remoting or interacting with systems across process boundaries. Don't listen to anyone who says otherwise; they have probably never written a remoting library.
Solution:
I have plumbed remoting to do this before by creating a custom, base exception class. The problem I ran into was that System.Exception does not serialize easily so I had to inherit from it. The way I handled this was by creating my own exceptions that did serialize (through ISerializable), and wrapped any System.Exception in a custom exception.
Throughout your server code you should use custom exceptions anyway, and these can all be based on your serializable base type. It is not much work, and you will quickly build up a common library of exceptions to through.
The layer you write out to the queue (and read from) should do all the exception serialization/hydration. You might consider something like this:
public class WireObject<T, E>
{
public T Payload{get;set;}
public E Exception{get;set;}
}
The server and client layers that talk to your queue will wrap the object you are sending in the Payload, or attach an exception (if any). When the data is consumed from the queue, the client layer can check for an exception and re-throw it if present, else hand you your data.
This is a very simple version of what I have written before, and what I have seen others write. Good luck on your project.
| {
"pile_set_name": "StackExchange"
} |
Q:
symfony routing problem
Please help a symfony noob with a basic question about routing an URLs..
I would like to be able to have nice urls in the following format:
shop/category/:name
and in my routing.yml i have:
shop_category:
url: /shop/category/:name/
param: { module: shop, action: category }
class: sfDoctrineRoute
options: { model: Category, type: object }
in my indexSuccess.php view i have:
<?php foreach($categories as $category) { ?>
<a href="<?php url_for('shop_category',$category)?>">link</a>
<?php } ?>
but the href link does not render when i mouse over the link..
what am i doing wrong?
A:
url_for() helper doesn't echo generated URL, it returns it. So simply add echo instruction:
<?php echo url_for(...) ?>
| {
"pile_set_name": "StackExchange"
} |
Q:
ecma2015 extend classes javascript
I want to do some extending in ecma2015 and i can't seem to understand how it works. I have written a method in plain JavaScript just like $.extend(), but i wanted to upgrade my code to classes.
Here is the following sample code that i tried.
var Test = ((window, document, undefined) => {
class Defaults {
constructor(options) {
this.options = options || {};
this.options.name = 'name';
this.options.age = '23';
}
}
class Test extends Defaults {
constructor(selector, options) {
super();
this.selector = document.querySelector(selector);
this.options = options;
}
createTest() {
var div = document.createElement('div');
this.selector.appendChild(div);
}
}
return Test;
})(window, document);
And after i called it like this:
var test = new Test('#test', {
name: 'nameInInstance'
});
test.createTest();
document.querySelector('#test').innerHTML = JSON.stringify(test.options);
Now what i see is just the name from the instance.
Why isn't age passed to the child Class ?
What am i missing ?
A:
Your Test constructor a) doesn't pass the options to the super call b) just overwrites the .options property with the argument, not caring for any defaults. You should be doing
class Test extends Defaults {
constructor(selector, options) {
super(options);
this.selector = document.querySelector(selector);
}
…
That said, your Defaults class doesn't exactly use best practises either. It does mutate its arguments, which no constructor should do, and most importantly the defaults always override the passed-in options while you actually want it the other way round. You should manually copy them over:
class Defaults {
constructor(options) {
this.options = Object.assign({
name: 'name',
age: '23'
}, options);
}
}
And I would recommend not to use inheritance here at all, since Defaults is only used as a super class for Test, it should have been merged into it or have become a simple helper function; but let's assume you were only doing this for demonstration purposes.
| {
"pile_set_name": "StackExchange"
} |
Q:
$q notify and -1 promise state status
From what I've seen in $q source code, promise.$$state.status can be equal to -1. This is related somehow to notify functionality.
On what conditions promise state status can be equal to -1, and what is its place in Angular promise life cycle?
A:
I've acquired status -1 with resolving a promise with another promise.
x = $q.defer();
y = $q.defer();
x.resolve(y.promise);
According to code, x changed status to -1 to wait for resolving promise y. But event after resolving y, x status still -1.
After tracing all chain of Promises() that are bind together with resolves - the final promise results with promise.then only of final one that is resolved with actually something (isObject(val)).
In this case -1 status can be acquired only when:
You created link to non-final Promise() in chain
You used link's status that is always -1
The -1 part in life cycle of promises is only determination that current promise in chain is not final and any next promise. This can be traced in function done() where for stack of promises created one resolution that updates its $$values with previous ones.
In chain status 0 or 1 pointing final promise that will be taken as final point.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i split up the results of this hashtable search?
I'm trying to use this to compare my AD NT hashdump with https://haveibeenpwned.com/Passwords hashes.
I'm having trouble with the results grouping multiple usernames with the same password together.
the code:
param(
[Parameter(Mandatory = $true)]
[System.IO.FileInfo] $ADNTHashes,
[Parameter(Mandatory = $true)]
[System.IO.FileInfo] $HashDictionary
)
#>
process {
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
#Declare and fill new hashtable with ADNThashes. Converts to upper case to
$htADNTHashes = @{}
Import-Csv -Delimiter ":" -Path $ADNTHashes -Header "User","Hash" | % {$htADNTHashes[$_.Hash.toUpper()] += @($_.User)}
#Create empty output object
$mrMatchedResults = @()
#Create Filestream reader
$fsHashDictionary = New-Object IO.Filestream $HashDictionary,'Open','Read','Read'
$frHashDictionary = New-Object System.IO.StreamReader($fsHashDictionary)
#Iterate through HashDictionary checking each hash against ADNTHashes
while (($lineHashDictionary = $frHashDictionary.ReadLine()) -ne $null) {
if($htADNTHashes.ContainsKey($lineHashDictionary.Split(":")[0].ToUpper())) {
$foFoundObject = [PSCustomObject]@{
User = $htADNTHashes[$lineHashDictionary.Split(":")[0].ToUpper()]
Frequency = $lineHashDictionary.Split(":")[1]
Hash = $linehashDictionary.Split(":")[0].ToUpper()
}
$mrMatchedResults += $foFoundObject
}
}
$stopwatch.Stop()
Write-Verbose "Function Match-ADHashes completed in $($stopwatch.Elapsed.TotalSeconds) Seconds"
}
end {
$mrMatchedResults
}
}
I tried commenting out | % {$htADNTHashes[$_.Hash.toUpper()] += @($_.User)} which seems to be close, but that somehow removed the Frequency column.
The results look like this:
User Frequency Hash
---- --------- ----
{TestUser2, TestUser3} 20129 H1H1H1H1H1H1H1H1H1H1H1H1H1H1H1H1
{TestUser1} 1 H2H2H2H2H2H2H2H2H2H2H2H2H2H2H2H2
I would like them separated:
User Frequency Hash
---- --------- ----
{TestUser2} 20129 H1H1H1H1H1H1H1H1H1H1H1H1H1H1H1H1
{TestUser3} 20129 H1H1H1H1H1H1H1H1H1H1H1H1H1H1H1H1
{TestUser1} 1 H2H2H2H2H2H2H2H2H2H2H2H2H2H2H2H2
i'm sure this is a simple change, but i have very little powershell experience.
The suggestion to change $FormatEnumerationLimit to -1 is not what i want either, that just fixes the list truncating.
{user1, user2, user3...}
A:
while (($lineHashDictionary = $frHashDictionary.ReadLine()) -ne $null) {
if($htADNTHashes.ContainsKey($lineHashDictionary.Split(":")[0].ToUpper())) {
$Users = $htADNTHashes[$lineHashDictionary.Split(":")[0].ToUpper()]
foreach($User in $Users){
$foFoundObject = [PSCustomObject]@{
User = $User
Frequency = $lineHashDictionary.Split(":")[1]
Hash = $linehashDictionary.Split(":")[0].ToUpper()
}
$mrMatchedResults += $foFoundObject
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Reverse Spectrogram A La Aphex Twin in MATLAB
I'm trying to convert an image into an audio signal in MATLAB by treating it as a spectrogram as in Aphex Twin's song on Windowlicker. Unfortunately, I'm having trouble getting a result.
Here it what I have at the moment:
function signal = imagetosignal(path, format)
% Read in the image and make it symmetric.
image = imread(path, format);
image = [image; flipud(image)];
[row, column] = size(image);
signal = [];
% Take the ifft of each column of pixels and piece together the real-valued results.
for i = 1 : column
spectrogramWindow = image(:, i);
R = abs(ifft(spectrogramWindow));
% Take only the results for the positive frequencies.
signalWindow = R(1 : row / 2.0);
signal = [signal; signalWindow];
end
end
So, I'm taking Inverse Fourier Transforms on columns of my image and then putting them together to form a signal. Also, this function uses the Image Processing Toolbox for MATLAB to read in images. The goal is to have some variation of
spectrogram(imagetosignal('image', 'bmp'));
result in something that looks like the original image. I would very much appreciate any help! I'm just learning signal processing, so don't be surprised if there's an obvious misconception. Thanks!
Edit: Thanks Dave! I got it working! I ended up with this:
function signal = imagetosignal(path, format)
% Read in the image and make it symmetric.
image = imread(path, format);
image = [image; flipud(image)];
[row, column] = size(image);
signal = [];
% Take the ifft of each column of pixels and piece together the results.
for i = 1 : column
spectrogramWindow = image(:, i);
signalWindow = real(ifft(spectrogramWindow));
signal = [signal; signalWindow];
end
end
A:
There are some small misconceptions here.
I'll go through the problems in order of occurrence, not severity:
1) Off-by-one error in the calculation of spectrogramWindow (image)
The first array entry ought to be the component of 0Hz, the next is N Hz. The final element of the array should be the component of -N Hz. However, you've calculated 0Hz.
I'm not sure the matlab syntax, but if you flip the image as you have, and then strip the top and bottom lines before appending it to the original, you should be set.
Alternatively, you could consider NOT appending the image to itself, and after extracting spectrogramWindow from image, applying some function to make it Hermitian symmetric.
2) Taking the abs of the IFT. No need. Don't do that.
What you get out of the iFFT, if the iFFT gets the right input, is completely real.
You're seeing complex values out because the input isn't ACTUALLY Hermitian symmetric, as described above. Never use Abs(). If you must cheat, extract the Real part, which won't fold in garbage from the imaginary component.
3) You're throwing away the second half of the signal.
Once you get output from the iFFT, that represents the signal you've asked for. Don't think of it in terms of frequencies, it's now an audio time-series. Keep the whole thing.
Here's how I see it going:
spectrogramWindow = image(:, i);
spectrogramWindow = [spectrogramWindow;reverse(spectrogramWindow(skip first and last))]
signalWindow = ifft(spectrogramWindow);
signal = [signal; signalWindow];
| {
"pile_set_name": "StackExchange"
} |
Q:
Mostrar solamente Personas que tengan un valor en concreto (Firebase)
Tengo un recyclerview que cargo desde una database que tengo en Firebase, lo hago así:
databaseReference.child("Personas").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
listPersonas.add(dataSnapshot.getValue(Personas.class));
displayPersonas(listPersonas);
}
En Firebase sería algo así,
Personas/id/
datospersona: valor
mostrar: valor
Pues lo que me gustaría conseguir es que cuando el valor de mostrar sea por ejemplo true ese item no se muestre en recyclerview los demás que no tengan ese valor en mostrar sí.
¿Cómo podría realizar esto? Gracias!
A:
Resumiendo los comentarios:
A la lista Personas que maneja el recyclerview puedes filtrarla segun el atributo mostrar, creando una nueva lista la cual le pasarias a tu metodo displayPersonas
De esa manera tu listaPersonas se mantiene siempre igual y en la view presentas un listado filtrado.
Eso lo puedes lograr simplemente iterando y agregando los elementos cuyo mostrar == true
databaseReference.child("Personas").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
listPersonas.add(dataSnapshot.getValue(Personas.class));
displayPersonas(filtrarPersonas(listPersonas));
}
private List<Persona> filtrarPersonas(List<Persona> original){
List<Persona> personasAMostrar = new ArrayList<Persona>():
if(original!=null){
for(Persona p : original){
if(p.getMostrar()){
personasAMostrar.add(p); // o add(p.clone()), podria interesarte tener la misma referencia o no, eso depende de la logica de negocio de tu app
}
}
}
return personasAMostrar;
}
EDIT: Si no te interesa mantener listaPersonas con las personas con mostrar = false puedes evitar filtrar la lista y simplemente no agregar esos elementos:
databaseReference.child("Personas").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Persona p = dataSnapshot.getValue(Personas.class);
if(p.getMostrar()){
listPersonas.add(p);
}
displayPersonas(listPersonas);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Online Database WebApp / Service
i'm experimenting by mounting a website hosted on my Dropbox Public folder. Files can my accesed and I used my domain name to redirect to de index.html public url.
I can run javascript, bootstrap, jquery and that stuff but not php (for obvious security reasons of dropbox).
I would like to save data from the website. We all know that JScript is not allowed to write files or anything outsite the browser or the webpage itself.
I've been searching for a webapp/service that provides me a database or something like that let me save data from javascript. Somethingthat get connected to my host and gives me an API to the service or something like that.
Anyone heard about something like this? Or any other way I can get data saved? (serializing a JS object to a file would be just enought to me)
A:
From experience,
If you stick with trying to host something on Dropbox or anything that was not purpose meant for that, you will continually run into problems like this.
In the end spending (wasting) more time, energy and money on workarounds, rather than having fun in a real hosted environment (cloud based is more fun than DB!)
Do yourself a favor and move to a hosting platform, and spend that energy more wisely in creating a website or product (maybe that will make you money even)
There are plenty of free hosting platforms to get your started.
A quick serach on Google:
http://appfog.com/
https://pagodabox.com/
| {
"pile_set_name": "StackExchange"
} |
Q:
Составление планов на будущее.
Решил составить небольшие планы на ближайшее будущее и хочу с вами, дорогие друзья, посоветоваться.
Есть несколько вариантов и нужно выбрать что - то, что сейчас актуально и максимально востребованно (в том числе полезно в команде). Я для себя накидал пару вариантов, но мне так же очень интересны Ваши.
1. Учиться верстать (что мне не очень нравится и даже угнетает, хотя, местами получается неплохо), после чего учиться работать с ЦМСками (натягивать вёрстку, писать плагины и прочее) и... Вроде всё, дальше тут некуда развиваться, походу.
2. Оставить вёрстку как есть, на среднем уровне и изучать PHP (знаю на уровне "ниже среднего"), после того, как почувствую себя уверенно можно будет взяться за какой - нибудь микрофреймворк/фреймворк.
3. Начать изучать dJango или Рельсы (отзываются о них очень хорошо, но разницы особой не вижу) и работать только с этими фреймворками.
4. Ну и в конец безумный для меня вариант (ибо кажется непростым. Но, не исключаю, что на деле будет проще) - браться за C# и осваивать платформу .net.
Вот несколько путей моего "развития". Нужно так же учитывать, что базовые навыки у меня есть (HTML + CSS, JS, PHP, etc...).
Очень интересно ваше мнение!
A:
если на ближайшее то почти все верно спланировал. Только когда дойдешь до php всрстку оставлять не нужно. И так с любыми пройденными технологиями. Пока изучаешь новое параллельно совершенствуешь старое, иначе не преуспеешь.
| {
"pile_set_name": "StackExchange"
} |
Q:
Select nth row after orderby in pyspark dataframe
I want to select the second row for each group of names. I used orderby to sort by name and then the purchase date/timestamp. It is important that I select the second purchase for each name (by datetime).
Here is the data to build dataframe:
data = [
('George', datetime(2020, 3, 24, 3, 19, 58), datetime(2018, 2, 24, 3, 22, 55)),
('Andrew', datetime(2019, 12, 12, 17, 21, 30), datetime(2019, 7, 21, 2, 14, 22)),
('Micheal', datetime(2018, 11, 22, 13, 29, 40), datetime(2018, 5, 17, 8, 10, 19)),
('Maggie', datetime(2019, 2, 8, 3, 31, 23), datetime(2019, 5, 19, 6, 11, 33)),
('Ravi', datetime(2019, 1, 1, 4, 19, 47), datetime(2019, 1, 1, 4, 22, 55)),
('Xien', datetime(2020, 3, 2, 4, 33, 51), datetime(2020, 5, 21, 7, 11, 50)),
('George', datetime(2020, 3, 24, 3, 19, 58), datetime(2020, 3, 24, 3, 22, 45)),
('Andrew', datetime(2019, 12, 12, 17, 21, 30), datetime(2019, 9, 19, 1, 14, 11)),
('Micheal', datetime(2018, 11, 22, 13, 29, 40), datetime(2018, 8, 19, 7, 11, 37)),
('Maggie', datetime(2019, 2, 8, 3, 31, 23), datetime(2018, 2, 19, 6, 11, 42)),
('Ravi', datetime(2019, 1, 1, 4, 19, 47), datetime(2019, 1, 1, 4, 22, 17)),
('Xien', datetime(2020, 3, 2, 4, 33, 51), datetime(2020, 6, 21, 7, 11, 11)),
('George', datetime(2020, 3, 24, 3, 19, 58), datetime(2020, 4, 24, 3, 22, 54)),
('Andrew', datetime(2019, 12, 12, 17, 21, 30), datetime(2019, 8, 30, 3, 12, 41)),
('Micheal', datetime(2018, 11, 22, 13, 29, 40), datetime(2017, 5, 17, 8, 10, 38)),
('Maggie', datetime(2019, 2, 8, 3, 31, 23), datetime(2020, 3, 19, 6, 11, 12)),
('Ravi', datetime(2019, 1, 1, 4, 19, 47), datetime(2018, 2, 1, 4, 22, 24)),
('Xien', datetime(2020, 3, 2, 4, 33, 51), datetime(2018, 9, 21, 7, 11, 41)),
]
df = sqlContext.createDataFrame(data, ['name', 'trial_start', 'purchase'])
df.show(truncate=False)
I order the data by name and then purchase
df.orderBy("name","purchase").show()
to produce the result:
+-------+-------------------+-------------------+
| name| trial_start| purchase|
+-------+-------------------+-------------------+
| Andrew|2019-12-12 22:21:30|2019-07-21 06:14:22|
| Andrew|2019-12-12 22:21:30|2019-08-30 07:12:41|
| Andrew|2019-12-12 22:21:30|2019-09-19 05:14:11|
| George|2020-03-24 07:19:58|2018-02-24 08:22:55|
| George|2020-03-24 07:19:58|2020-03-24 07:22:45|
| George|2020-03-24 07:19:58|2020-04-24 07:22:54|
| Maggie|2019-02-08 08:31:23|2018-02-19 11:11:42|
| Maggie|2019-02-08 08:31:23|2019-05-19 10:11:33|
| Maggie|2019-02-08 08:31:23|2020-03-19 10:11:12|
|Micheal|2018-11-22 18:29:40|2017-05-17 12:10:38|
|Micheal|2018-11-22 18:29:40|2018-05-17 12:10:19|
|Micheal|2018-11-22 18:29:40|2018-08-19 11:11:37|
| Ravi|2019-01-01 09:19:47|2018-02-01 09:22:24|
| Ravi|2019-01-01 09:19:47|2019-01-01 09:22:17|
| Ravi|2019-01-01 09:19:47|2019-01-01 09:22:55|
| Xien|2020-03-02 09:33:51|2018-09-21 11:11:41|
| Xien|2020-03-02 09:33:51|2020-05-21 11:11:50|
| Xien|2020-03-02 09:33:51|2020-06-21 11:11:11|
+-------+-------------------+-------------------+
How might I get the second row for each name? In pandas it was easy. I could just use nth. I have been looking at sql but have not found a solution. Any suggestions appreciated.
The output I am looking for would be:
+-------+-------------------+-------------------+
| name| trial_start| purchase|
+-------+-------------------+-------------------+
| Andrew|2019-12-12 22:21:30|2019-08-30 07:12:41|
| George|2020-03-24 07:19:58|2020-03-24 07:22:45|
| Maggie|2019-02-08 08:31:23|2019-05-19 10:11:33|
|Micheal|2018-11-22 18:29:40|2018-05-17 12:10:19|
| Ravi|2019-01-01 09:19:47|2019-01-01 09:22:17|
| Xien|2020-03-02 09:33:51|2020-05-21 11:11:50|
+-------+-------------------+-------------------+
A:
Try with window row_number() function then filter only the 2 row after ordering by purchase.
Example:
from pyspark.sql import *
from pyspark.sql.functions import *
w=Window.partitionBy("name").orderBy(col("purchase"))
df.withColumn("rn",row_number().over(w)).filter(col("rn") ==2).drop(*["rn"]).show()
SQL Api:
df.createOrReplaceTempView("tmp")
spark.sql("SET spark.sql.parser.quotedRegexColumnNames=true")
sql("select `(rn)?+.+` from (select *,row_number() over(partition by name order by purchase) rn from tmp) e where rn =2").\
show()
| {
"pile_set_name": "StackExchange"
} |
Q:
Android notifyDataSetChanged not working
I have an adapter which fills a ListView with 2 TextViews with data from a TreeMap.
When the user adds or deletes Data from the ListView, the View should be refreshed.
So here is my Adapter:
public class MyAdapter extends BaseAdapter {
private final ArrayList mData;
public MyAdapter(Map<String, String> map) {
mData = new ArrayList();
mData.addAll(map.entrySet());
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Map.Entry<String, String> getItem(int position) {
return (Map.Entry) mData.get(position);
}
@Override
public long getItemId(int position) {
// TODO implement you own logic with ID
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View result;
if (convertView == null) {
result = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_adapter_item, parent, false);
} else {
result = convertView;
}
Map.Entry<String, String> item = getItem(position);
// TODO replace findViewById by ViewHolder
((TextView) result.findViewById(android.R.id.text1)).setText(item.getKey());
((TextView) result.findViewById(android.R.id.text2)).setText(item.getValue());
return result;
}}
Because I want to update the view from a dialog and on another question I read, that notifyDataSetChanged() needs to be called from the UIThread I put my notifyDataSetChanged() into a Runnable. here is it:
Runnable run = new Runnable(){
public void run(){
Log.v("in the Runnable: ", String.valueOf(colorHashMap));
adapter.notifyDataSetChanged();
}
};
And this it how the Runnable gets called in the Dialog:
DefaultColorActivity.this.runOnUiThread(run);
But I no matter what I try or do, the List just won't get updated. I need to close and reopen the activity to get the new List.
A:
create a method in your adapter like:
public void updateList(){
notifyDataSetChanged()
}
and call this method when you want to refresh the list
| {
"pile_set_name": "StackExchange"
} |
Q:
Queue or other methods to handle tick data?
In our electronic trading system, we need to do calculation based on tick data from 100+ contracts.
Tick data of contracts is not received in one message. One message only include tick data for one contract. Timestamp of contracts are slightly different (sometimes big diff, but let's ignore this case).
eg: (first column is timestamp. Second is contract name)
below 2 data has 1ms diff
10:34:03.235,10002007,510050C2006A03500 ,0.0546
10:34:03.236,10001909,510050C2003A02750 ,0.3888
below 2 data has 3ms diff
10:34:03.594,10002154,510300C2003M03700 ,0.4985
10:34:03.597,10002118,510300C2001M03700 ,0.4514
Only those with price change will have data. So I can't count contract number to know if I have received all data for this tick.
But on the other hand, we don't want to wait till we receive all data for the tick, because sometimes data could be late for long time, we will want to exclude them.
Low latency is required. So I think we will define a window - say 50 ms - and start to calculate based on whatever data we received in past 50ms.
What will be the best way to handle such use case?
Originally I want to use redis stream to maintain a small queue, that whenever a contract's data is received, I will push it to redis stream. But I couldn't figure out what's the best way to pull data as soon as specific time (say 50ms) passed.
I am thinking about maybe I should use some other technicals?
Any suggestions are appreciated.
A:
Use XRANGE myStream - + COUNT 1 to get the first entry.
Use XREVRANGE myStream + - COUNT 1 to get the last entry.
XINFO STREAM myStream also brings first and last entry, but the docs say it is O(log N).
Assuming you are using a timestamp as ID, or as a field, then you can compute the time difference.
If you are using Redis Streams auto-ID (XADD myStream * ...), the first part of the ID is the UNIX timestamp in milliseconds.
Assuming the above, you can do the check atomically with a Lua script:
EVAL "local first = redis.call('XRANGE', KEYS[1], '-', '+', 'COUNT', '1') local firstTime = {} if next(first) == nil then return redis.error_reply('Stream is empty or key doesn`t exist') end for str in string.gmatch(first[1][1], '([^-]+)') do table.insert(firstTime, tonumber(str)) end local last = redis.call('XREVRANGE', KEYS[1], '+', '-', 'COUNT', '1') local lastTime = {} for str in string.gmatch(last[1][1], '([^-]+)') do table.insert(lastTime, tonumber(str)) end local ms = lastTime[1] - firstTime[1] if ms >= tonumber(ARGV[1]) then return redis.call('XRANGE', KEYS[1], '-', '+') else return redis.error_reply('Only '..ms..' ms') end" 1 myStream 50
The arguments are numKeys(1 here) streamKey timeInMs(50 here): 1 myStream 50.
Here a friendly view of the Lua script:
local first = redis.call('XRANGE', KEYS[1], '-', '+', 'COUNT', '1')
local firstTime = {}
if next(first) == nil then
return redis.error_reply('Stream is empty or key doesn`t exist')
end
for str in string.gmatch(first[1][1], '([^-]+)') do
table.insert(firstTime, tonumber(str))
end
local last = redis.call('XREVRANGE', KEYS[1], '+', '-', 'COUNT', '1')
local lastTime = {}
for str in string.gmatch(last[1][1], '([^-]+)') do
table.insert(lastTime, tonumber(str))
end
local ms = lastTime[1] - firstTime[1]
if ms >= tonumber(ARGV[1]) then
return redis.call('XRANGE', KEYS[1], '-', '+')
else
return redis.error_reply('Only '..ms..' ms')
end
It returns:
(error) Stream is empty or key doesn`t exist
(error) Only 34 ms if we don't have the required time elapsed
The actual list of entries if the required time between first and last message has elapsed.
Make sure to check Introduction to Redis Streams to get familiar with Redis Streams, and EVAL command to learn about Lua scripts.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's an algorithm for the intersection and union of 2 AVL trees?
Any help would be appreciated.
A:
You can intersect any two sorted lists in linear time.
get the in-order (left child, then parent data, then right child) iterators for both AVL trees.
peek at the head of both iterators.
if one iterator is exhausted, return the result set.
if both elements are equal or the union is being computed, add their minimum to the result set.
pop the lowest (if the iterators are in ascending order) element. If both are equal, pop both
This runs in O(n1+n2) and is optimal for the union operation (where you are bound by the output size).
Alternatively, you can look at all elements of the smaller tree to see if they are present in the larger tree. This runs in O(n1 log n2).
This is the algorithm Google uses (or considered using) in their BigTable engine to find an intersection:
Get iterators for all sources
Start with pivot = null
loop over all n iterators in sequence until any of them is exhausted.
find the smallest element larger than the pivot in this iterator.
if the element is the pivot
increment the count of the iterators the pivot is in
if this pivot is in all iterators, add the pivot to the result set.
else
reset the count of the iterators the pivot is in
use the found element as the new pivot.
To find an element or the next largest element in a binary tree iterator:
start from the current element
walk up until the current element is larger than the element being searched for or you are in the root
walk down until you find the element or you can't go to the left
if the current element is smaller than the element being searched, return null (this iterator is exhausted)
else return the current element
This decays to O(n1+n2) for similarly-sized sets that are perfectly mixed, and to O(n1 log n2) if the second tree is much bigger. If the range of a subtree in one tree does not intersect any node in the other tree / all other trees, then at most one element from this subtree is ever visited (its minimum). This is possibly the fastest algorithm available.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Async method call all the way to Main
Can someone clarify this example, which of course, is not working:
class Program
{
static void Main(string[] args)//main cant' be async
{
int res = test();//I must put await here
Console.WriteLine("END");
}
public async static Task<int> test()
{ //why can't I make it just: public int test()??
int a1, a2, a3, a4;
a1 = await GetNumber1();
a2 = await GetNumber2();
a3 = await GetNumber3();
a4 = a1 + a2 + a3;
return a4;
}
public static async Task<int> GetNumber1()
{
await Task.Run(() =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("GetNumber1");
System.Threading.Thread.Sleep(100);
}
});
return 1;
}
I am trying to "collect" values from GenNumberX methods by using "await". I would like to make method "test" not async somehow. I dont understand why test has to be async when I am using await to get a value. This example makes me to write async on every method where I use async, and when I drill up to Main, I cannot make it async?
How to write real-world example:
public bool ReserveAHolliday()
{
bool hotelOK = await ReserveAHotel();//HTTP async request
bool flightOK = await ReserveFlight();////HTTP async request
bool result = hotelOK && flightOK;
return result;
}
How to make method ReserveAHolliday synchronous?
Am I missing something or don't understand the use of async-await mechanism?
A:
below is a full example. you can run the ReserverAHoliday both Synchronously (bool r = ReserveAHolliday().Result;) and Asynchronously (just call ReserveAHolliday();) from MAIN (depends which line you comment). and you can see the effect ("END" gets printed before / after the reservation is complete).
I prefer the await Task.WhenAll() methods, which is more readable.
also note that it's preferred to use await Task.Delay(100) instead of Thread.sleep inside GetNumber1.
class Program
{
static void Main(string[] args)//main cant' be async
{
//int res = test().Result;//I must put await here
bool r = ReserveAHolliday().Result; //this will run Synchronously.
//ReserveAHolliday(); //this option will run aync : you will see "END" printed before the reservation is complete.
Console.WriteLine("END");
Console.ReadLine();
}
public async static Task<int> test()
{ //why can't I make it just: public int test()??
//becuase you cannot use await in synchronous methods.
int a1, a2, a3, a4;
a1 = await GetNumber1();
a2 = await GetNumber1();
a3 = await GetNumber1();
a4 = a1 + a2 + a3;
return a4;
}
public static async Task<int> GetNumber1()
{
//await Task.Run(() =>
// {
for (int i = 0; i < 10; i++)
{
Console.WriteLine("GetNumber1");
await Task.Delay(100); // from what I read using Task.Delay is preferred to using System.Threading.Thread.Sleep(100);
}
// });
return 1;
}
public async static Task<bool> ReserveAHolliday()
{
//bool hotelOK = await ReserveAHotel();//HTTP async request
//bool flightOK = await ReserveAHotel();////HTTP async request
var t1 = ReserveAHotel("FirstHotel");
var t2 = ReserveAHotel("SecondHotel");
await Task.WhenAll(t1, t2);
bool result = t1.Result && t1.Result;// hotelOK && flightOK;
return result;
}
public static async Task<bool> ReserveAHotel(string name)
{
Console.WriteLine("Reserve A Hotel started for "+ name);
await Task.Delay(3000);
if (name == "FirstHotel")
await Task.Delay(500); //delaying first hotel on purpose.
Console.WriteLine("Reserve A Hotel done for " + name);
return true;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Radio button trigger with javascript
I have two radio buttons and I need first radio button to be check after window load with javascript. by using its class automatically need to be triggered
A:
Try the following way:
function manageRadioButton() {
var x = document.getElementsByClassName("radio");
x[0].checked = true;
}
<body onload="manageRadioButton()">
<input type="radio" class="radio" name="gender" value="male"> Male<br>
<input type="radio" class="radio" name="gender" value="female"> Female<br>
</body>
| {
"pile_set_name": "StackExchange"
} |
Q:
Copy text inside of any tag to clipboard using JS
I need to copy the text that is inside of ~p~ tag, I've tryed using this code:
HTML:
<p id="copy">Text to copy</p>
<button onclick="copyFunction()">Copy text</button>
JS:
function copyFunction() {
var textToCopy = document.getElementById("copy");
textToCopy.select();
document.execCommand("copy");
alert("Copied the text: " + textToCopy.value);
}
But it didn't worked.
A:
function copyFunction()
{
var $temp = $("<input>");
$("body").append($temp);
$temp.val($('#copy').text()).select();
document.execCommand("copy");
$temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="copy">Text to copy</p>
<button onclick="copyFunction()">Copy text</button>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get list of contacts in specific engagement plan state?
I have an engagement plan and there are number of contacts in each state.
How can I programmatically obtain list of contacts which are in specific engagement plan state by state ID?
A:
Have just found a method:
var pageableContactIds = AutomationManager.Provider.GetEnrolledContactsIdsByStatePaged(engagementPlanStateId);
This will return an object of type Sitecore.Common.IPageable<ID> which provides a method .GetAll()
Seems to work for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do all moderators stand for re-election?
I notice we have a new election!
Do all moderators stand for re-election? Or does the election add new moderators to our existing 6?
As a follow up question, three (possibly four) of our moderators are active and do a great job. I haven't seen two of them active in the time I've been here (the larger part of this year). If not all moderators stand for re-election, should we be requesting removal of the inactive moderators at this time too?
A:
Current moderators stay as they are, we are on the hook until we make decision to retire or are removed (typically for inactivity).
As per election page there are two new positions to be filled with newly elected moderators.
| {
"pile_set_name": "StackExchange"
} |
Q:
Storing the dictionary's keys in the dictionary when defining dictionary
I want to be able to store the keys of a dictionary in the dictionary, preferably defining the dictionary only once. I am unsure if this is possible as it very close to recursively defining variables but what I want is:
d = {
"a" : d.keys()
}
My attempts
The only approaches I have come up with are the following:
Using Eval
d = {
"a" : 'd.keys()' #stored as a string for future execution
}
This works but isn't ideal.
Using separate passes
d = {
"a" : None
}
d = {
"a" : d.keys()
}
This works but I would prefer one to only define my dictionary once. I also don't want to store another list of keys and take that approach.
A:
you could do this:
d = dict()
d.update({"a": d.keys()})
d.update({"c": "dfghjk"})
d.update({"f": "dfjk"})
print(d.get("a"))
prints:
dict_keys(['a', 'c', 'f'])
| {
"pile_set_name": "StackExchange"
} |
Q:
how to validate same form id in javascript?
I am trying to validate two forms with same id. for first its working fine. but for second its not validating why?
Here, i have given the example code:
function cc(id){
if(document.getElementById(id).value.toUpperCase()==(id)){
document.getElementById(id).style.backgroundColor = "green";
}else{
document.getElementById(id).style.backgroundColor = "red";
}
}
<form id="save" method="post">
<input type="text" name="A" id="C" class="textbox" onKeyUp="cc(id,this, 'H')" maxlength="1" />
<input type="text" name="A" id="C" class="textbox" onKeyUp="cc(id,this, 'H')" maxlength="1" />
</form>
http://jsbin.com/viraqixicigi/6/edit
A:
Use the this argument to operate on the target of the event:
function cc(element, goodValue){
if(element.value.toUpperCase() == goodValue){
element.style.backgroundColor = "green";
}else{
element.style.backgroundColor = "red";
}
}
<form id="save" method="post">
<input type="text" name="A" id="C" class="textbox" onKeyUp="cc(this, 'H')" maxlength="1" />
<input type="text" name="A" id="C" class="textbox" onKeyUp="cc(this, 'H')" maxlength="1" />
</form>
DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
Backup picture using FreeFileSync
I would like to backup my pictures using FreeFileSync, I say pictures because i want to migrate both iPhoto and photos libraries till i figure which one i want to keep
I have my reasons not to use TimeMachine
So with FreeFileSync which folder should i be selecting as the folder to sync?
A:
To back up photos visible in Photos.app and iPhotos.app, select the folder:
~/Pictures/
Where ~ is your home folder.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing Date in string Database using getters/setters
I'm trying to get a Date to Gmt+7 from listview Adapter :
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
_teamlist.clear();
db = new DBHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<TeamModel> team_list = getTeams2();
for (int i = 0; i < team_list.size(); i++) {
String tdate = team_list.get(i).getTeamdate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+7"));
Date datex = null;
try {
datex = sdf.parse(tdate);
} catch (ParseException e) {
e.printStackTrace();
}
TeamModel _TeamModel = new TeamModel();
_TeamModel.setTeamdate(datex); ///// here the probleme !!!!!
_teamlist.add(_TeamModel);
}
}
in this line '_TeamModel.setTeamdate(datex)' the error : "setTeamdate java.lang.String in TeamModel cannot be applied to java.util.Date "
My get/set class TeamModel:
public class TeamModel {
public String teamdate="";
....
public String getTeamdate() {
return teamdate;
}
public void setTeamdate(String teamdate) {
this.teamdate = teamdate;
}
}
i tried to change teamdate in this class to date from string but it mess up my DBHelper
A:
thanks to "mithrop" for his help, this's what i did to fix the problem :
String tname = team_list.get(i).getTeamname();
String topponent = team_list.get(i).getTeamopponent();
String tdate111 = team_list.get(i).getTeamdate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+9"));
Date datex = null;
try {
datex = sdf.parse(tdate111);
} catch (ParseException e) {
e.printStackTrace();
}
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String tdate = sdf.format(datex);
System.out.println(tdate);
TeamModel _TeamModel = new TeamModel();
_TeamModel.setTeamname(tname);
_TeamModel.setTeamopponent(topponent);
_TeamModel.setTeamdate(tdate);
_teamlist.add(_TeamModel);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make toon shader more realistic and clean crooked shadow in models?
How can I make my toon shader more realistic? I have a crooked shadow in my character model, how can I correct it?
A:
One thing that might help is to bump up the subdivision modifier (assuming you have it on), though that might increase render times.
Another thing you might try is custom normals. This way, you can have more control over how the shading looks but it adds several steps to your workflow.
I would also suggest this video. Its long and has nothing to do with blender, but it is very informative.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create smaller instruction set from x86 assembly
I have a sort of simulator for x86 assembly instructions, but the thing is it doesn't accept the full instruction set. For instance if given an INT command it will terminate. It is possible to run all the binary representation (8bit, 16bit and 32bit) of commands on the simulator and see which one's are valid and which are not.
It is for using in genetic programming and need to mutate the commands binary representation, but trying to do this without creating an invalid one.
The easiest solution seems to just count them, but how will the transform function between the original and smaller instruction sets work?
A:
If the code segment is modifiable, it will be very difficult to create a translator, because you will need to account for the possibility of self-modifying code. Any such translator would need to include a copy of itself in the generated code; at that point it would be easiest to just 'finish' the simulator.
If the code segment is not modifiable, it's still very difficult, because with x86 it's possible to jump into the middle of an instruction, and have it interpreted as a different instruction. So while in principle you could build a static translation for all possible start addresses, and build a big jump table to figure out which static translation you need, it's still not worth it.
I would suggest that rather than converting general x86 code to this subset, instead constrain the code generated by the GA to make it fit into the subset. You can try using techniques such as those described in the google native client paper to further restrict the code to avoid the jumping-into-the-middle-of-instructions problem.
Alternately, there's always the option of using a complete x86 emulator instead of a limited one. You'll still have the problem of the GA generating illegal opcodes however. You could also consider using an ISA custom-designed to be easy to emulate instead of x86 and emulating that. Then compile to x86 (you did design it to be easy to compile, right?) when you have something you want to keep.
This reference seems similar to what you're doing as well, you might want to take a look:
Nordin, Peter. "A compiling genetic programming system that directly manipulates the machine code." Advances in genetic programming. Cambridge, Mass: MIT, 1994. 311-32. Print.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot divide by zero error on DB2
Hello all I am using DB2! I have a query that calculates the MPG over a period of 30 days it is done by capturing the change in odometer as the numerator and the sum of fuel purchases as the denominator. However I have a particular unit that is causing me some grief!
Apparently he has not purchased any fuel within the last 30 days and as a result he is causing my query to return an error
Division by zero was attempted. SQLState = 22012
I thought I could be clever and use coalesce but it an unsupported type.
here is the query the mpg!
ROUND(((SELECT MAX(ODOMETER)-MIN(ODOMETER) FROM ODOHIST O
WHERE READINGDATE >= CURRENT DATE - 30 DAYS AND O.UNIT_ID = DEFAULT_PUNIT)/
(SELECT SUM(T2.VOL_PFUEL) FROM FC_POS T2 WHERE T2.DRIVER_ID = DRIVER.DRIVER_ID AND POS_DATE >= CURRENT DATE - 30 DAYS)),2) AS MPG_30DAYS
Rather than actually returning a field of 0 it is just blank, so is there a function similar to coalesce that will force a return value?
Thanks for your help!
A:
That would mean that this evaluates to 0:
(SELECT SUM(T2.VOL_PFUEL)
FROM FC_POS T2
WHERE T2.DRIVER_ID = DRIVER.DRIVER_ID AND POS_DATE >= CURRENT DATE - 30 DAYS
)
My suggestion is to use NULLIF() in the statement:
(SELECT NULLIF(SUM(T2.VOL_PFUEL), 0)
FROM FC_POS T2
WHERE T2.DRIVER_ID = DRIVER.DRIVER_ID AND POS_DATE >= CURRENT DATE - 30 DAYS
)
This will replace the 0 with NULL, which should fix the problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why Cookie name and value is 'http' and 'proxy' respectively without having created one in eclipse?
I am trying to create a simple cookie program in servlet using eclipse.
This is how it is:-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie[] cookies = request.getCookies();
if(cookies == null)
{
out.print("<b> Hello Stranger </b><br>");
}
else
{
for(Cookie cookie:cookies)
{
out.print("<b> Hello" + cookie.getValue() + "</b>");
}
}
out.print("<form action = '' method = 'post'>");
out.print("What is your name?");
out.print("<input type = 'text' name = 'username'><br>");
out.print("<br>");
out.print("<input type = 'submit'>");
out.print("</form>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
response.setContentType("text/html");
String str = request.getParameter("username");
Cookie[] cookies = request.getCookies();
if (cookies == null)
{
Cookie c = new Cookie("username",str);
c.setMaxAge(-1);
response.addCookie(c);
}
for(Cookie cookie: cookies)
{
out.print("<b> Hello," + cookie.getName() + "</b>");
}
}
When running it in the tomcat server using eclipse
instead of getting output as Hello Stranger I am getting Hello http
Even after clicking on submit
It is showing the same thing instead of the name entered.
A:
You're iterating through (and printing) the list of cookies contained in the inbound HttpServletRequest, but you're adding the new cookie to the HttpServletResponse.
While the HttpServletResponse has an addCookie() method, it doesn't have a matching getCookies(), so you would need to work around this if your wish to see the cookies you have added to the response object. There are several posts that cover this, for example here and here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why have an off position for the heating dial on electric showers?
So - some background. I'm fairly new to the concept of electric showers - showers that heat cold water themselves with internal heating elements. With my shower, I have two dials - one for temperature, and another for adjusting the "Eco" setting. This eco dial has three positions - I'm totally blind, so not sure how these are physically labeled. During testing, it appears that if I have my temperature setting on the highest value and do the same for the eco dial, the water is at its hottest. If I then keep the temperature at the same setting but turn the eco dial down, it appears that the shower will wait until the water cools down before it will then heat some more - and on its lowest setting (which I assume is off or similar), the water doesn't appear to get heated at all.
So - my question. If no heating is performed on water when the heating/eco dial is at its lowest value despite the temperature dial being on the highest setting, why have an "off" value for this dial? Is this effectively the same as simply turning the temperature dial down to its lowest value?
A:
Note: this answer is based on my experiance in the UK, I do not know if this are the same in the rest of the world.
Traditionally the "temperature" control on an electic shower did not directly control temperature, instead it controlled flow rate. For a given input water temperature and heating power, a lower flow rate resulted in a higher temperature.
Nowadays nearly all electric showers have thermostats to prevent the output water becoming unexpected hot in limited water scenarios, but the control scheme in normal operation (not limited by input water) remains the same. You set a power control to select how much heating power (if any) you want, then use the main dial to control the trade-off between temperature and flow, or in the case of "cold" mode to control the flow.
| {
"pile_set_name": "StackExchange"
} |
Q:
CouchDb - One design doc with multiple views vs multiple design docs with split views
I am trying to figure out the tradeoffs between these two.
It seems that using one design doc with multiple views is fast to update because when indexing, each doc is passed into each view in a single pass.
But, a tradeoff would be that if I change a view in the design doc, all the views need to be updated.
Does this seem correct? Is there something else someone could add to this understanding?
A:
More detail informations can be found here :
Views are organized into design docs. Theoretically, you can have as many design docs as you want in a database, and as many views as you want in a single design doc. Theoretically, each view can emit arbitrarily many b-tree nodes per document, and your map/reduce code can be arbitrarily complex. But keep in mind:
Having many views degrades performance, because each view must be run on every document change
All views in the same design doc are indexed together; changing, adding, or removing any view requires all of them to be reindexed
Having many emits per document in a view can degrade performance (but slightly more performant than putting each emit in its own view)
Complex map and reduce code degrades performance
Emitting values other than null degrades performance
Using reduce code other than the _sum, _count, _stats built-ins degrades performance
As a side note CouchDB and Cloudant differ on exactly when views are updated:
CouchDB updates views lazily, that is when they are queried. This can lead to long wait times for infrequently accessed views.
Cloudant updates views asynchronously in the background. This means that views that are no longer being accessed are still consuming system resources.
| {
"pile_set_name": "StackExchange"
} |
Q:
Use c++ compiled library in virtualenv
Notes
This is a python-2.7/django-1.6 project
I have a project that requires the use of the libRETS C++ library which supports python. I was able to successfully compile so that librets is now in my /usr/local/lib/python2.7/dist-packages using the ./configure, make and make install commands.
Now for the current project I am using a virtualenv and doing development using PyCharm as the IDE. I am not sure how to include this library in my virtual environment. Is there a way to inlcude global site packages in my virtualenv? Do I need to create a symbolic link to the librets files in the dist-packages directory, or should I have specified where the package should be installed when I did the configure command?
Any help or suggestions would be greatly appreciated or if my question is not clear please let me know how I can expound.
A:
I solved this by simply copying librets.* files from my /usr/local/lib... directory directly into my virtualenv dist-packages directory for the project.
| {
"pile_set_name": "StackExchange"
} |
Q:
A box BIGGER than... vs A BIGGER box than...?
He gets a box bigger than the one I lost.
He gets a bigger box than the one I lost.
Is there any difference in the meaning of two of the above sentences or those things are just about grammar, and they are the
same in meaning?
Ps. I got the 2nd sentence by applying the postpositive-adjective grammar stuff. You can enjoy that matter here.
A:
The two sentences are both grammatically correct, and they mean essentially the same thing. The only real difference is a slight difference in emphasis.
He gets a bigger box than the one I lost.
This is the most common way that this would be phrased, so it's the most neutral in terms of emphasis: He got a box, and it was bigger than the one you lost.
He gets a box bigger than the one I lost.
This is a somewhat less common construction, so it actually emphasizes the word "bigger" a bit more: He got a box, and not only that, but the box was actually bigger than the one you lost!
The difference in emphasis is not that large, so really either one could be substituted for the other without a problem..
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a Diplomacy variant that does not contain stalemate lines?
The standard Diplomacy game can often end up locked in a stalemate, with one player pushing for 18 territories, and two or more defenders trying to stop them. There are already many articles about this, including a useful visual index to stalemate positions. However, I have so far failed to find a Diplomacy map that was designed to prevent stalemates.
Firstly is it even possible to have such a map using the standard rules? Maybe there is logical reasoning that proves that a stalemateless board does not exist?
If it is possible, has it already been done? Does the lack of stalemate lines make the game more dynamic, or does it mean players have to be more edgy about attacking?
If it is not possible to create such a map, is there a variant that avoids stalemates with some other change to the rules? In one of the articles I saw it mentioned that "it is difficult to see" how certain variants could allow stalemates, but have any variants been designed with this goal in mind?
A:
Erlend Janbu's variant South America v. 3.2 for four players was designed with the explicit aim "to create a variant where there are no stalemate lines." In a 2001 article on the variant he admits that he does not know for sure whether there is a stalemate line in his variant, but "I and others have searched, and after 100 games, no game has ended in a stalemate." He claims in that article that only "[f]ew variants are stalemate-free," but unfortunately he does not name any. Until one could prove that there is indeed a stalemate line in the South America variant, the answers to your main questions should be positive: yes, it is possible to design a stalemate-free board and yes, it has been done before.
As to how the lack of stalemates would affect the game, it might be worth reading what Andy Schwarz has written on his variant Hundred (based on the Hundred Year's War). As he wrote in an article from 1996, "eliminating draws was a big part of the design of Hundred." This has encouraged solo wins and alliances-shifts, making the game very dynamic. This should also apply to any variant which reduces or eliminates stalemates.
As to variants which avoid stalemates by means of changes to the rules, Stephen Agar wrote about this specifically in his article from 1992, "Designing Maps for Diplomacy Variants," where he notes that "[s]ome variants avoid stalemate lines through the rule mechanics." The only example which he gives is the Multiplicity variant, where multiple units can occupy a single space.
A:
Somewhat trivially, the Pure variant has no stalemate lines.
This is a simple traditional variant of diplomacy. There are the usual
seven countries. There are seven spaces on the board - one
corresponding to each country - its home supply center. These spaces
are all connected by land one with another. Initially, each player
begins with one army in his home supply center.
The objective of the game is to accumulate four supply centers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Estou problemas para ler uma string dentro de uma função
Boa noite, gostaria de saber métodos para ler uma string em C(Versão C99), já tentei bastante coisa, e não funciona, abaixo, o código defeituoso.
Obs: O erro que relato é que, logo após apertar "ENTER" no primeiro 'gets' da função cadastro, o programa buga, e exibe a mensagem "o programa.exe parou de funcionar".
Obs.1: Retirei os < > dos includes pois o navegador identifica isso como uma tag html e não exibe o conteúdo dos includes.
#include stdio.h
#include stdlib.h
int menu()
{
int opc;
printf("\n Opcoes: \n1. Cadastrar livros\n2. Consultar livros\n3. Alterar informacoes de livros\n4. Remover um livro da lista");
scanf("%d", &opc);
return(opc);
}
struct informacoes
{
char nome[100];
char autor[100];
long long int isbn;
char volume[10];
int data;
char editora[100];
int paginas;
};
int cadastro(struct informacoes *livros, int i){
printf("\nNome do livro: ");
gets(livros[i].nome);
printf("\nAutor: ");
gets(livros[i].autor);
printf("\n ISBN : ");
scanf("%lli", livros[i].isbn);
printf("\n Volume em romanos: ");
gets(livros[i].volume);
printf("\n Ano de lancamento: ");
scanf("%d", livros[i].data);
printf("\nEditora do livro: ");
gets(livros[i].editora);
printf("\nQuantidade de paginas no livro: ");
scanf("%d", livros[i].paginas);
}
int main()
{
int opc = menu();
struct informacoes livros[10];
int i=0;
switch(opc)
{
case 1:
cadastro(livros, &i);
}
return (EXIT_SUCCESS);
}
A:
Seu código na verdade tem vários erros, os 2 mais claros são:
Você não pode enviar um ponteiro para um método que você pede um valor inteiro como parâmetro:
Onde você colocou:
cadastro(livros, &i);
Troque por:
cadastro(livros, i); //Note que não possui o &
O método cadastro é do tipo int mais não retorna nenhum valor, coloque-o do tipo void, ou seja, não retorna nada:
Onde você colocou:
int cadastro(struct informacoes *livros, int i){
Troque por:
void cadastro(struct informacoes *livros, int i){
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove that $\sum_{i=1}^{\frac{n-1}{2}}\left\lfloor\frac{mi}{n}+\frac{1}{2}\right\rfloor$ is an even number
Let $m$, $n$ be positive odd numbers such that $\gcd(m,n)=1$. Show that
$$\sum_{i=1}^{\frac{n-1}{2}}\left\lfloor\dfrac{mi}{n}+\dfrac{1}{2}\right\rfloor$$
is an even number, where $\lfloor{x}\rfloor$ is the largest integer not greater than $x$.
My try:
$$\sum_{i=1}^{\frac{n-1}{2}}\left\lfloor\dfrac{mi}{n}+\dfrac{1}{2}\right\rfloor=\left\lfloor\dfrac{m}{n}+\dfrac{1}{2}\right\rfloor+\left\lfloor\dfrac{2m}{n}+\dfrac{1}{2}\right\rfloor+\cdots+\left\lfloor\dfrac{m(n-1)}{2n}+\dfrac{1}{2}\right\rfloor$$
Then I can't it. Thank you for your help.
A:
This is not a full answer to the question, but a proof of a claim I made in a comment.
In Fig 1, hypotenuse of the half-sized triangle is the line $\frac mni+\frac12$.
$\hspace{2cm}$
The number of dots inside that triangle is the sum in question:
$$
\sum_{i=1}^{(n-1)/2}\left\lfloor\frac mni+\frac12\right\rfloor\tag{1}
$$
If we scale that triangle to the full-sized triangle, we see that the dots inside the half-sized triangle correspond to the red dots in the full-sized triangle. Flipping the full-sized triangle from Fig 1 to Fig 2, we see that the red dots are the points with odd coordinates. Thus, the red dots represent the solutions in non-negative integers of
$$
m(2x+1)+n(2y+1)\lt mn\tag{2}
$$
Since the left side of $(2)$ is even and the right side is odd, it is equivalent to
$$
m(2x+1)+n(2y+1)\lt mn+1\tag{3}
$$
which is equivalent to
$$
mx+ny\lt\frac{(m-1)(n-1)}{2}\tag{4}
$$
Therefore, the sum in $(1)$ counts the number of non-negative solutions of $(4)$.
A:
Note $[x+\frac{1}{2}]=[2x]-[x]$
$$\sum_{i=1}^{\frac{n-1}{2}}\left\lfloor\dfrac{mi}{n}+\dfrac{1}{2}\right\rfloor=\sum_{i=1}^{\frac{n-1}{2}}(\left\lfloor2x\right\rfloor-\lfloor x\rfloor)\\=\sum_{i\ge \frac{n-1}{2},i\equiv0\pmod{2}}\left\lfloor x \right\rfloor-\sum_{i\le \frac{n-1}{2},i\equiv1\pmod{2}}\left\lfloor x \right\rfloor\\=\sum_{i\ge \frac{n-1}{2},i\equiv0\pmod{2}}\left\lfloor x \right\rfloor+\sum_{i\le \frac{n-1}{2},i\equiv1\pmod{2}}\left\lfloor -x+1 \right\rfloor \\ \equiv 2\sum_{i\ge \frac{n-1}{2},i\equiv0\pmod{2}}\left\lfloor x \right\rfloor \pmod{2}\\ \equiv0\pmod{2}$$
I hope you don't mind me trying to clarify what you have above:
$$
\begin{align}
\sum_{i=1}^{\frac{n-1}{2}}\left\lfloor\frac{mi}{n}+\frac12\right\rfloor
&=\sum_{i=1}^{\frac{n-1}{2}}\left\lfloor\frac{2mi}{n}\right\rfloor
-\sum_{i=1}^{\frac{n-1}{2}}\left\lfloor\frac{mi}{n}\right\rfloor\\
&=\sum_{\substack{i=2\\i\text{ even}}}^{n-1}\left\lfloor\frac{mi}{n}\right\rfloor
-\sum_{i=1}^{\frac{n-1}{2}}\left\lfloor\frac{mi}{n}\right\rfloor\\
&=\sum_{\substack{i\gt n/2\\i\text{ even}}}\left\lfloor\frac{mi}{n}\right\rfloor
-\sum_{\substack{i\lt n/2\\i\text{ odd}}}\left\lfloor\frac{mi}{n}\right\rfloor\\
&=\sum_{\substack{i\gt n/2\\i\text{ even}}}\left\lfloor\frac{mi}{n}\right\rfloor
-\sum_{\substack{i\gt n/2\\i\text{ even}}}\left\lfloor\frac{m(n-i)}{n}\right\rfloor\\
&=\sum_{\substack{i\gt n/2\\i\text{ even}}}\left\lfloor\frac{mi}{n}\right\rfloor
-\sum_{\substack{i\gt n/2\\i\text{ even}}}\left\lfloor m-\frac{mi}{n}\right\rfloor\\
&=\sum_{\substack{i\gt n/2\\i\text{ even}}}\left\lfloor\frac{mi}{n}\right\rfloor
-\sum_{\substack{i\gt n/2\\i\text{ even}}}\left(m-1-\left\lfloor\frac{mi}{n}\right\rfloor\right)\tag{$\ast$}\\
&=2\sum_{\substack{i\gt n/2\\i\text{ even}}}\left(\left\lfloor\frac{mi}{n}\right\rfloor-\frac{m-1}{2}\right)
\end{align}
$$
$(\ast)$ is true as long as $\frac{mi}{n}\not\in\mathbb{Z}$.
| {
"pile_set_name": "StackExchange"
} |
Q:
inserting hash into a specific array location
I'd like to insert a hash into a specific location in an array. I have this:
arr = [
{:key1=>"one", :key2=>"two", :key3=>"three"},
{:key1=>"four", :key2=>"five", :key3=>"six"},
{:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]
and would like to insert this hash into the array
{:key1=>"---", :key2=>"---", :key3=>"---"}
So that the result is
arr = [
{:key1=>"one", :key2=>"two", :key3=>"three"},
{:key1=>"---", :key2=>"---", :key3=>"---"},
{:key1=>"four", :key2=>"five", :key3=>"six"},
{:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]
Can anyone help please
A:
I think you should use the array insert method.
arr.insert(1, {:key1=>"---", :key2=>"---", :key3=>"---"} )
Check out the example here
http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-insert
| {
"pile_set_name": "StackExchange"
} |
Q:
SetOnFocusChangeListener with NullpointerException
I have fragment A:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main, container, false);
CustomKeyboard customKeyboard = new CustomKeyBoard(getActivity());
etAge = (EditText) getActivity().findViewById(R.id.etAge);
customKeyboard.actionEt(etAge);
return view;
}
And I have class B:
public class CustomKeyboard {
private Context context;
public CustomKeyboard (Context context) {
this.context = context;
}
private void hideKeyboard(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void actionEt(Edittext edittext){
editText.setOnFocusChangeListener((view, hasFocus) -> {
if(!hasFocus) {
hideKeyboard(view);
} else {
//........
}
});
}
}
The Exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setOnFocusChangeListener(android.view.View$OnFocusChangeListener)' on a null object reference
What is the reason of the problem? Hope for some help.
EDIT:
NOW THE APP RUNS. But the Edittexts dont hide.
A:
Your code:
etAge = (EditText) getActivity().findViewById(R.id.etAge);
Is wrong because it inflates from an activity instead of the view it is located in. The cause is comparable to getting a Nullpointer when finding a view in a different layout
Correct code:
etAge = (EditText) view.findViewById(R.id.etAge);
As this finds the EditText in the view instead of the activity(which has no defined view inflated)
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I read a 5¼″ drive on 1996–2007 equipment?
In my organization's archive I just found some 5¼″ floppies, presumably IBM PC 320/360k. They contain information that we have on paper, but I'd really like to have on electronic media, not least so we can make searchable PDFs of it without a whole bunch of archival work.
What is my most expedient way to read these? I have access to an IBM PC 300PL Type 6862 running Win98SE with a 3½″ floppy, a late Power Mac running 10.5, and an early Intel Mac running 10.11.
Any chance a run of the mill 5¼″ floppy off eBay will plug into the PC300?
A:
The answer will depend on the exact model of 300PL you have, but there’s a good chance it will be possible to use a 5.25” drive with your computer.
Many 300PL models, such as type 6592, type 6565, and your type 6862, explicitly support 5.25” drives, and support connecting two drives at once; so with one of those, you should be able to connect the drive, configure the BIOS and go. The 6862 at least is supplied with a very short cable with only two connectors, so you will need to replace the existing floppy cable with one appropriate for 5.25” drives, which normally use an edge connector. Compatible cables looks like the one shown here, with five connectors and a twist.
Given the physical layout of the 6862, you might have trouble routing the floppy cable if you try to connect both the 3.5” drive and the 5.25” drive at once. You will at least need a rather long cable, and in particular one with a decent length in between both sets of drive connectors (where the twist in the cable is found). You’ll probably find it much easier to only connect one drive at a time.
Other types might or might not directly support 5.25” drives; for example, type 6562’s manual claims it doesn’t. However if the BIOS doesn’t support the drive, you may be able to configure Windows to use it anyway, and if that fails, you can buy a cheap ISA floppy controller and plug it into one of the ISA slots.
A:
Generally, most 1996 mainboards WILL deal with a 5 1/4" floppy just fine IF you use the appropriate cable (which will often NOT have been supplied with a computer or mainboard in 1996). The important thing is BIOS support. Which is likely on any mainboard that still has ISA slots.
IIRC I did use a 5 1/4" drive just fine on a ca. 1998 ASUS P5A based system, with Windows 98SE and various Unices.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to reduce space between label and a text box in html
I am designing a html form where I have a label and a textbox, but in my design there is a big space between the textbox and the label, which I want to reduce.
Here is my code:
<tr>
<td>
<bean:message key="tml.registration.captcha.verification.code"/>
<font color='red'>*</font>
</td>
<td>
<input type="text" name="imageValidation" size="25" title="Enter verification Code"/>
</td>
<td>
<logic:messagesPresent property="imageValidation">
<font color="red"><html:errors property="imageValidation" /></font>
</logic:messagesPresent>
</td>
</tr>
I want the verification code and textbox closely aligned. Somebody please help.
Here is a screenshot of the current state:
A:
Assign small width for the td and apply nowrap style. Update your code like below.
<tr>
<td width="3" nowrap>
<bean:message key="tml.registration.captcha.verification.code" />
<font color='red'>* </font>
</td>
<td>
<input type="text" name="imageValidation" size="25" title="Enter verification Code" />
</td>
<td>
<logic:messagesPresent property="imageValidation">
<font color="red"><html:errors property="imageValidation" /></font>
</logic:messagesPresent>
</td>
</tr>
EDIT:
If this table-row comes up with so many other content, then create one table inside the td like below.
<tr>
<td colspan="3">
<table cellpadding="0" cellspacing="0" width="100%" border="0">
<tr>
<td width="3" nowrap>
<bean:message key="tml.registration.captcha.verification.code" />
<font color='red'>*</font>
</td>
<td>
<input type="text" name="imageValidation" size="25" title="Enter verification Code" />
</td>
<td>
<logic:messagesPresent property="imageValidation">
<font color="red"><html:errors property="imageValidation" /></font>
</logic:messagesPresent>
</td>
</tr>
</table>
</tr>
| {
"pile_set_name": "StackExchange"
} |
Q:
размещение сайта(веб приложения)
есть созданный сайт(веб приложение) на java созданный как Dynamic Web Project запуск в Apache Tomcat прошел успешно
после я перекинул папку с файлами на хостинг
результат меня не порадовал http://webtest1.ga/ , http://webtest1.ga/WebContent/ вопрос что не так ?
A:
Думаю твой хостинг не поддерживает работу java приложений. Предположу, что это хостинг только для php.
И я ни когда не видел, что бы веб приложения на java разворачивали путём копирования исходников в корень сайта. Хотя такое можно настроить, но маловероятно).
Обычно приложение компилируют и упаковывают в war файл. Потом этот файл разворачивают на сервере приложений(tomcat, wildfly и д.р) через web консоль. Путём копирования тоже можно развернуть, но это зависит сервера приложений. К примеру у wildfly есть директория deployments которую он постоянно проверяет на наличие новых файлов.
| {
"pile_set_name": "StackExchange"
} |
Q:
Show a Form without stealing focus?
I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus?
A:
Hmmm, isn't simply overriding Form.ShowWithoutActivation enough?
protected override bool ShowWithoutActivation
{
get { return true; }
}
And if you don't want the user to click this notification window either, you can override CreateParams:
protected override CreateParams CreateParams
{
get
{
CreateParams baseParams = base.CreateParams;
const int WS_EX_NOACTIVATE = 0x08000000;
const int WS_EX_TOOLWINDOW = 0x00000080;
baseParams.ExStyle |= ( int )( WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW );
return baseParams;
}
}
A:
Stolen from PInvoke.net's ShowWindow method:
private const int SW_SHOWNOACTIVATE = 4;
private const int HWND_TOPMOST = -1;
private const uint SWP_NOACTIVATE = 0x0010;
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
static extern bool SetWindowPos(
int hWnd, // Window handle
int hWndInsertAfter, // Placement-order handle
int X, // Horizontal position
int Y, // Vertical position
int cx, // Width
int cy, // Height
uint uFlags); // Window positioning flags
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static void ShowInactiveTopmost(Form frm)
{
ShowWindow(frm.Handle, SW_SHOWNOACTIVATE);
SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST,
frm.Left, frm.Top, frm.Width, frm.Height,
SWP_NOACTIVATE);
}
(Alex Lyman answered this, I'm just expanding it by directly pasting the code. Someone with edit rights can copy it over there and delete this for all I care ;) )
A:
If you're willing to use Win32 P/Invoke, then you can use the ShowWindow method (the first code sample does exactly what you want).
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you run a function when any data in an object is changed using Vuejs?
So I have the following data, and my goal is to recalculate the user's results every time data in this object is changed. Here is the data.
data() {
return {
test: 0,
userData: {
sex: null,
age: null,
feet: null,
inches: null,
activity: null,
goal: null,
},
}
}
Now I have tried to implement both watch and computed, but it seams Vue is not noticing when individual items in the object are changed. However, if I take some data out of the object it does notice the change.
Here is what I tried for watch:
watch: {
userData: function () {
console.log("Changed");
}
}
The result was nothing in the console.
For computed I tried the following:
computed: {
results: function () {
console.log(this.userData);
return this.userData.sex;
}
}
But again nothing was printed in the console.
If I tried with the test variable:
watch: {
test: function () {
console.log("Changed");
}
}
It WOULD output changed when the variable was changed. So that works because it is not an object.
Any help would be very appreciated. Again the goal is to recalculate results whenever any userData is changed.
A:
Are you actually using the results property (in your template for example)? Computed properties do not get recomputed if they are not being used.
As opposed to what @match says, I doubt you have a reactivity problem since you do not add or delete properties (they already exist in your data so they are already reactive).
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem with user reputation and/or missing questions
I was just looking at the users list (specifically rep in the last month) and then looked at a couple of user profiles. These users have 500+ rep even though it says they have 0 questions and 0 answers:
https://webmasters.stackexchange.com/users/9607/alan-h
https://webmasters.stackexchange.com/users/10172/rook
They do have several badges that imply they have asked or answered questions. I'm assuming a bug with question display?
A:
Both users' reputation appears to be related to a deleted question which was migrated from StackOverflow - here's the original: How do Google+ +1 widgets break out of their iframe?
A:
I went ahead and deleted those accounts to clean up.
(They can always recreate them, but neither user seemed particularly interested in this site, which is perhaps another argument in favor of the un-migration of that question..)
| {
"pile_set_name": "StackExchange"
} |
Q:
Read Bytes off a Serial Device (and make sense of them??)
I'm pulling my hair out trying to figure out how to read bytes off a serial device, check a checksum, and then convert them into something that I can actually read.
I have a device which "should" be sending me various messages, each started with the byte $83 and ended with the byte $84. The second to last byte is supposedly a checksum, generated by XORign all the other values together and comparing.
The actual values coming back should be alphanumeric, but I can't make heads or tail of the data. I'm newish to C++ - I'm sure that's not helping.
I've read several guides on serial programming, but I'm lost.
Can anyone help me, link me, or show me how to read bytes off a serial device, watch for $83 and $84, and then make sense of the data in between?
Here is the format of each message:
$FF byte Destination Address
$10 byte Message Length 16 Bytes
$37 byte Message Type
$00 byte Message subtype
BankAngle int -179 to +180
PitchAngle int -90 to +90
YawAngle int -179 to +180
Slip sint -50 to +50
GForce fps 0 to 6G
MISC byte Mode bits
Heading word 0 to 359
N/A not used
Voltage byte input voltage
This is all coming off an MGL SP-4 AHRS, and for ease of use I am targeting a Linux system, specifically Ubuntu. I am using the GCC compiler end the Eclipse CDT for development.
Where I'm lost
I can read the data into a buffer, but then I'm not versed enough in C++ to make sense of it after that, since it's not ASCII. I'm interested in learning what I need to know, but I don't know what I need to know.
I have a Perl / Java background.
A:
Accomplishing this is going to be wholly dependent on the Operating System and platform that you target. Since the device you mention is mounted internally to an aircraft in the general use-case, I will assume you are not targeting a Windows platform, but more likely a Linux or embedded system. There are a number of resources available for performing serial I/O on such platforms (for example: the Serial Programming HOW-TO) that you should look at. Additionally, as suggested in the device's Installation Manual (available here about halfway down the page), you should "Consult the SP-4 OEM manual for message formats and message type selection." I suspect you will obtain the most relevant and useful information from that document. You may want to check if the manufacturer provides an API for your platform, as that would negate the need for you to implement the actual communication routine.
As far as making sense of the data, once you can read bytes from your serial interface, you can leverage structs and unions to make accessing your data more programmer-friendly. For the rough message outline you provided, something like this might be appropriate:
struct _message
{
uint8_t DestinationAddress;
uint8_t MessageLength;
uint8_t MessageType;
uint8_t MessageSubtype;
int32_t BankAngle; //assuming an int is 32 bits
int32_t PitchAngle;
int32_t YawAngle;
sint_t Slip; //not sure what a 'sint' is
fps_t GForce; //likewise 'fps'
uint8_t MISC;
uint16_t Heading; //assuming a word is 16 bits
uint8_t Unused[UNUSED_BYTES]; //however many there are
uintt_t Voltage;
}
struct myMessage
{
union
{
char raw[MAX_MESSAGE_SIZE]; //sizeof(largest possible message)
struct _message message;
}
}
This way, if you were to declare struct myMessage serialData;, you can read your message into serialData.raw, and then conveniently access its members (e.g. serialData.message.DestinationAddress).
Edit: In response to your edit, I'll provide an example of how to make sense of your data. This example supposes there is only one message type you have to worry about, but it can be easily extended to other types.
struct myMessage serialData;
memcpy(serialData.raw, serialDataBuffer, MAX_MESSAGE_SIZE); //copy data from your buffer
if(serialData.message.MessageType == SOME_MESSAGE_TYPE)
{
//you have usable data here.
printf("I am a SOME_MESSAGE!\n");
}
Now, supposing that these integral types are really only useful for data transmission, you need to translate these bits into "usable data". Say one of these fields is actually an encoded floating-point number. One common scheme is to select a bit-weight (sometimes also called resolution). I don't know if this is directly applicable to your device, or if it is what the real values are, but let's say for the sake of discussion, that the YawAngle field had a resolution of 0.00014 degrees/bit. To translate the value in your message (serialData.message.YawAngle) from its uint32_t value to a double, for example, you might do this:
double YawAngleValue = 0.00014 * serialData.message.YawAngle;
...and that's about it. The OEM manual should tell you how the data is encoded, and you should be able to work out how to decode it from there.
Now, let's say you've got two message types to handle. The one I've already shown you, and a theoretical CRITICAL_BITS message. To add that type using the scheme I've laid out, you would first define the CRITICAL_BITS structure (perhaps as follows):
struct _critical_bits
{
uint8_t DestinationAddress;
uint8_t MessageLength;
uint8_t MessageType;
uint8_t MessageSubtype;
uint32_t SomeCriticalData;
}
...and then add it to the struct myMessage definition like so:
struct myMessage
{
union
{
char raw[MAX_MESSAGE_SIZE]; //sizeof(largest possible message)
struct _message message;
struct _critical_bits critical_message;
}
}
...then you can access the SomeCriticalData just like the other fields.
if(serialData.message.MessageType == CRITICAL_MESSAGE_TYPE)
{
uint32_t critical_bits = serialData.critical_message.SomeCriticalData;
}
You can find a little more information on how this works by reading about structs. Bear in mind, that instances of the struct myMessage type will only ever contain one set of meaningful data at a time. Put more simply, if serialData contains CRITICAL_MESSAGE_TYPE data, then the data in serialData.critical_message is valid, but serialData.message is not --even though the language does not prevent you from accessing that data if you request it.
Edit: One more example; to calculate the checksum of a message, using the algorithm you've specified, you would probably want something like this (assuming you already know the message is completely within the buffer):
uint8_t calculate_checksum(struct myMessage *data)
{
uint8_t number_bytes = data->message.MessageLength;
uint8_t checksum = 0;
int i;
for(i=0; i<number_bytes; ++i)
{
//this performs a XOR with checksum and the byte
//in the message at offset i
checksum ^= data->raw[i];
}
return checksum;
}
You might need to adjust that function for bytes that aren't included, check to make sure that data != NULL, etc. but it should get you started.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flex wordwrap issue with multiple text instances
I have a scenario where I want to dynamically add words of text to a container so that it forms a paragraph of text which is wrapped neatly according to the size of the parent container. Each text element will have differing formatting, and will have differing user interaction options. For example, imagine the text " has just spoken out about ". Each word will be added to the container one at a time, at run time. The username in this case would be bold, and if clicked on will trigger an event. Same with the news article. The rest of the text is just plain text which, when clicked on, would do nothing.
Now, I'm using Flex 3 so I don't have access to the fancy new text formatting tools. I've implemented a solution where the words are plotted onto a canvas, but this means that the words are wrapped at a particular y position (an arbitrary value I've chosen). When the container is resized, the words still wrap at that position which leaves lots of space.
I thought about adding each text element to an Array Collection and using this as a datasource for a Tile List, but Tile Lists don't support variable column widths (in my limited knowledge) so each word would use the same amount of space which isn't ideal.
Does anyone know how I can plot words onto a container so that I can retain formatting, events and word wrapping at paragraph level, even if the container is resized?
A:
Why aren't you just using a mx:Text component and html text (you can call functions from htmlText), and apply different formatting using html tags.
For information on how to trigger a function from a htmlText field:
http://www.adobepress.com/articles/article.asp?p=1019620
| {
"pile_set_name": "StackExchange"
} |
Q:
If $f(x+1)=f(x)$ then?
Let $f: \ \mathbb{R} \rightarrow \mathbb{R}$ be a function such that $f(x+1) = f(x)$, $\forall x \in \mathbb{R}$.
Then which of the following statement(s) is/are true?
$f$ is bounded.
$f$ is bounded if it is continuous.
$f$ is differentiable if it is continuous
$f$ is uniformly continuous if it is continuous
I took the example of
$$f(x) = \begin{cases}
\tan(\pi x) & x \neq \displaystyle \frac{n}{2}\\
1 & x = \displaystyle \frac{n}{2}
\end{cases}$$
$n \in \mathbb{Z}$. This function satisfies the given condition and $f(x)$ is unbounded, so we can exclude the first option.
Now since the example we took is not continuous at $x = \frac{n}{2}$, I think if $f$ satisfies the given condition and is continuous then it is bounded. Is there any theorem which states: if $f$ is periodic and continuous then it is bounded? If yes, how to prove it?
I think we can even discard the third option by defining a triangle function
$$ f(x) =
\begin{cases}
x & 0 \leq x \leq \displaystyle \frac{1}{2}\\
f(x)=1-x & \displaystyle \frac{1}{2} < x \leq 1
\end{cases}$$
$$ f(x+k) = f(x), \ k \in \mathbb{Z} $$
now this function is continuous all over $\mathbb{R}$ but not differentiable at $x = \frac{n}{2}$.
The only left option is the 4th one. I know the basics of uniform continuity but not how to solve in this case. If $f$ is periodic and continuous, does this imply that $f$ is uniformly continuous? How to prove this if it is true?
A:
Point 2 and 4 essentially boil down to the following fact:
Consider
$$
f|_{[0,1]}
$$
that is $f$ restricted to the interval $[0,1]$. This interval is closed and bounded, hence compact.
You have that continuous functions on compact intervals are bounded and uniformly continuous. Can you conclude using the fact, that $f$ is periodic with period $1$?
| {
"pile_set_name": "StackExchange"
} |
Q:
'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository
I am not able to clone or push to a git repository at Bitbucket in Eclipse:
It's weird, because a day before I didn't have any problem. I have downloaded the sts 3 times with no luck. This error keeps showing. Also I have installed SourceTree and it says 'This is not a valid source path / URL':
If I use git commands to import the project, it works, but I wan't to use EGit for this task, since I am a newbie with git.
I don't know if this has to do with it, but in the same directory I have the android-adt-bundle. This one works pretty well, but the project lies on GitHub and not Bitbucket. Also, I'm working with another person and he is able to fetch and push data from and to the Bitbucket repository. I have read lots of posts but none of them have helped me out.
I'm using Windows 7 btw.
A:
Might also be bad SSL cert, fix the server
If you have a GIT server with an outdated or self-signed SSL cert fix the server, afterwards everything should run fine.
Insecure Hotfix: Let the client accept any certificate
The following solution is just a mere hotfix on client side and should be avoided as it compromises security of your credentials and content. There is a detailed explanation for this in "How can I make git accept a self signed certificate?" which offers more complex and more secure solutions you can try out if the following works in general.
In my case it was Eclipse using a different storage for the git config as the command line does and thus not having the option
git config http.sslVerify false
set (which I set using command line for the repo for working with invalid/untrusted SSL cert).
Adding the option insides Eclipse immediately resolves the issue. To add the option
open preferences via application menu Window => Preferences (or on OSX Eclipse => Settings).
Navigate to Team => Git => Configuration
click Add entry..., then put http.sslVerify in the key box and false in the value box.
Seems to be a valid solution for Eclipse 4.4 (Luna), 4.5.x (Mars) and 4.6.x (Neon) on different Operating systems.
A:
It happens due to the following Reasons:
1) Firewall.
2) Network Issues.
3) Proxy Settings Mismatch
4) Connected through different Router - which is not authorized within the network.
5) Git Proxy Authentication Details
A:
Finally I made it work thanks to the steps outlined in the Eclipse forum:
Set up the SSH key stuff
Download and install mysys git according to the github instructions at http://help.github.com/win-git-installation/
In C:/Users/you/ssh hide any existing keys (id_rsa and id_rsa.pub) in a subdirectory. If the ssh directory does not exist, create it. Of course, "you" is your username as the OS knows you.
From the start menu, run Git-Bash command shell (a regular DOS command shell will not work).
In the Git-Bash shell generate an rsa key based on your email (the one you registered at github):
ssh-keygen -t rsa -C "[email protected]"
and enter your pass phrase and confirm when asked.
The previous step should have created C:/User/you/ssh/id_rsa.pub which you can now open in a text editor and copy. At github, go to account settings, SSH Keys, add a key and paste this in the key box.
In Git-Bash again (notice the back-ticks in the next line):
eval `ssh-agent`
ssh-add C:/User/you/ssh/id_rsa
ssh [email protected]
Here is what you just did: You ran the ssh-agent which is needed by ssh-add. Then you used ssh-add to make note of the location of your key. Then you tried to ssh to GitHub. The response to this last command should be that you have successfully authenticated at GitHub but that you don't have shell access. This is just an authentication test. If the authentication was not successful, you'll have to sort that out. Try the verbose version:
ssh -v [email protected]
Assuming this worked....
In Eclipse, configure the remote push
Window > Show View > Git > Git Repositories will add a repository explorer window.
In the repository window, select the repository and expand and right-click Remotes and choose Create Remote.
Copy the GitHub repository URI from the GitHub repository page and paste it in the URI box.
Select ssh as the protocol but then go back to the URI box and add "git+" at the beginning so it looks like this:
git+ssh://[email protected]/UserName/ProjectName.git
In the Repository Path box, remove the leading slash
Hit Next and cross your fingers. If your get "auth fail", restart Eclipse and try step 5 again.
When you get past the authentication, in the next dialog select "master" for source ref, click "Add all branches spec" and "Finish".
Instead of using SSH [email protected] I did it with SSH [email protected].
Now I can push and import without any problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Repeatedly playing an equilibrium in a repeated game
What is a formal proof to this known fact about repeated games?
The situation in which, in every time step, the players play a Nash equilibrium in the basic game unconditioned on history, is a Nash equilibrium in the repeated game.
A:
Suppose all players play unconditioned Nash equilibria, except player $i$ who diverts and plays another strategy. The other strategy of player $i$ may depend on history. We have to show that player $i$'s payoff in the repeated game does not increase.
For every time-period t, define the following random variables:
$X^{t}$ - the utility of player $i$ in time t when all players, including player $i$, play the basic Nash equilibrium.
$Y_{h}^{t}$ (where $h$ is a history vector of length $t-1$) - the utility of player $i$ in time $t$ when player $i$ diverts and plays the alternative strategy while all other players continue to play the basic Nash equilibrium.
$Y^{t}$ - the utility of player $i$ in time $t$ when player $i$ diverts while all other players continue to play the basic Nash equilibrium:
$$Y^{t}=\sum_{h}Prob[h]\cdot Y_{h}^{t}$$
By definition of a Nash equilibrium, for every time $t$
and for every history $h$:
$$E[Y_{h}^{t}]\leq E[X^{t}]$$
Hence also:
$$E[Y^{t}]\,=\,\sum_{h}Pr[h]\cdot E[Y_{h}^{t}]\,\leq\,\sum_{h}Pr[h]\cdot E[X^{t}]\,\leq\,E[X^{t}]\cdot\sum_{h}Pr[h]\,\leq\,E[X^{t}]$$
Summing over the entire series, and using the fact that the expectation of a sum is the sum of expectations:
$$E[\sum_{t=1}^{T}Y^{t}]\leq E[\sum_{t=1}^{T}X^{t}]$$
So the player cannot gain by deviating.
Thanks to @denesp for verifying this proof!
| {
"pile_set_name": "StackExchange"
} |
Q:
Sorting a long string with a composite of strings and integers + symbols
The code below is to sort a file containing the following info (eg. input.txt):
rango burrito apri%cot 1 -10 3.5 8 5 tesla 10 hyphen -4.7 2 bus 20 cat vul$ture m0nkey -9999999
The output should have the symbols removed and then strings and integers sorted in ascending order, but the order retaining the type of the original list. for example, the first item is a string in both input and output and the final item for example is an int.
When the script is run the output looks as follows:
$ ./sort_input.py input.txt
apricot burrito bus -9999999 -47 -10 1 2 cat 5 hyphen 8 10 m0nkey 20 rango tesla vulture 35
I've written code that looks as follows and I'm sure this can be improved a lot:
Reading the file first, then splitting on white space into an array of strings: \$O(n)\$ complexity where \$n\$ is the length of the original string
def listify(input_file):
with open(input_file) as f:
for line in f:
list_of_strings = line.strip().split()
return list_of_strings
Using the list of strings and converting it into a typed list, but removing any symbols first using the method below: \$O(n)\$ complexity for the typed list, then \$O(k)\$ for each string in that list to remove symbols - so total complexity is \$O(n)*O(k)\$.
def typed_list(untyped_list):
""" converts an untyped list to a typed list of strings and integers """
typed_list = []
for item in untyped_list:
item_without_symbol = remove_any_symbols(item)
try:
typed_list.append(int(item_without_symbol))
except ValueError:
typed_list.append(item_without_symbol)
return typed_list
Method to remove any symbols, which I use in the function above. \$O(k)\$ complexity where \$k\$ is the length of the string:
def remove_any_symbols(s_string):
"""We take a string and remove any symbols from it. """
acceptable_characters = string.ascii_letters + string.digits
no_s_string_list = [c for c in s_string if c in acceptable_characters]
if s_string.startswith("-"):
return "-"+''.join(no_s_string_list)
else:
return ''.join(no_s_string_list)
I then use the typed list that's generated above to sort integers and strings separately. Then using the original list to generate a list with the same type items in their original order. \$O(n log n)\$ complexity for both sorting functions and then \$O(n)\$ for adding to the final output list.
def sort_em_up(no_symbol_list=None):
"""we take a list here, note the type, sort and then return a sorted
list"""
sorted_int = sorted([int(i) for i in no_symbol_list if isinstance(i, int)])
sorted_str = sorted([s for s in no_symbol_list if isinstance(s, str)])
final_sorted_list = []
i = j = 0
for item in no_symbol_list:
if isinstance(item, int):
final_sorted_list.append(str(sorted_int[i]))
i += 1
else:
final_sorted_list.append(sorted_str[j])
j += 1
return ' '.join(final_sorted_list)
if __name__=="__main__":
input_file = sys.argv[1]
list_of_strings = listify(input_file)
print(sort_em_up(typed_list(list_of_strings)))
A:
listify function
Since, as you mentioned in the comments, the function is meant to read a single first line from a file only - you can use the next() built-in function:
def listify(filename):
"""Reads the first line from a file and splits it into words."""
with open(filename) as input_file:
return next(input_file).strip().split()
remove_any_symbols function
You can actually pre-define the allowed characters as a constant - no need to re-define them for every function call. You can also make it a set for faster lookups:
ACCEPTABLE_CHARACTERS = set(string.ascii_letters + string.digits)
def remove_any_symbols(input_string):
"""Removes any symbols from a string leaving the leading dashes."""
filtered_characters = [c for c in input_string if c in ACCEPTABLE_CHARACTERS]
prefix = "-" if input_string.startswith("-") else ""
return prefix + ''.join(filtered_characters)
Or, a regex-based version (less understandable overall, but see if it is going to be faster):
PATTERN = re.compile(r"""
(
(?<!^)- # dash not at the beginning of a string
| # or
[^A-Za-z0-9\-] # not letters, digits and dashes
)+
""", flags=re.VERBOSE)
def remove_any_symbols(input_string):
"""Removes any symbols from a string leaving the leading dashes."""
return PATTERN.sub("", input_string)
Pre-process the complete string
With regexes, it would also be possible to pre-process the input string as a whole, checking for the dashes at the beginning of words. This may lead to applying remove_any_symbols() on the complete input string read from a file:
PATTERN = re.compile(r"""
(
(?<!(?:^| ))- # dash not at the beginning of a word
| # or
[^A-Za-z0-9\- ] # not letters, digits, dashes and spaces
)+
""", flags=re.VERBOSE)
def remove_any_symbols(input_string):
"""Removes any symbols from a string leaving the leading dashes for each word."""
return PATTERN.sub("", input_string)
if __name__=="__main__":
input_file = sys.argv[1]
with open(input_file) as f:
data = next(f).strip()
list_of_words = remove_any_symbols(data).split()
print(sort_em_up(typed_list(list_of_words)))
| {
"pile_set_name": "StackExchange"
} |
Q:
Linux USB CDC sending unexpected characters
I have a USB device which enumerates correctly as a CDC interface. /dev/ttyACM1 is created, and I can ultimately communicate over the endpoints.
But alas, in the first few seconds after enumeration, Some Mysterious Thing on the Linux host side sends AT<CR>AT<CR>AT<CR> to the device, then a few seconds after that, the strange sequence 0x7E 0x00 0x78 0xF0 0x7E. The first is evidently Some Mysterious Thing trying to wake up a modem. The second is presumably similar in intent.
Does anyone know where these unsolicited bytes come from?
I've tried two different VIDs --- 0x1CBE, as the device is a TI chip and that's their default, and 0xF055, in case the TI VID was triggering some alternate driver. Same behavior. The device descriptor looks pretty completely vanilla: CDC class, subclass 0, protocol 0, one configuration.
The host is Ubuntu 14.04.1 LTS, 64-bit. /sys/bus/usb/drivers/ says that it is using the cdc_acm driver. Following is the output from usbmon; the mysterious extra bytes are at the end.
Note that in this run, it was enumerating with USB_CDC_ACM_PROTO_AT_V25TER; I also tried USB_CDC_PROTO_NONE but the result was the same.
ffff8801466ff180 3244792454 S Ci:2:029:0 s 80 06 0100 0000 0012 18 <
ffff8801466ff180 3244792654 C Ci:2:029:0 0 18 = 12011001 02000040 55f00200 00010102 0301
ffff8801466ff180 3244792709 S Ci:2:029:0 s 80 06 0200 0000 0009 9 <
ffff8801466ff180 3244792934 C Ci:2:029:0 0 9 = 09024300 020105c0 00
ffff8801466ff180 3244792997 S Ci:2:029:0 s 80 06 0200 0000 0043 67 <
ffff8801466ff180 3244793306 C Ci:2:029:0 0 67 = 09024300 020105c0 00090400 00010202 01040524 00100104 24020605 24060001
ffff8801466ff180 3244793377 S Ci:2:029:0 s 80 06 0300 0000 00ff 255 <
ffff8801466ff180 3244793570 C Ci:2:029:0 0 4 = 04030904
ffff8801466ff180 3244793632 S Ci:2:029:0 s 80 06 0302 0409 00ff 255 <
ffff8801466ff180 3244793802 C Ci:2:029:0 0 30 = 1e035300 61007400 50006100 71003a00 20007300 65007200 69006100 6c00
ffff8801466ff180 3244793861 S Ci:2:029:0 s 80 06 0301 0409 00ff 255 <
ffff8801466ff180 3244794065 C Ci:2:029:0 0 28 = 1c034800 69006700 68006500 72002000 47007200 6f007500 6e006400
ffff8801466ff180 3244794131 S Ci:2:029:0 s 80 06 0303 0409 00ff 255 <
ffff8801466ff180 3244794309 C Ci:2:029:0 0 18 = 12033100 32003300 34003500 36003700 3800
ffff8801466ff000 3244794739 S Co:2:029:0 s 00 09 0001 0000 0000 0
ffff8801466ff000 3244794897 C Co:2:029:0 0 0
ffff8801466ff000 3244794959 S Ci:2:029:0 s 80 06 0305 0409 00ff 255 <
ffff8801466ff000 3244795140 C Ci:2:029:0 0 54 = 36035300 65006c00 66002000 50006f00 77006500 72006500 64002000 43006f00
ffff8801466ffe40 3244795245 S Ci:2:029:0 s 80 06 0304 0409 00ff 255 <
ffff8801466ffe40 3244795390 C Ci:2:029:0 0 44 = 2c034100 43004d00 20004300 6f006e00 74007200 6f006c00 20004900 6e007400
ffff8801466d1f00 3244796605 S Co:2:029:0 s 21 22 0000 0000 0000 0
ffff8801466d1f00 3244796764 C Co:2:029:0 0 0
ffff8801466d1f00 3244796791 S Co:2:029:0 s 21 20 0000 0000 0007 7 = 80250000 000008
ffff8801466d1f00 3244796931 C Co:2:029:0 0 7 >
ffff8801466ffe40 3244812303 S Ii:2:029:1 -115:1 16 <
ffff8801477a69c0 3244812323 S Co:2:029:0 s 21 22 0003 0000 0000 0
ffff8801477a69c0 3244812387 C Co:2:029:0 0 0
ffff8801466ff480 3244812454 S Bi:2:029:2 -115 128 <
ffff8801466ff600 3244812457 S Bi:2:029:2 -115 128 <
ffff8801466ff6c0 3244812458 S Bi:2:029:2 -115 128 <
ffff8801466ff780 3244812459 S Bi:2:029:2 -115 128 <
ffff8801466ff840 3244812460 S Bi:2:029:2 -115 128 <
ffff8801466ff900 3244812460 S Bi:2:029:2 -115 128 <
ffff8801466fff00 3244812461 S Bi:2:029:2 -115 128 <
ffff8801466ff9c0 3244812462 S Bi:2:029:2 -115 128 <
ffff8801466ffa80 3244812463 S Bi:2:029:2 -115 128 <
ffff8801466ffd80 3244812463 S Bi:2:029:2 -115 128 <
ffff8800971e8240 3244812464 S Bi:2:029:2 -115 128 <
ffff8801473c2f00 3244812465 S Bi:2:029:2 -115 128 <
ffff8801473c2e40 3244812465 S Bi:2:029:2 -115 128 <
ffff8801473c2d80 3244812466 S Bi:2:029:2 -115 128 <
ffff8801473c2cc0 3244812467 S Bi:2:029:2 -115 128 <
ffff8801473c2c00 3244812468 S Bi:2:029:2 -115 128 <
ffff8801477a6300 3244812483 S Co:2:029:0 s 21 20 0000 0000 0007 7 = 00e10000 000008
ffff8801477a6300 3244812634 C Co:2:029:0 0 7 >
ffff8801477a6300 3244813414 S Co:2:029:0 s 21 22 0002 0000 0000 0
ffff8801477a6300 3244813510 C Co:2:029:0 0 0
ffff8801473b96c0 3244913682 S Co:2:029:0 s 21 22 0003 0000 0000 0
ffff8801473b96c0 3244913763 C Co:2:029:0 0 0
ffff8801473c2b40 3244913835 S Bo:2:029:1 -115 1 = 41
ffff8801473c2b40 3244913882 C Bo:2:029:1 0 1 >
ffff8801473c2b40 3245014062 S Bo:2:029:1 -115 1 = 54
ffff8801473c2b40 3245014160 C Bo:2:029:1 0 1 >
ffff8801473c2b40 3245114308 S Bo:2:029:1 -115 1 = 0d
ffff8801473c2b40 3245114394 C Bo:2:029:1 0 1 >
ffff8801473b9480 3245302014 S Co:2:029:0 s 21 20 0000 0000 0007 7 = 00c20100 000008
ffff8801473b9480 3245302184 C Co:2:029:0 0 7 >
ffff8801473c2b40 3248486129 S Bo:2:029:1 -115 1 = 41
ffff8801473c2b40 3248486239 C Bo:2:029:1 0 1 >
ffff8801473c2b40 3248586369 S Bo:2:029:1 -115 1 = 54
ffff8801473c2b40 3248586488 C Bo:2:029:1 0 1 >
ffff8801473c2b40 3248686655 S Bo:2:029:1 -115 1 = 0d
ffff8801473c2b40 3248686737 C Bo:2:029:1 0 1 >
ffff8801473c2b40 3251487738 S Bo:2:029:1 -115 1 = 41
ffff8801473c2b40 3251487836 C Bo:2:029:1 0 1 >
ffff8801473c2b40 3251587976 S Bo:2:029:1 -115 1 = 54
ffff8801473c2b40 3251588088 C Bo:2:029:1 0 1 >
ffff8801473c2b40 3251688249 S Bo:2:029:1 -115 1 = 0d
ffff8801473c2b40 3251688357 C Bo:2:029:1 0 1 >
ffff8801473c2b40 3254489075 S Bo:2:029:1 -115 5 = 7e0078f0 7e
ffff8801473c2b40 3254489188 C Bo:2:029:1 0 5 >
ffff8801473c2b40 3257488394 S Bo:2:029:1 -115 5 = 7e0078f0 7e
ffff8801473c2b40 3257488549 C Bo:2:029:1 0 5 >
A:
Those AT commands are being sent by ModemManager.
It is possible to add a udev rule to tell ModemManager to leave your device alone if it is a problem. Just add a file in /etc/udev/rules.d with a name like foo.rules with content like this:
ATTRS{idVendor}=="12ba", ATTRS{idProduct}=="23ef", ENV{ID_MM_DEVICE_IGNORE}="1"
| {
"pile_set_name": "StackExchange"
} |
Q:
Strange issue giving margin right to my menu items
I'm trying to turn a desktop design to a tablet one.
And I'm doing now a media query for 768px, and so I have my menu with 768px, and I want to give margin-left and margin-right to my menu items.
And when I give margin-left, everything works fine, but margin-right is not working, and my last menu item that is my search input appears outside my 768px.
Can someone please help me understanding what is happening? What I have so far:
My JSFiddle with the problem: http://jsfiddle.net/ra3zc/3/
My HTML:
<section id="menu-container">
<nav id="menu">
<ul>
<li><a href="#">Link 1</a>
<ul>
<li style="border-top:none;"><a href="#">Link 1.1</a></li>
<li><a href="#">Link 1.2</a></li>
</ul>
</li>
<li><a href="#">Link 2</a>
<ul>
<li style="border-top:none;"><a href="#">Link 2.1</a></li>
<li><a href="#">Link 2.2</a></li>
</ul>
</li>
<li><a href="#">Link 3</a>
<ul>
<li style="border-top:none;"><a href="#">Link 3.1</a></li>
<li><a href="#">Link 3.2</a></li>
</ul>
</li>
<li id="search_list">
<form id="search">
<input name="q" type="text" size="40" placeholder="Search..." />
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</li>
</ul>
</nav>
</section>
My CSS is a bit long so I’m not putting it here.
A:
#menu ul
{
list-style-type: none;
width: 768px;
margin-left: 5px;
}
your #menu ul should not be 768px because it occupied all the #menu range, try to change it to 500px or less.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mod_Rewrite, search for non-existing files in a different folder
I have a templates system in which I use images and other kinds of files, so here is a sample of a few templates and their images
/templates/template1/images/image1.jpg
/templates/template1/images/header/red/new/image1.jpg
/templates/template1/image2.jpg
/templates/template2/images/image2.jpg
/templates/template2/image2.jpg
Now, some times the templates miss an image or a file, in those cases I want to redirect the user to the "default" template, while keeping the rest of the url.
So for the examples given, if the image is not found the user should be redirected to
/templates/default/images/image1.jpg
/templates/default/images/header/red/new/image1.jpg
/templates/default/image2.jpg
/templates/default/images/image2.jpg
/templates/default/image2.jpg
This is my attempt at making this work, it's defined in the virtual host file
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/templates/default/(.*)$
RewriteRule ^/templates/(.*)/(.*) /templates/default/$2 [R]
this right now
redirects /templates/template1/images/image1.jpg to /templates/default/image1.jpg and then throws a 500 error.
What am I doing wrong in here?
A:
I'm not sure why you're getting the 500, but the ReqriteRule will have problems with multiple sub-directories because of the greediness of the first .*.
Consider the request for /templates/template1/images/header/red/new/image1.jpg. If this file does not exist then in ^/templates/(.*)/(.*), the first (.*) will match all of "template1/images/header/red/new" and the second (.*) will match "image1.jpg" and so you'll get redirected to "/templates/default/image1.jpg".
A better rule:
RewriteRule ^/templates/[^/]+/(.*)$ /templates/default/$1 [R]
Or, if you know that template directories can only have alpha-numerical characters, the underscore or the hyphen, this is better still:
RewriteRule ^/templates/[a-zA-Z0-9_-]+/(.*)$ /templates/default/$1 [R]
Try to keep regexes as specific as possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Цикл по массиву объектов
Сервер отдает JSON c массивом объектов, перебираю их обычным for.
for(var i = 0; i < data[0].target.length; i++){
if(data[0].target[i].code == Geo){
$('.old').html(data[0].target[i].price_high + ' ' + data[0].target[i].currency);
$('.new').html(data[0].target[i].price + ' ' + data[0].target[i].currency);
}
}
Будет-ли этот код лучше работать с конструкцией for in и есть ли в ней преимущества в конкретно этой задаче?
A:
В плане производительности так же. Но нет гарантии, что все объекты(если у вас объект, а не массив) будут иметь ключи по возростанию. Может быть data[0], data[1], data[3], а data с ключом 2 не окозалось и for тут выкинет ошибку, а for in нет.
For in не викинет ошибку
var data = {
0: 'bla',
1: 'bla2',
3: 'bla3',
}
for (key in data) {
console.log(data[key]);
}
For викинет ошибку
var data = {
0: 'bla',
1: 'bla2',
3: 'bla3',
}
for (ar i = 0; i < data.length; i++) {
console.log(data[i]);
}
Ваш цикл в for in
for(key in data[0].target){
if(data[0].target[key].code == Geo){
$('.old').html(data[0].target[key].price_high + ' ' + data[0].target[key].currency);
$('.new').html(data[0].target[key].price + ' ' + data[0].target[key].currency);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding the number of occurences of an integer in multidimensional array in C++
I wish to find the number of occurrences of a number taken as input in the given multidimensional array defined by the logic below:
...
int n,x,count=0;
cin>> n >> x;
int a[n][n] ;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
a[i][j]= i*j ;
}
}
for( int i=1;i<=n;i++)
{
for( int j=1;j<=n;j++)
{
if(a[i][j] == x)
++count;
}
}
cout<< count ;
...
For eg., if I give input as 6(n) and 12(to find its number of occurrences, x here). The multidimensional array looks something like this:
1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
6 12 18 24 30 36
Now, the number of occurences of 12 here is 4(count).
But when I give n as 10 and x as 5, the program stops working. I can't seem to find what is happening. Can someone help me on this?
Also in what way can I modify my code?
How can I handle the case when n is as large as 1000 or 10k without changing the logic of the program?
A:
Indices in C/C++ starts at 0. If an array is declared to have size n as in int a[n] the only valid indices are: 0,1,...,n-1 i.e. [0,n[
If you go out of bound undefined behaviour is expected. That should be your case.
Fix the loops as follows (note the new bounds and the +1 in i and j)
int a[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
a[i][j]= (i+1)*(j+1) ;
| {
"pile_set_name": "StackExchange"
} |
Q:
LeetCode 01: Matrix challenge
Recently, I've solved the "01 Matrix" LeetCode problem and the solution was accepted by the LeetCode OJ:
Given a matrix consists of 0 and 1, find the distance of the nearest 0
for each cell.
The distance between two adjacent cells is 1.
Example:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are
adjacent in only four directions: up, down, left and right.
The idea behind the solution above is to use Dynamic Programming - starting with 0 cells work outwards putting not processed cells on the queue:
from collections import deque
class Solution(object):
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix:
return matrix
row_length = len(matrix)
col_length = len(matrix[0])
queue = deque()
# put all 0 cells on queue, set all other cells to a big number
for row_index in range(row_length):
for col_index in range(col_length):
if matrix[row_index][col_index] == 0:
queue.append((row_index, col_index))
else:
matrix[row_index][col_index] = 10000
# work from the 0 cells outwards while the queue is not empty
while queue:
row_index, col_index = queue.popleft()
for i, j in [(row_index - 1, col_index),
(row_index + 1, col_index),
(row_index, col_index - 1),
(row_index, col_index + 1)]:
if 0 <= i < row_length and \
0 <= j < col_length and \
matrix[i][j] > matrix[row_index][col_index] + 1:
matrix[i][j] = matrix[row_index][col_index] + 1
queue.append((i, j))
return matrix
Even though the code works, I am not happy with the readability, in particular:
setting the non-zero cells to "magical" 10000 does not look good
getting the cell neighbors and checking if they are not out-of-bounds seems overly complicated
What would you improve code style and organization or time and space complexity wise?
A:
By storing the return value in a different variable and placing the distance in the queue, the magic number can be avoided:
class Solution(object):
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix:
return matrix
row_length = len(matrix)
col_length = len(matrix[0])
result = [[None for j in range(col_length)] for i in range(row_length)]
queue = deque()
# put all 0 cells in queue, set all other cells to a big number
for row_index in range(row_length):
for col_index in range(col_length):
if 0 == matrix[row_index][col_index]:
queue.append((row_index, col_index, 0))
# work from the 0 cells outwards while the queue is not empty
while queue:
i, j, dist = queue.popleft()
if 0 <= i < row_length and 0 <= j < col_length and result[i][j] is None:
result[i][j] = dist
queue.append((i-1, j, dist+1))
queue.append((i+1, j, dist+1))
queue.append((i, j-1, dist+1))
queue.append((i, j+1, dist+1))
return result
| {
"pile_set_name": "StackExchange"
} |
Q:
XPath to select the nodes that matches
I have a XML that looks like this:
<?xml version="1.0"?>
<RootName>
<RandomNode v="someValue"/>
<Series>
<Idendity v="C16"/>
<CodeOut v="C41073"/>
<Period>
<TimePeriod v="2013-07-18T22:00Z/2013-07-19T22:00Z"/>
<Resolution v="PT60M"/>
<Interval>
<Pos v="1"/>
<Qty v="14.1"/>
</Interval>
<Interval>
<Pos v="2"/>
<Qty v="20.7"/>
</Interval>
And I need a xPath that returns all the Period nodes which matches these conditions:
The node CodeOut/CodeIn has the value of any of the values that I have in an array
This node CodeOut can be named CodeOut or CodeIn, but only one of these
The date on TimePeriod must match
The only node that repeates over the xml is the Series node. In other words, there is only one Period per Series, but there is a lot of different Series.
For example, get all Period nodes which have his Codeout or CodeIn value to being C41073 or B85028 and the date being 2013-07-18.
I tried, to match the multiple names, using something like:
//*[@v="C41073"] | //*[@v="B85028"] | ...
But I think it will be better if only matches the correct nodes, just in case some other node has the same value, isn't it?
I was searching to use something like "contains", but it works in a different way.
I'm using .Net, if that matters, and I'm going to use this xPath on the .SelectNodes() function.
EDIT:
Something strange is happening. Maybe the syntax is not correct. Look at this tests:
This: doc.SelectNodes("/*")(0).Name is returning RootName
This: doc.SelectNodes("/*/*").Count is returning 912
This: doc.SelectNodes("/*/*")(11).Name is returning Series
But this: doc.SelectNodes("/RootName").Count is returning 0
This: doc.SelectNodes("/*/Series").Count is returning 0
And this: doc.SelectNodes("/*/RootName").Count is returning 0
Making all the other xPath sequences suggested in answers not working.
EDIT:
Ok, it was the namespace, I did this:
Dim xmlnsManager As Xml.XmlNamespaceManager = New System.Xml.XmlNamespaceManager(doc.NameTable)
xmlnsManager.AddNamespace("ns", "http://example")
And adding ns: before every element node name in the xPath sequence. (See this for more information about it: Is it possible to specify the namespace prefix just once in a xpath expression?)
A:
To select all of the Period elements limited just by the CodeIn/CodeOut list, you could do something like this:
/RootName/Series[(CodeOut/@v = 'C41073') or (CodeOut/@v = 'B85028') or (CodeIn/@v = 'C41073') or (CodeIn/@v = 'B85028')]/Period
If you don't want to list each item in the list as a separate condition, you could concatenate them all together into a delimited list and then use the contains function, like this:
/RootName/Series[(CodeOut/@v and contains('|C41073|B85028|', concat('|', CodeOut/@v, '|'))) or (CodeIn/@v and contains('|C41073|B85028|', concat('|', CodeIn/@v, '|')))]/Period
Notice, to avoid the problem with a substring like C4 matching the full value, like C41073, you need to concatenate the delimiter before and after the attribute value. Also, you need to make sure your delimiter exists at the beginning and ending of the delimited list of values. Also, whatever delimiter you choose must be an invalid character which would never occur in any of the values in the list.
However, limiting it also by the TimePeriod will be a bit more problematic, since it appears to be a non-standard time range value. If the start and end times were stored in separate nodes, it would be easier.
If all you need to do is match an exact TimePeriod value, for instance, you could just do something like this:
/RootName/Series[(CodeOut/@v = 'C41073') or (CodeOut/@v = 'B85028') or (CodeIn/@v = 'C41073') or (CodeIn/@v = 'B85028')]/Period[TimePeriod/@v = '2013-07-18T22:00Z/2013-07-19T22:00Z']
You can split the string on the / character, with substring-before(TimePeriod, '/') and substring-after(TimePeriod, '/'), but unless you are using XPath 2.0, you can't compare strings to see if they are greater or less than. If you are using 2.0, you could compare each of those substrings with the search value using the compare function, but it's still messy. It's probably best to handle that time-range comparison in your .NET code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Empty array (which's not empty)
while($row = mysql_fetch_row($result)){
preg_match('#<span id="lblNumerZgloszenia" style="font-weight:bold;font-style:italic;">([^<]*)<\/span>#',$row[1],$matches);
$query2 = 'UPDATE content_pl SET kategoria_data='.$matches[1].' WHERE id='.$row[0].';';
mysql_query($query2);
}
I'm doing this preg_match to get the span contents into $matches array.
When I do a print_r($matches), it shows the right results but when I use $matches[1], it browser tells me that there is no such index.
EDIT: print_r shows
[...]Array ( [0] => TOW: (210) 252250, (220) 01-07-2002 [1] => TOW: (210) 252250, (220) 01-07-2002 ) Array ( [0] => TOW: (210) 252251, (220) 01-07-2002 [1] => TOW: (210) 252251, (220) 01-07-2002 ) Array ( [0] => TOW: (210) 252252, (220) 01-07-2002 [1] => TOW: (210) 252252, (220) 01-07-2002 ) Array ( [0] => TOW: (210) 252253, (220) 01-07-2002 [1] => TOW: (210) 252253, (220) 01-07-2002 )[...]
A:
You're doing this in a while loop which means it's likely happening more than once. If you just print_r($matches); exit; you might notice that you get what you're expecting, but that's just one of the iterations of your loop.
Most likely, there is at least one case where you do not find any matches. You should wrap your second mysql_query (which is deprecated, BTW - you might want to switch to PDO if your project is small) with an if statement that checks the return value of your preg_match call. Only run the query if preg_match returns > 0
| {
"pile_set_name": "StackExchange"
} |
Q:
Uploading files and JSON data in the same request with jquery ajax?
I need to upload image file to canvas. Assuming the canvas already has objects, then I have to grab the json first, upload the image, and reload the page. The problem is, I can't send the uploaded image file together with json data in the same ajax request. Here is my code:
<canvas id="canvas"></canvas>
<form enctype="multipart/form-data" id="myform" method="post" action="">
<input type="file" name="image" id="image" />
... (other input tags)
<button type="submit" id="upload">Upload</button>
</form>
$('#upload').bind("click",function(event) {
event.preventDefault();
var json = JSON.stringify(canvas.toDatalessObject());
var url = "upload.php";
var data = new FormData($('#myform')[0]);
var dataString = JSON.stringify(data.serializeObject());
$.post(url, { json: json, data: dataString }, 'json');
});
Whilst I get the json data just fine, the form data are just empty. Is there any other better solution?
A:
remove
var dataString = JSON.stringify(data.serializeObject());
,it's already Json,
and try to set ajax properties:
processData: false,
contentType: false,
| {
"pile_set_name": "StackExchange"
} |
Q:
Convergence tests for a series
I have this infinite sum
$$\sum_{n=1}^\infty n^2\sin \left(\frac{1}{n^2}\right)$$
anyone knows if this series is converging and if so how do I prove it?
A:
A big hint: for a series $\sum_n a_n$ to converge, a necessary (not sufficient, but necessary) condition is that $\lim_{n\to\infty} a_n =0$.
However, here, since $\lim_{x\to 0} \frac{\sin x}{x} = \sin'(0)=\cos 0=1$...
| {
"pile_set_name": "StackExchange"
} |
Q:
Easiest way to build a Linux live CD
I want to demonstrate a certain in-house application as a Linux Live CD. I'd like to basically take a live CD "source" (preferably something based on Fedora/RedHat/Debian/Ubuntu which I know reasonably well), modify it slightly to add the app + it's dependencies (Java VM etc.) and repackage it so that the app boots automatically under X. What's the easiest way to do that?
A:
SUSE Studio
Build an appliance — or your own
custom Linux distro — with a few mouse
clicks. Customize it to your heart's
content, and share it with the world!
... it doesn't get much easier.
| {
"pile_set_name": "StackExchange"
} |
Q:
C: Using hexadecimal to represent UTF-8 (like Euro)
I'm new to the world of C, so bear with me. And I've searched high and low for an answer to this, but have yet to understand it clearly.
I am trying to input and output, for example, the Euro symbol € (an extended character value). I want to use hexadecimal byte combinations. For the Euro, they are: 0xE2, 0x82, 0xAC . I understand that in C++, you can simply use \u20ac, which is not the case in C.
I have tried assigning the hex values to an int, but that did not work for me. I have also tried using the Euro symbol's decimal value.
The idea behind my program is to take user input (e.g. €100) and convert it to a different currency. So differentiating the currency symbols is my main issue at hand. Is there another way to go about this than what I have tried?
A:
Basically € can be represented with 3 char's.
So you can do it like this.
char str[] = { 0xE2, 0x82, 0xAC, 0x00 };
printf("str: \"%s\"\n", str);
The output:
str: "€"
| {
"pile_set_name": "StackExchange"
} |
Q:
How to hide password in a url
There is a JSP script for login to a Server. Currently user credentials are being accepted through HTTP Header and the login.jsp file is so designed that once the user provides credentials the user is redirected to a redirectURL which is a fully qualified URL containing Username and Password in query string and hence the user is able to access the page he wants but problem is the password is being visible in the browser address bar.
So, what are the ways by which I can hide the user password in the url.
A:
Others suggested using POST, which is the correct method for this. But it is not enough to guarantee that a man-in-the-middle can't see the password. In order to prevent that you should enable TLS (SSL) on your server and serve the page over https
| {
"pile_set_name": "StackExchange"
} |
Q:
How does a supercharger differ from a turbocharger?
What is the difference between superchargers and turbochargers?
I looked it up before but I really don't understand what the difference is.
A:
Both turbochargers and superchargers perform the same function: compress air that will be fed into the engine. In other words, they are glorified air compressors.
As with any compressor, both need energy in order to compress the air, which is where the difference between the two devices becomes relevant.
Superchargers are belt-driven or chain-driven, so the compressor rotor is mechanically coupled to the rotation of the engine; when the engine rotates, the supercharger vanes rotate and compress air.
Turbochargers use a completely different energy source - hot exhaust gases. The idea here is to make use of the hot gases to spin a turbine, which turns a shaft that turns the compressor vanes. As the hot exhaust gases perform work in turning the shaft, they cool down.
The difference is concisely captured on this HowStuffWorks page:
Unlike turbochargers, which use the exhaust gases created by
combustion to power the compressor, superchargers draw their power
directly from the crankshaft. Most are driven by an accessory belt,
which wraps around a pulley that is connected to a drive gear. The
drive gear, in turn, rotates the compressor gear. The rotor of the
compressor can come in various designs, but its job is to draw air in,
squeeze the air into a smaller space and discharge it into the intake
manifold.
Comparing the two...
Both technologies have their advantages and disadvantages; the "better" choice depends on a number of factors which include design philosophy, cost, available space, controller complexity and desired torque/power gains.
Having said that, there are plenty of "forced-induction" configurations out in the wild, ranging from single superchargers to twin-turbo and three-turbo (!) setups. In fact, some VW engines operate a turbocharger and a supercharger in tandem.
A:
A turbo is a type of supercharger. Superchargers all compress the intake air before pushing it into the engine. A turbine-supercharger (aka "turbo") is powered by a turbine wheel connected to the exhaust. Other superchargers are driven via a pulley system directly from the engine.
That's all really. Conceptually speaking, a centrifugal supercharger and turbocharger are the closest in terms of performance and function. They both provide increasing levels of boost as RPM increases (within the limits of their efficiency). The only difference is that a centrifugal charger does not need to "spool up" because its speed is dictated by RPM, while a turbo's speed is dictated by the speed and volume of the exhaust gases, so there's a small amount of "lag" while the gases increase in proportion to how much boost is fed in.
Pro tip: it is possible to run some superchargers without installing an intercooler because they produce much less heat than a turbo. Although they eat a lot of torque in the process of increasing performance, so they are less efficient than turbos and will be worse for fuel consumption.
| {
"pile_set_name": "StackExchange"
} |
Q:
asp.net user control changes not getting picked up
I have made some changes inside the user control, to both the code behind and aspx. When i run my local development or the dev site (posted the changes to dev site). I don't see my changes. I recycled the app pools and restarted the dev site as well.
I have placed break points in the code. The code never hits those. When i mouse over the break points after the page has executed, i get unreachable code message (yellow popop and attached).
I am only able to see my changes (local dev and dev site) after deleting asp.net temp internet files on my local machine and dev box.
I have just posted the code to the staging site and it is doing the same thing. Here i can't delete the asp.net temp files during the middle of the day or restart iis.
The project is
VS 2012
ASP.NET 4.5
IIS 7
Kentico CMS - Classic Asp.Net
This is the first time i am seeing this behavior. Has some one else seen this and how did you fix it?
Thanks.
A:
Kentico had a caching bug that got fixed in HotFix upgrade 7.0.86. I have applied most recent HotFix 7.0.92 and on dev and staging sites, it looks fixed now.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET Core TagHelper with content from ViewBag - it's empty
I have a simple ToastTagHelper:
[HtmlTargetElement("toast")]
public class ToastTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
string message = output.Content.GetContent();
if (string.IsNullOrWhiteSpace(message))
{
output.TagName = ""; // this should not output anything!
return;
}
output.TagName = "div";
output.Attributes.Add("id", "toast");
output.Content.SetContent(message.Trim());
}
}
Now, here's how I use it in my _Layout:
<toast>@ViewBag.Message</toast>
And I initialize ViewBag.Message in my Controller when I need it. The problem is even it's initialized I get the following:
[message text]
NO TAGS here. I put a breakpoint and here's what happens - when it hits Process method, the Content is still empty. And then later somewhere down the pipe it initializes the content from ViewBag but it's too late.
So, how can I make it work?
A:
For this to work I had to override ProcessAsync instead of Process and call await output.GetChildContentAsync() in place of output.Content.GetContent().
| {
"pile_set_name": "StackExchange"
} |
Q:
Python pandas functions work in shell not in script
I have a pandas dataframe in which I'm trying to run some operations on a column of string values which includes some missing data being interpreted as float('nan'), equivalent to:
df = pd.DataFrame({'otherData':[1,2,3,4],'stringColumn':[float('nan'),'Random string one... ','another string.. ','a third string ']})
DataFrame contents:
otherData stringColumn
1 nan
2 'Random string one... '
3 'another string.. '
4 ' a third string '
I want to clean the stringColumn data of the various trailing ellipses and whitespace, and impute empty strings, i.e. '', for nan values.
To do this, I'm using code equivalent to:
df['stringColumn'] = df['stringColumn'].fillna('')
df['stringColumn'] = df['stringColumn'].str.strip()
df['stringColumn'] = df['stringColumn'].str.strip('...')
df['stringColumn'] = df['stringColumn'].str.strip('..')
The problem I'm encountering is that when I run this code in the script I've written, it doesn't work. There are still nan values in my 'stringColumn' column, and there are still some, but not all, ellipses. There are no warning messages. However, when I run the exact same code in the python shell, it works, imputing '' for nan, and cleaning up as desired. I've tried running it in IDLE 3.5.0 and Spyder 3.2.4, with the same result.
A:
This works nicely for me on pandas v0.20.2, so you might want to try upgrading with
pip install --upgrade pandas
Call str.strip first, and you can do this in one str.replace call.
df.stringColumn = df.stringColumn.fillna('')\
.str.strip().str.replace(r'((?<=^)\.+)|(\.+(?=$))', '')
0
1 Random string one
2 another string
3 a third string
Name: stringColumn, dtype: object
If nan is not a NaNtype, but a string, just modify your regex:
((?<=^)\.+)|(\.+(?=$))|nan
Regex Details
(
(?<=^) # lookbehind for start of sentence
\.+ # one or more '.'
)
| # regex OR
(
\.+ # one or more '.'
(?=$) # lookahead for end of sentence
)
The regex looks for leading or trailing dots (one or more) and removes them.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing JSON in Flutter / Dart: () => Map , NoSuchMethodError - (array problem?)
Im still a bit new to Flutter / Dart and Ive struggled with parsing JSON for quite some time now. It seems like a daunting task to me, even though I think my JSON structure is not that complicated.
Your help would be greatly appreciated.
This is the JSON I want to parse:
{
"predictionICL":{
"openingTimeToday":"8:00 - 23:00",
"openingTimeTomorrow":"8:00 - 23:00",
"percentagesToday":[
3,
5,
11,
17,
20,
23,
25,
26,
25,
29,
30,
32,
31,
35,
40,
43,
44,
46,
49,
53,
50,
56,
54,
60,
62,
61,
69,
70,
75,
76,
84,
90,
94,
100,
93,
81,
72,
70,
73,
71,
63,
59,
55,
56,
51,
49,
50,
45,
43,
40,
38,
35,
31,
27,
25,
23,
20,
20,
19,
17,
12,
9,
8,
2,
1
],
"percentagesTomorrow":[
0,
0,
1,
7,
14,
20,
22,
21,
21,
22,
20,
25,
27,
31,
30,
31,
32,
33,
30,
34,
35,
33,
35,
37,
39,
40,
40,
39,
38,
40,
41,
38,
34,
37,
34,
35,
33,
32,
31,
30,
33,
30,
31,
30,
29,
30,
27,
28,
26,
23,
20,
19,
16,
17,
15,
12,
10,
7,
5,
1,
1,
0,
0,
0,
0
]
},
"predictionRandwyck":{
"openingTimeToday":"8:00 - 23:00",
"openingTimeTomorrow":"8:00 - 23:00",
"percentagesToday":[
3,
5,
11,
17,
20,
23,
25,
26,
25,
29,
30,
32,
31,
35,
40,
43,
44,
46,
49,
53,
50,
56,
54,
60,
62,
61,
69,
70,
75,
76,
84,
90,
94,
100,
93,
81,
72,
70,
73,
71,
63,
59,
55,
56,
51,
49,
50,
45,
43,
40,
38,
35,
31,
27,
25,
23,
20,
20,
19,
17,
12,
9,
8,
2,
1
],
"percentagesTomorrow":[
0,
0,
1,
7,
14,
20,
22,
21,
21,
22,
20,
25,
27,
31,
30,
31,
32,
33,
30,
34,
35,
33,
35,
37,
39,
40,
40,
39,
38,
40,
41,
38,
34,
37,
34,
35,
33,
32,
31,
30,
33,
30,
31,
30,
29,
30,
27,
28,
26,
23,
20,
19,
16,
17,
15,
12,
10,
7,
5,
1,
1,
0,
0,
0,
0
]
},
"predictionTapijn":{
"openingTimeToday":"8:00 - 23:00",
"openingTimeTomorrow":"8:00 - 23:00",
"percentagesToday":[
3,
5,
11,
17,
20,
23,
25,
26,
25,
29,
30,
32,
31,
35,
40,
43,
44,
46,
49,
53,
50,
56,
54,
60,
62,
61,
69,
70,
75,
76,
84,
90,
94,
100,
93,
81,
72,
70,
73,
71,
63,
59,
55,
56,
51,
49,
50,
45,
43,
40,
38,
35,
31,
27,
25,
23,
20,
20,
19,
17,
12,
9,
8,
2,
1
],
"percentagesTomorrow":[
0,
0,
1,
7,
14,
20,
22,
21,
21,
22,
20,
25,
27,
31,
30,
31,
32,
33,
30,
34,
35,
33,
35,
37,
39,
40,
40,
39,
38,
40,
41,
38,
34,
37,
34,
35,
33,
32,
31,
30,
33,
30,
31,
30,
29,
30,
27,
28,
26,
23,
20,
19,
16,
17,
15,
12,
10,
7,
5,
1,
1,
0,
0,
0,
0
]
},
"message":"optionalmessageString"
}
Its basically just three instances of the datatype LibraryPrediction and one optional Message string.
The datatype LibraryPrediction consists of one String "openingTimeToday", one String "openingTimeTomorrow" and two double Arrays "percentagesToday" and "percentagesTomorrow".
Right now, I am trying to parse the json from above from disk, as my Server is not running yet.
This is my code so far:
I have one service file:
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:test_app/models/predictions_update_model.dart';
PredictionsUpdate parseUpdate(String responseBody) {
final jsonResponse = json.decode(responseBody).cast<Map<String, dynamic>>();
PredictionsUpdate update = jsonResponse.map<PredictionsUpdate>((json) => PredictionsUpdate.fromJson(json));
return update;
}
Future<PredictionsUpdate> fetchUpdate() async {
final response = await rootBundle.loadString('lib/testJson/data.json');
return parseUpdate(response);
}
And one model file:
class PredictionsUpdate {
final LibraryPrediction predictionICL;
final LibraryPrediction predictionRandwyck;
final LibraryPrediction predictionTapijn;
final String message;
PredictionsUpdate({
this.predictionICL,
this.predictionRandwyck,
this.predictionTapijn,
this.message,
});
factory PredictionsUpdate.fromJson(Map<String, dynamic> parsedJson){
return PredictionsUpdate(
predictionICL: LibraryPrediction.fromJson(parsedJson['predictionICL']),
predictionRandwyck: LibraryPrediction.fromJson(parsedJson['predictionRandwyck']),
predictionTapijn: LibraryPrediction.fromJson(parsedJson['predictionTapijn']),
message: parsedJson['message'] as String,
);
}
}
class LibraryPrediction {
final String openingTimeToday;
final String openingTimeTomorrow;
final List<double> percentagesToday;
final List<double> percentagesTomorrow;
LibraryPrediction({
this.openingTimeToday,
this.openingTimeTomorrow,
this.percentagesToday,
this.percentagesTomorrow,
});
factory LibraryPrediction.fromJson(Map<String, dynamic> json){
return LibraryPrediction(
openingTimeToday: json['openingTimeToday'] as String,
openingTimeTomorrow: json['openingTimeTomorrow'] as String,
percentagesToday: json['percentagesToday'] as List<double>,
percentagesTomorrow: json['percentagesTomorrow'] as List<double>,
);
}
}
This is how I call the function:
Row(
children: <Widget>[
RaisedButton(
child: Text('update'),
onPressed: () {
Future<PredictionsUpdate> futureUpdate = fetchUpdate();
futureUpdate.then((update)=> widget.currentNumbers = update)
.catchError((error) => print(error));
},
),
],
),
whenever I try to parse the JSON, I get the following error:
flutter: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
Receiver: _LinkedHashMap len:4
Tried calling: cast<Map<String, dynamic>>()
Found: cast<RK, RV>() => Map<RK, RV>
I have this feeling that the error originates somewhere when im trying to parse the double arrays "percentagesToday" or "percentagesTomorrow", but I can't say for sure and Im not able to get more clues from the error message.
I would be very grateful for any help in figuring out where I went wrong.
A:
You can copy paste run full code below
You can do like this List<double>.from(json["percentagesToday"].map((x) => x.toDouble())),
code snippet
factory LibraryPrediction.fromJson(Map<String, dynamic> json) =>
LibraryPrediction(
openingTimeToday: json["openingTimeToday"],
openingTimeTomorrow: json["openingTimeTomorrow"],
percentagesToday: List<double>.from(
json["percentagesToday"].map((x) => x.toDouble())),
percentagesTomorrow: List<double>.from(
json["percentagesTomorrow"].map((x) => x.toDouble())),
);
...
futureUpdate.then((update) {
print('${update.predictionIcl.openingTimeToday.toString()}');
print('${update.message}');
print('${update.predictionRandwyck.openingTimeTomorrow}');
}).catchError((error) => print(error));
output
I/flutter ( 7344): 8:00 - 23:00
I/flutter ( 7344): optionalmessageString
I/flutter ( 7344): 8:00 - 23:00
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
PredictionsUpdate predictionsUpdateFromJson(String str) =>
PredictionsUpdate.fromJson(json.decode(str));
class PredictionsUpdate {
LibraryPrediction predictionIcl;
LibraryPrediction predictionRandwyck;
LibraryPrediction predictionTapijn;
String message;
PredictionsUpdate({
this.predictionIcl,
this.predictionRandwyck,
this.predictionTapijn,
this.message,
});
factory PredictionsUpdate.fromJson(Map<String, dynamic> json) =>
PredictionsUpdate(
predictionIcl: LibraryPrediction.fromJson(json["predictionICL"]),
predictionRandwyck:
LibraryPrediction.fromJson(json["predictionRandwyck"]),
predictionTapijn: LibraryPrediction.fromJson(json["predictionTapijn"]),
message: json["message"],
);
}
class LibraryPrediction {
String openingTimeToday;
String openingTimeTomorrow;
List<double> percentagesToday;
List<double> percentagesTomorrow;
LibraryPrediction({
this.openingTimeToday,
this.openingTimeTomorrow,
this.percentagesToday,
this.percentagesTomorrow,
});
factory LibraryPrediction.fromJson(Map<String, dynamic> json) =>
LibraryPrediction(
openingTimeToday: json["openingTimeToday"],
openingTimeTomorrow: json["openingTimeTomorrow"],
percentagesToday: List<double>.from(
json["percentagesToday"].map((x) => x.toDouble())),
percentagesTomorrow: List<double>.from(
json["percentagesTomorrow"].map((x) => x.toDouble())),
);
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Future<PredictionsUpdate> fetchUpdate() async {
String jsonString = '''
{
"predictionICL":{
"openingTimeToday":"8:00 - 23:00",
"openingTimeTomorrow":"8:00 - 23:00",
"percentagesToday":[
3,
5,
11,
17,
20,
23,
25,
26,
25,
29,
30,
32,
31,
35,
40,
43,
44,
46,
49,
53,
50,
56,
54,
60,
62,
61,
69,
70,
75,
76,
84,
90,
94,
100,
93,
81,
72,
70,
73,
71,
63,
59,
55,
56,
51,
49,
50,
45,
43,
40,
38,
35,
31,
27,
25,
23,
20,
20,
19,
17,
12,
9,
8,
2,
1
],
"percentagesTomorrow":[
0,
0,
1,
7,
14,
20,
22,
21,
21,
22,
20,
25,
27,
31,
30,
31,
32,
33,
30,
34,
35,
33,
35,
37,
39,
40,
40,
39,
38,
40,
41,
38,
34,
37,
34,
35,
33,
32,
31,
30,
33,
30,
31,
30,
29,
30,
27,
28,
26,
23,
20,
19,
16,
17,
15,
12,
10,
7,
5,
1,
1,
0,
0,
0,
0
]
},
"predictionRandwyck":{
"openingTimeToday":"8:00 - 23:00",
"openingTimeTomorrow":"8:00 - 23:00",
"percentagesToday":[
3,
5,
11,
17,
20,
23,
25,
26,
25,
29,
30,
32,
31,
35,
40,
43,
44,
46,
49,
53,
50,
56,
54,
60,
62,
61,
69,
70,
75,
76,
84,
90,
94,
100,
93,
81,
72,
70,
73,
71,
63,
59,
55,
56,
51,
49,
50,
45,
43,
40,
38,
35,
31,
27,
25,
23,
20,
20,
19,
17,
12,
9,
8,
2,
1
],
"percentagesTomorrow":[
0,
0,
1,
7,
14,
20,
22,
21,
21,
22,
20,
25,
27,
31,
30,
31,
32,
33,
30,
34,
35,
33,
35,
37,
39,
40,
40,
39,
38,
40,
41,
38,
34,
37,
34,
35,
33,
32,
31,
30,
33,
30,
31,
30,
29,
30,
27,
28,
26,
23,
20,
19,
16,
17,
15,
12,
10,
7,
5,
1,
1,
0,
0,
0,
0
]
},
"predictionTapijn":{
"openingTimeToday":"8:00 - 23:00",
"openingTimeTomorrow":"8:00 - 23:00",
"percentagesToday":[
3,
5,
11,
17,
20,
23,
25,
26,
25,
29,
30,
32,
31,
35,
40,
43,
44,
46,
49,
53,
50,
56,
54,
60,
62,
61,
69,
70,
75,
76,
84,
90,
94,
100,
93,
81,
72,
70,
73,
71,
63,
59,
55,
56,
51,
49,
50,
45,
43,
40,
38,
35,
31,
27,
25,
23,
20,
20,
19,
17,
12,
9,
8,
2,
1
],
"percentagesTomorrow":[
0,
0,
1,
7,
14,
20,
22,
21,
21,
22,
20,
25,
27,
31,
30,
31,
32,
33,
30,
34,
35,
33,
35,
37,
39,
40,
40,
39,
38,
40,
41,
38,
34,
37,
34,
35,
33,
32,
31,
30,
33,
30,
31,
30,
29,
30,
27,
28,
26,
23,
20,
19,
16,
17,
15,
12,
10,
7,
5,
1,
1,
0,
0,
0,
0
]
},
"message":"optionalmessageString"
}
''';
//final response = await rootBundle.loadString('lib/testJson/data.json');
final http.Response response = http.Response(jsonString, 200);
PredictionsUpdate payload = predictionsUpdateFromJson(response.body);
return payload;
}
void _incrementCounter() {
Future<PredictionsUpdate> futureUpdate = fetchUpdate();
futureUpdate.then((update) {
print('${update.predictionIcl.openingTimeToday.toString()}');
print('${update.message}');
print('${update.predictionRandwyck.openingTimeTomorrow}');
}).catchError((error) => print(error));
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrofit 2.0.0 Beta2 OkHttpClient interceptor throwing StackOverFlowError
I am trying to build an interceptor for logging in. Here is my following code for that:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String authToken = SharedPrefsManager.get(context).getAccessToken();
request.newBuilder()
.addHeader("Authorization", "Bearer " + authToken)
.addHeader("Content-Type", "application/json")
.build();
return intercept(chain);
}
});
My GSON:
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.create();
My Retrofit RestAdapter:
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(Endpoints.ENDPOINT_BASE_URL+Endpoints.ENDPOINT_VERSION)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
apiInterface = restAdapter.create(ApiService.class);
However when I call this service using:
try {
Account myAccount = ApiInterface.getKidMixClient(getActivity()).getAccountDetails().execute().body();
callbacks.showDashboard(myAccount.getUser());
} catch (IOException e) {
e.printStackTrace();
}
I receive a StackOverFlowError, the following Logcat output:
java.lang.StackOverflowError: stack size 8MB
10-08 16:42:39.013 21279-21279/com.kidmixapp.kidmixchild E/AndroidRuntime: at java.util.ArrayList.<init>(ArrayList.java:71)
10-08 16:42:39.013 21279-21279/com.kidmixapp.kidmixchild E/AndroidRuntime: at com.squareup.okhttp.Headers$Builder.<init>(Headers.java:215)
10-08 16:42:39.013 21279-21279/com.kidmixapp.kidmixchild E/AndroidRuntime: at com.squareup.okhttp.Headers.newBuilder(Headers.java:121)
10-08 16:42:39.013 21279-21279/com.kidmixapp.kidmixchild E/AndroidRuntime: at com.squareup.okhttp.Request$Builder.<init>(Request.java:137)
10-08 16:42:39.013 21279-21279/com.kidmixapp.kidmixchild E/AndroidRuntime: at com.squareup.okhttp.Request$Builder.<init>(Request.java:120)
10-08 16:42:39.013 21279-21279/com.kidmixapp.kidmixchild E/AndroidRuntime: at com.squareup.okhttp.Request.newBuilder(Request.java:94)
10-08 16:42:39.013 21279-21279/com.kidmixapp.kidmixchild E/AndroidRuntime: at com.kidmixapp.commoncode.networking.ApiInterface$1.intercept(ApiInterface.java:39)
10-08 16:42:39.013 21279-21279/com.kidmixapp.kidmixchild E/AndroidRuntime: at com.kidmixapp.commoncode.networking.ApiInterface$1.intercept(ApiInterface.java:45)
10-08 16:42:39.013 21279-21279/com.kidmixapp.kidmixchild E/AndroidRuntime: at com.kidmixapp.commoncode.networking.ApiInterface$1.intercept(ApiInterface.java:45)
A:
You need to be using chain.proceed(request), what you're doing is recursively calling the same intercept method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Shuffling String
I need to write a program that scrambles a 4 letter string inputted by the user. (example TEST can be scrambled like tset, ttse etc...) Well I have a program that works but it is limited to a 4 element char array, and I want to know if there is any way to make it so I don't have to have the size pre-determined.
//4 letter word scrambler (ex. test tets tset...)
int counter=0;
int main(int argc, char* argv[])
{
char str[4];
cout << "Please enter a word: "; //ask for input
cin >> str;
counter+=1; // set counter to 1
cout << counter << " " << str << endl;
for (int i=0;i<3;i++){// iteration through one full loop in array
swap(str[i], str[i+1]); //swap two elements as iterates through array
counter+=1;//add 1 to counter each time
cout <<counter<<" "<< str << endl;
}
for (int i=0;i<3;i++){
swap(str[i], str[i+1]);
counter+=1;
cout << counter<< " " << str << endl;
}
for (int i=0;i<3;i++){
swap(str[i], str[i+1]);
counter+=1;
cout << counter << " " << str << endl;
}
for (int i=0;i<2;i++){
swap(str[i], str[i+1]);
counter+=1;
cout << counter << " " << str << endl;
}
system("PAUSE");
return 0;
}
A:
I'm not sure if you want to shuffle the string once or print all permutations of the letters in the word. Both are fairly simple using the C++ Standard Library.
This first bit of code does a single random shuffle:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Please enter a word: "; //ask for input
cin >> str;
random_shuffle(str.begin(), str.end());
cout << str << '\n';
}
The following prints all permutations of the string:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Please enter a word: "; //ask for input
cin >> str;
sort(str.begin(), str.end());
do {
cout << str << '\n';
} while (next_permutation(str.begin(), str.end()));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Identifying which Azure WorkRole Instance is executing the Queue?
I am working on Azure Worker Roles. I have a worker role which is scaled up to 5 instance. I want to identify which Instance processed the queue item. I know, I can use RoleEnvironment.Roles to get the list of the instances but not sure how to get the actual instance.
Thanks in advance.
A:
You are looking for
RoleEnvironment.CurrentRoleInstance.Role.Name
| {
"pile_set_name": "StackExchange"
} |
Q:
SimpleModal-container positioning
I am still a relative beginner with jquery so any help is gratefully appreciated.
I took the simplemodal function and changed the positioning from fixed to absolute as I wanted the modal box to be able to be scrolled with the background page.
This is causing me a problem as somewhere (I presume in the jscript) the top position is being set so I can't override it in the external css.
Can anyone tell me how I can change the inline css for simplemodal-container?
Thanks!
A:
The following should work:
// replace #foo with your id or element
$('#foo').modal({onShow: function (d) {
// replace '0px' with your value, or remove the property
d.container.css({position: 'absolute', top: '0px'});
}});
Note: This does not work in IE6
| {
"pile_set_name": "StackExchange"
} |
Q:
Equivalent to ddply(...,transform,...) in data.table
I have the following code using ddply from plyr package:
ddply(mtcars,.(cyl),transform,freq=length(cyl))
The data.table version of this is :
DT<-data.table(mtcars)
DT[,freq:=.N,by=cyl]
How can I extend this when I have more than one function like the one below?
Now, I want to perform more than one function on ddply and data.table:
ddply(mtcars,.(cyl),transform,freq=length(cyl),sum=sum(mpg))
DT[,list(freq=.N,sum=sum(mpg)),by=cyl]
But, data.table gives me only three columns cyl,freq, and sum. Well, I can do like this:
DT[,list(freq=.N,sum=sum(mpg),mpg,disp,hp,drat,wt,qsec,vs,am,gear,carb),by=cyl]
But, I have large number of variables in my read data and I want all of them to be there as in ddply(...transform....). Is there shortcut in data.table just like doing := when we have only one function (as above) or something like this paste(names(mtcars),collapse=",") within data.table?
Note: I also have a large number of function to run. So, I can't repeat =: a number of times (but I would prefer this if lapply can be applied here).
A:
Use backquoted := like this...
DT[ , `:=`( freq = .N , sum = sum(mpg) ) , by=cyl ]
head( DT , 3 )
# mpg cyl disp hp drat wt qsec vs am gear carb freq sum
#1: 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 7 138.2
#2: 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 7 138.2
#3: 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 11 293.3
| {
"pile_set_name": "StackExchange"
} |
Q:
Can anyone explain how this block of code work?
I'm trying to understand this piece of code where it checks the anagrams of 2 different strings.
int[] charSet = new int[256];
for (int i = 0; i < sA.length(); i++) {
charSet[sA.charAt(i)]++;
}
for (int i = 0; i < sB.length(); i++) {
charSet[sB.charAt(i)]--;
}
int deletion = 0;
for (int i = 0; i < 256; i++) {
deletion += Math.abs(charSet[i]);
}
System.out.println("The amount of deletion needed: " + deletion);
I used debugging to really grasp the idea of placing the char indexes in an array but when i check the content of the array there are either 0's or 1's. But isn't sA.charat(i) returns the index of the string not 0 or 1?
So charSet[sA.charAt(i)]++; what does this code really do as to my understanding it gets the char index of the string and adds to the array but what is the point of ++ ?
Also, more specifically, deletion += Math.abs(charSet[i]); how does this line of code work because all it does is adds the corresponding index of an array on top of another. But i don't really understand how this work to check anagrams of 2 strings.
I really will appreciate if anyone can explain this in detail.
A:
You seem to have misunderstood the purpose and behaviour of charSet[sA.charAt(i)]++;. As soon as you understand why that line is there, everything else becomes straightforward.
charSet here is counting how many of each char the first string has. For example, if the string were aab, then index 97 of charSet will be 2, index 98 will be 1, and the rest will be all 0s. The int value for "a" is 97 and the int value for "b" is 98.
The first for loop loops through each character of the first string. charSet[sA.charAt(i)]++; basically increments the count of that character by 1. For the string aab, the expression evaluates to:
// note that charAt(i) returns the character at index i of the string
charSet[97]++; // 1st iteration
charSet[97]++; // 2nd iteration
charSet[98]++; // 3rd iteration
Now the second for loop does the reverse to the second string. This time, we count down. Why? Because if the two strings are anagrams, we would end up with charSet filled with 0s, after counting up the characters and counting down the same characters.
Let's say that the two strings are not anagrams. This means that after the first two for loops, charSet contains some non-0s. We add the absolute value of these non-0s up to get how many characters needs to be added/removed to make the two strings anagrams.
Note that this program will crash if the strings contain characters that has values that are more than 256! A better way to solve this problem would be to use a HashMap to count the characters.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.