text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
VB Reading data from SQL Server to Array, writing into .CSV
I'm trying to read out data from a SQL Server into an array. After that, I'd like to write each line into separate .csv files.
This is my code so far:
Imports System.Data.SqlClient
Public Class Form1
Public SQLcn As New SqlConnection
Public Function Connect() As Boolean
SQLcn = New SqlConnection("Server = Server01;Database=PROD;User ID=user; Password = 123")
Try
SQLcn.Open()
Return True
Catch ex As Exception
MessageBox.Show(ex.Message)
Return False
End Try
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SQLQuery As String
Dim SQLcmd As SqlCommand
Dim SQLrdr As SqlDataReader
Dim NAVArray As New ArrayList()
Call Connect()
SQLQuery = "SELECT No_ FROM " & "dbo.Database" & " Where No_ LIKE '10007*'"
SQLcmd = New SqlCommand(SQLQuery, SQLcn)
SQLrdr = SQLcmd.ExecuteReader()
While SQLrdr.Read()
Dim dict As New Dictionary(Of String, Object)
For count As Integer = 0 To (SQLrdr.FieldCount - 1)
dict.Add(SQLrdr.GetName(count), SQLrdr(count))
Next
NAVArray.Add(dict)
End While
ExportCSV(NAVArray, "\\path\path\path")
SQLcn.Close()
End Sub
Function ExportCSV(ByVal Daten As ArrayList, ByVal Pfad As String) As Boolean
Dim Nummer As Integer
For Each Nummer In Daten
Dim csv As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Pfad & Nummer, False)
csv.WriteLine("formatcount;formatname;printername;Beschreibung;")
csv.WriteLine("1;\\path\path\path\Format1.fmt;")
csv.Close()
Next
Return 0
End Function
End Class
The NAVArray does not even get filled with the data.
Additionally, I don't know how to write the data to the CSV.Writeline.
EDIT:
The New Code (working so far) looks like this:
Option Infer On
Option Strict On
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Public SQLcn As New SqlConnection
Public Function GetData(databaseColumnNames As String()) As DataTable
Dim dt As New DataTable()
Dim csb As New SqlConnectionStringBuilder With {.DataSource = "NAVDB01",
.InitialCatalog = "NAV110_PROD",
.UserID = "paz",
.Password = "****"
}
Dim columnNames = " " & String.Join(", ", databaseColumnNames.Select(Function(c) "[" & c & "]")) & " "
Dim sql = "SELECT " & columnNames & " FROM [dbo.Part1 Part2$Item] WHERE No_ LIKE '10007%'"
Using conn = New SqlConnection(csb.ConnectionString),
cmd = New SqlCommand(sql, conn)
Dim DAdap As New SqlDataAdapter(cmd)
DAdap.Fill(dt)
End Using
Return dt
End Function
Function CsvLine(a As Object(), separator As Char) As String
Dim b = a.Select(Function(x) x.ToString()).ToArray()
For i = 0 To b.Count - 1
If b(i).IndexOfAny({separator, Chr(42), Chr(10), Chr(13)}) >= 0 Then
b(i) = b(i).Replace("""", """""")
b(i) = """" & b(i) & """"
End If
Next
Return String.Join(separator, b)
End Function
Sub WriteCsvFiles(destPath As String, headings As String(), dt As DataTable)
Dim separator As Char = ";"c
Dim header = String.Join(separator, headings)
For Each r As DataRow In dt.Rows
Dim destFile = Path.Combine(destPath, r(0).ToString().Trim() & ".csv")
Using sw As New StreamWriter(destFile)
sw.WriteLine(header)
sw.WriteLine(CsvLine(r.ItemArray, separator))
End Using
Next
End Sub
Private Sub bnDatenVerarbeiten_Click() Handles bnDatenVerarbeiten.Click
Dim destinationFolder = "\\fileserver02\Folder1"
Dim columnsToUseSQL = {"Description"}
Dim columnsToUseCSV = {"formatcount", "formatname", "printername", "Beschreibung"}
Dim daten = GetData(columnsToUseSQL)
WriteCsvFiles(destinationFolder, columnsToUseCSV, daten)
End Sub
End Class
About the additional Input.
5 fields will be implemented:
Formatcount As InputBox
Formatname As Dropdown
printername As Dropown (default value defined by Formatname)
itemnumber As Inputbox (Used as Filter for SQL)
creditor As Inputbox (Used for a second SQL-Statement)
Fields going directly to the csv. :
formatcount
formatname
printername
Fields with the result going to the csv. :
itemnumber (result e.g. "Description")
creditor (result = "specialcode";"countrycode")
EDIT2:
The current state:
Option Infer On
Option Strict On
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Public SQLcn As New SqlConnection
Public Function GetData(databaseColumnNames As String()) As DataTable
Dim dt As New DataTable()
Dim csb As New SqlConnectionStringBuilder With {.DataSource = "Server01",
.InitialCatalog = "NAV110_PROD",
.UserID = "paz",
.Password = "***"
}
Dim columnNames = " " & String.Join(", ", databaseColumnNames.Select(Function(c) "[" & c & "]")) & " "
Dim sql = "SELECT " & columnNames & " FROM [dbo.Part1 Part2$Item] WHERE No_ LIKE '10007%'"
Using conn = New SqlConnection(csb.ConnectionString),
cmd = New SqlCommand(sql, conn)
Dim DAdap As New SqlDataAdapter(cmd)
DAdap.Fill(dt)
End Using
Return dt
End Function
Function CsvLine(a As Object(), separator As Char) As String
Dim b = a.Select(Function(x) x.ToString()).ToArray()
For i = 0 To b.Count - 1
If b(i).IndexOfAny({separator, Chr(42), Chr(10), Chr(13)}) >= 0 Then
b(i) = b(i).Replace("""", """""")
b(i) = """" & b(i) & """"
End If
Next
Return String.Join(separator, b)
End Function
Sub WriteCsvFiles(destPath As String, headings As String(), dt As DataTable)
Dim separator As Char = ";"c
Dim header = String.Join(separator, headings)
For Each r As DataRow In dt.Rows
Dim destFile = Path.Combine(destPath, r(0).ToString().Trim() & ".csv")
Using sw As New StreamWriter(destFile)
sw.WriteLine(header)
sw.WriteLine(CsvLine(r.ItemArray, separator))
End Using
Next
End Sub
Private Sub bnDatenVerarbeiten_Click() Handles bnDatenVerarbeiten.Click
Dim destinationFolder = "\\fileserver02\folder"
Dim Anzahl = 1
Dim Format = "\\fileserver02\folder2"
Dim Drucker = "\\PRNSRV\Druckdruck"
Dim columnsToUseSQL = {"Description", "Description 2"}
Dim columnsToUseCSV = {"Beschreibung", "Beschreibung 2", "formatcount", "formatname", "printername"}
Dim daten = GetData(columnsToUseSQL)
daten.Columns.Add("formatcount", GetType(Integer))
daten.Columns.Add("formatname", GetType(String))
daten.Columns.Add("printername", GetType(String))
daten.Rows.Add(daten.Rows(0).Item("Description"), daten.Rows(0).Item("Description 2"), Anzahl, Format, Drucker)
WriteCsvFiles(destinationFolder, columnsToUseCSV, daten)
End Sub
End Class
A:
It looks like you want to select 4 columns from the database, so for the purpose of answering the question I made a table named "Huber" with this data:
No_ formatcount formatname printername Beschreibung
10007 1 Hello World Starting "entry".
100071 2 Yellow Flower NULL
100072 3 Grey Rock Let's have a ; here.
You may need some flexibility in which columns to select, so I made the column names an array.
There is a standard for CSV files: RFC 4180, so we might as well try to follow that.
It seems to me that in this case it would be simplest to retrieve the data into a DataTable. As each datum will be converted to a String to write to the CSV file, there will be no problem with NULL data from the database this way.
When using a database, it is best to open the connection, do the operation, dispose of the connection. The VB.NET Using statement takes care of the dispose automatically, even if something goes wrong. The DataAdapter.Fill method does the open and close for you (actually it leaves the connection in the same state as before it was called). Do not use anything like the "Function Connect()" in the question: it will lead to problems.
Given all that, I used this code:
Option Infer On
Option Strict On
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Function GetData(databaseColumnNames As String()) As DataTable
Dim dt As New DataTable()
Dim csb As New SqlConnectionStringBuilder With {.DataSource = "Server01",
.InitialCatalog = "PROD",
.UserID = "user",
.Password = "123"}
' Put the column names in square brackets in case a reserved word is used as a column name.
' Does not take into account using square brackets in a column name (don't do that).
Dim columnNames = " " & String.Join(", ", databaseColumnNames.Select(Function(c) "[" & c & "]")) & " "
Dim sql = "SELECT " & columnNames & " FROM dbo.[Huber] WHERE [No_] LIKE '10007%'"
Using conn = New SqlConnection(csb.ConnectionString),
cmd = New SqlCommand(sql, conn)
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
End Using
Return dt
End Function
Function CsvLine(a As Object(), separator As Char) As String
' Ref: RFC 4180 "Common Format and MIME Type for Comma-Separated Values (CSV) Files"
' https://tools.ietf.org/html/rfc4180
Dim b = a.Select(Function(x) x.ToString()).ToArray()
For i = 0 To b.Count - 1
' If the field contains the separator, a double-quote, LF, or CR, then make adjustments:
If b(i).IndexOfAny({separator, Chr(42), Chr(10), Chr(13)}) >= 0 Then
b(i) = b(i).Replace("""", """""")
b(i) = """" & b(i) & """"
End If
Next
Return String.Join(separator, b)
End Function
Sub WriteCsvFiles(destPath As String, headings As String(), dt As DataTable)
Dim separator As Char = ";"c
Dim header = String.Join(separator, headings)
For Each r As DataRow In dt.Rows
' Use the first column for the filename:
Dim destFile = Path.Combine(destPath, r(0).ToString().Trim() & ".csv")
Using sw As New StreamWriter(destFile)
sw.WriteLine(header)
sw.WriteLine(CsvLine(r.ItemArray, separator))
End Using
Next
End Sub
Private Sub bnDatenVerarbeiten_Click(sender As Object, e As EventArgs) Handles bnDatenVerarbeiten.Click
Dim destinationFolder = "C:\Temp\Huber"
Directory.CreateDirectory(destinationFolder)
' The names of the columns in the database...
Dim columnsToUse = {"formatcount", "formatname", "printername", "Beschreibung"}
Dim daten = GetData(columnsToUse)
' You could use different text for the headers if required.
WriteCsvFiles(destinationFolder, columnsToUse, daten)
End Sub
End Class
To get 3 files:
1.csv
formatcount;formatname;printername;Beschreibung
1 ;Hello;World;"Starting ""entry""."
2.csv
formatcount;formatname;printername;Beschreibung
2 ;Yellow;Flower;
3.csv
formatcount;formatname;printername;Beschreibung
3 ;Grey;Rock;"Let's have a ; here."
Hopefully I left in enough adjustable parts for you to change it as needed.
N.B. If the query is modified to use parameters, e.g. you might want to make the 10007% into a variable, then you must use SQL parameters to keep it safe from SQL injection.
Regarding adding columns to the datatable.
Adding the columns is a good idea, but instead of adding a row with the extra data like this:
daten.Rows.Add(daten.Rows(0).Item("Description"), daten.Rows(0).Item("Description 2"), Anzahl, Format, Drucker)
You need to add the extra data to each row, like this:
For i = 0 To daten.Rows.Count - 1
daten.Rows(i)("formatcount") = Anzahl
daten.Rows(i)("formatname") = Format
daten.Rows(i)("printername") = Drucker
Next
| {
"pile_set_name": "StackExchange"
} |
Q:
Wide to long format with several variables
This question is related to a previous question I asked on converting from wide to long format in R with an additional complication.
previous question is here: Wide to long data conversion
The wide data I start with looks like the following:
d2 <- data.frame('id' = c(1,2),
'Q1' = c(2,3),
'Q2' = c(1,3),
'Q3' = c(3,1),
'Q1_X_Opt_1' = c(0,0),
'Q1_X_Opt_2' = c(75,200),
'Q1_X_Opt_3' = c(150,300),
'Q2_X_Opt_1' = c(0,0),
'Q2_X_Opt_2' = c(150,200),
'Q2_X_Opt_3' = c(75,300),
'Q3_X_Opt_1' = c(0,0),
'Q3_X_Opt_2' = c(100,500),
'Q3_X_Opt_3' = c(150,300))
In this example, there are two individuals who have answered three questions. The answer to each question takes the following values {1,2,3} encoded in Q1, Q2, and Q3. So, in this examples, individual 1 chose option 2 in Q1, chose option 1 in Q2, and chose option 3 in Q3.
For each option there is also a variable X associated with each option that I also need to be converted to wide format. The output I am seeking looks like the following:
id question option choice cost
1 1 1 1 0 0
2 1 1 2 1 75
3 1 1 3 0 150
4 1 2 1 1 0
5 1 2 2 0 150
6 1 2 3 0 75
7 1 3 1 0 0
8 1 3 2 0 100
9 1 3 3 1 150
10 2 1 1 0 0
11 2 1 2 0 200
12 2 1 3 1 300
13 2 2 1 0 0
14 2 2 2 0 200
15 2 2 3 1 300
16 2 3 1 1 0
17 2 3 2 0 500
18 2 3 3 0 300
I have tried to adapting the code from the answer to the prior question, but with no success thus far. Thanks for any suggestions or comments.
A:
It's not exactly elegant, but here's a tidyverse version:
library(tidyverse)
d3 <- d2 %>%
gather(option, cost, -id:-Q3) %>%
gather(question, choice, Q1:Q3) %>%
separate(option, c('question2', 'option'), extra = 'merge') %>%
filter(question == question2) %>%
mutate_at(vars(question, option), parse_number) %>%
mutate(choice = as.integer(option == choice)) %>%
select(1, 5, 3, 6, 4) %>%
arrange(id)
d3
#> id question option choice cost
#> 1 1 1 1 0 0
#> 2 1 1 2 1 75
#> 3 1 1 3 0 150
#> 4 1 2 1 1 0
#> 5 1 2 2 0 150
#> 6 1 2 3 0 75
#> 7 1 3 1 0 0
#> 8 1 3 2 0 100
#> 9 1 3 3 1 150
#> 10 2 1 1 0 0
#> 11 2 1 2 0 200
#> 12 2 1 3 1 300
#> 13 2 2 1 0 0
#> 14 2 2 2 0 200
#> 15 2 2 3 1 300
#> 16 2 3 1 1 0
#> 17 2 3 2 0 500
#> 18 2 3 3 0 300
| {
"pile_set_name": "StackExchange"
} |
Q:
Select exclusive list of list of objects based on object properties
I have a list of a class that contains another list of a different class, example:
public class jobs
{
public int jobID {get;set;}
public string jobName {get;set;}
}
public class jobSteps
{
public int stepID {get;set;}
public string stepDescription {get;set;}
public int stepOrder {get; set;}
public List<jobs> jobCollection {get; set;}
}
I can have an N size list of 'jobSteps', and each 'jobStep' can have an N size list of 'jobs', however, the same 'job' can be in more than one 'step', usually in an ascending 'stepOrder'.
How can I create a list of 'jobSteps', that only contains the job at the last 'step' that it is present in, in other words, the Max 'stepOrder'?
I have the following function that iterated over each 'jobStep' list, and then selects only the jobIDs where they aren't in a later 'stepOrder', for example.
public class myFunctions
{
public void getJobLatestStep()
{
// Example Data:
List<jobSteps> jobStepCollection = new List<jobSteps>
{
new jobSteps()
{
stepID = 1,
stepDescription = "Start",
stepOrder = 0,
jobCollection = new List<jobs>()
{
new jobs() { jobID = 1, jobName = "Cook food" },
new jobs() { jobID = 2, jobName = "Do laundry" },
new jobs() { jobID = 3, jobName = "Go to work" }
}
},
new jobSteps()
{
stepID = 2,
stepDescription = "Continue",
stepOrder = 1,
jobCollection = new List<jobs>()
{
new jobs() { jobID = 1, jobName = "Cook food" },
new jobs() { jobID = 2, jobName = "Do laundry" }
}
},
new jobSteps()
{
stepID = 3,
stepDescription = "Finalise",
stepOrder = 2,
jobCollection = new List<jobs>()
{
new jobs() { jobID = 2, jobName = "Do laundry" }
}
}
};
List<jobSteps> lastStepOfJob = new List<jobSteps> {};
foreach (jobSteps c in jobStepCollection )
{
jobSteps currentStep = c;
for (int i = jobStepCollection.IndexOf(c); i < jobStepCollection.Count() - 1; i++){
currentStep.jobCollection = currentStep.jobCollection.Where(x => !jobStepCollection[i].jobCollection.Select(z => z.jobID).ToList().Contains(x.jobID)).ToList();
};
lastStepOfJob.Add(currentStep);
};
}
//The desired result would be:
//stepID = 1
//stepDescription = 'Start'
//stepOrder = 0
//jobID = 3
//jobName = 'Go to work'
//stepID = 2
//stepDescription = 'Continue'
//stepOrder = 1
//jobID = 1
//jobName = 'Cook food'
//stepID = 3
//stepDescription = 'Finalise'
//stepOrder = 2
//jobID = 2
//jobName = 'Do laundry'
}
How can I write this using only LINQ if possible, as I will have to handle large amounts of data at a given time?
A:
If you strictly want to use the built in LINQ operators it is going to be kind of convoluted. This will work:
List<jobSteps> lastStepOfJob =
jobStepCollection
.SelectMany(x => x.jobCollection.Select(y => new { JobStep = x, Job = y }))
.GroupBy(x => x.Job.jobID)
.Select(x => x.OrderByDescending(y => y.JobStep.stepOrder).Select(y => new { JobStep = y.JobStep, Job = y.Job }).First())
.GroupBy(x => x.JobStep.stepOrder)
.Select(x => new { JobStep = x.First().JobStep, Jobs = x.Select(y => y.Job) })
.Select(x => new jobSteps()
{
stepDescription = x.JobStep.stepDescription,
stepID = x.JobStep.stepID,
stepOrder = x.JobStep.stepOrder,
jobCollection = x.Jobs.OrderBy(y => y.jobID).Select(y => new jobs() { jobID = y.jobID, jobName = y.jobName }).ToList()
})
.OrderBy(x => x.stepOrder)
.ToList();
Basically, you want to:
flatten your list
group by the job id
select the first job step for each job
group by your job step order
finally, 'rehydrate' your list
In this example I am creating entirely new jobs and jobSteps objects to avoid side effects.
If you were to roll your own extension method I am sure you would get better performance. If I have time later tonight I will show an example implementation.
EDIT - Additional approach
Here is a slight twist on the above approach that I think could give you little better performance. I am essentially replacing the first GroupBy with an aggregate function that keeps a memo.
List<jobSteps> lastStepOfJob =
jobStepCollection
.SelectMany(x => x.jobCollection.Select(y => Tuple.Create(y, x)))
.Aggregate(
new Dictionary<int, Tuple<jobs, jobSteps>>(),
(memo, value) =>
{
if (memo.ContainsKey(value.Item1.jobID))
{
if (memo[value.Item1.jobID].Item2.stepOrder < value.Item2.stepOrder)
{
memo[value.Item1.jobID] = value;
}
}
else
{
memo.Add(value.Item1.jobID, value);
}
return memo;
})
.Select(x => new { Job = x.Value.Item1, JobStep = x.Value.Item2 })
.GroupBy(x => x.JobStep.stepOrder)
.Select(x => new { JobStep = x.First().JobStep, Jobs = x.Select(y => y.Job) })
.Select(x => new jobSteps()
{
stepDescription = x.JobStep.stepDescription,
stepID = x.JobStep.stepID,
stepOrder = x.JobStep.stepOrder,
jobCollection = x.Jobs.OrderBy(y => y.jobID).Select(y => new jobs() { jobID = y.jobID, jobName = y.jobName }).ToList()
})
.OrderBy(x => x.stepOrder)
.ToList();
The strategy is essentially the same strategy as my first solution. I know it looks a little intimidating. It could probably be simplified a little if you override the GetHashCode method for the jobs and jobSteps types or implemented custom IEqualityComparers.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to decrease the size of a KVM virtual machine disk image?
How do you decrease or shrink the size of a KVM virtual machine disk?
I allocated a virtual disk of 500GB (stored at /var/lib/libvirt/images/vm1.img), and I'm finding that overkill, so now I'd like to free up some of that space for use with other virtual machines. There seems to be a lot answers on how to increase image storage, but not decrease it. I found the virt-resize tool, but it only seems to work with raw disk partitions, not disk images.
Edit: I'm using an LVM with an Ext4 formatted partition.
Edit: GParted screenshot showing my LVM parition layout. I need to do a lot more then just resize the filesystem. I know of no safe way to resize an LVM. And please don't tell me to use pvresize. Despite its name, it does not support resizing LVMs.
I did try sudo pvresize /dev/vda5, but it just says physical volume "/dev/vda5" changed but doesn't actually reduce the size.
I tried start parted to manually set the partition size (very dangerous), but doing print all just gives me the error "/dev/sr0 unrecognised disk label".
Edit: By following these instructions, I was able to successfully shrink both my logical and physical volumes (although I had to remember to activate and deactivate lvm before and after certain commands, which the instructions omit.
Now GParted is showing 250G of unallocated free space. How do I remove this from the KVM disk image and give it back to the underlying hypervisor?
A:
Thanks to those who posted, but your answers were way too vague to be of any help.
After hours of Googling, I finally found a guide(link redacted) providing step-by-step instructions on how to shrink my filesystem, logical volumes, and physical volumes. The trick that most guides miss is the need to actually delete the physical partitions, and recreate them with the correct size, because parted is unable to resize lvm partitions.
I then found this documentation on qemu-img, which explains how to shrink a raw-formatted virtual disk image by running:
sudo qemu-img resize /var/lib/libvirt/images/myvm.img 255G
A:
What you need to do,
Take a backup
Shrink the file system(s) *don't do this on a live
system, I recommend using a live cd.
Create a new disk image of desired size.
Run a live os, with the new and old images attached as (virtual) hard disks (not mounted)
Create the new partition(s) the same size as the resized partitions on the old disk
Use dd to mirror the data to the new partition.
You'll possibly need to purge / regenerate grub(2) to boot successfully.
This can be accomplished through both GUI and CLI
Resources
fdisk partitioning -
http://linux.die.net/HOWTO/Partition/fdisk_partitioning.html
dd man
page - http://linux.die.net/man/1/dd
Tools
gparted ( link omitted due to Spam, not enough rep )
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP while loop issue in iOS 5 Safari
I have a while loop that do some things with a usleep() function inside loop, like this:
$x = 0;
while ($x < 30)
{
$x += 1;
usleep(200000);
}
echo 'done';
This script is called by ajax in a background by this way:
(function test() {
$.ajax({
type: 'POST',
url: '/jq_test/txt.php',
data: {text: $('#input').val()},
async: true,
success: function (data) {
$('#table tbody').append(data);
setTimeout(test);
}
});
})();
The problem i get is that safari keeps page loading bar stay active while loop is in progress. Only when x equals 30, page stops loading and echos 'done'. After that script is called in background as i supposed it to and echos 'done' each 30*0.2s. Why this happenes?
A:
I found out what was the problem in. Ajax was requesting a .php file that contained a while loop. Since this script was called kinda same time the page itself was, safari 5 understood it as a part of main page and didnt finish page loading until loop done.
| {
"pile_set_name": "StackExchange"
} |
Q:
Running Into A Contradiction In Algebra/Category Theory
In Aluffi's Algebra Chapter 0, on page 34, he proves the following claim:
Claim 5.5: Denoting by $\pi$ the 'canonical projection' defined in Example 2.6 [he means $\pi:A \rightarrow A/\sim$ for some equivalencce relation $\sim$] the pair $(\pi, A/\sim)$ is an initial object of this category.
More precisely he means that if $\phi:A \rightarrow Z$ is a morphism that there exists a unique function $\bar{\phi}$ such that $\bar{\phi}\pi = \phi$. However, I am having trouble conceptualizing this.
In particular, I am thinking of the example in which $Z = A$. Clearly, $1_A:A \rightarrow A$ exists as long as $A$ is non-empty. Also, a surjective canoncial projection $\pi:A \rightarrow A/\sim$ exists for any equivalence relation $\sim$ on $A$.
My problem then, is that the above theorem states that there exists some unique function $\bar{1_A}$ such that $\bar{1_A}\pi = 1_A$. However, this appears to imply that canonical projections have left-inverses, meaning they are injective!! This is obviously not true.
What mistake am I making??
A:
The quotient $(\pi,A/\sim)$ is an initial object, not of the category whose objects are arbitrary maps out of $A$, but of the category whose objects are maps out of $A$ which identify elements of $A$ equivalent under $\sim$. So $1_A$ is an object in the relevant category if and only if $\sim$ is the discrete relation, in which case $\pi=1_A$ and there's no problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
How should low-rep users approach issues that could be solved by permissions they don't have access to?
As a new, low-rep user I often find issues that I struggle to help with due to not having access to permissions that would be able to easily address the issues, for example:
I came across this question which at the time was still active, the flags I currently have access to for this would were:
It seemed that 'other' would be the most appropriate, in the flag I described the issue at hand
User has made no effort to solve the problem, question is vague and merely a request rather than a question to solve. – Aaron Critchley 27 mins ago
My flag was afterwards declined by a mod with the message:
declined - Please use standard close votes or close flags for this instead of flagging for moderators.
Which I do not have access to, and therefore, cannot use.
As a side note for this particular example a mod soon came in to close the question with the comment:
At this point, this could be written any number of ways and you've showed absolutely no attempts at solving this problem, so I'm closing this. – bluefeet♦ 25 mins ago
This seems remarkably similar to the comment I gave on my flag. Is this simply irrelevant or does it take away from the validity of the declination of my flag?
Another example would be when a question is too vague, where users with the appropriate rep can comment in an attempt to extract information, or encourage the user in the right direction, low rep users would be left to either edit, flag, answer or ignore. (I understand this is far less of an issue on the ground it only requires 50 rep to comment, but the principle still stands.)
Generally speaking, is it be better for the low-rep user to ignore the question or should they take the best approach they have available, knowing there are other, better approaches that they personally cannot take?
A:
Please don't use custom moderator flags to draw attention to things that can be handled by the community. A lot of people have close-vote privileges. When one person casts a close vote or selects one of the standard close reasons from the flag menu, it goes into a review queue for a very large community to look at. When you use a custom flag, it goes to the diamond moderator queue where only a handful of people can see it. That particular queue currently has a backlog of over 1000 flags. If you don't have the reputation to vote to close and you don't see the option on your flag dialog, please don't do anything. Someone with more privileges will be along shortly.
A:
Perhaps you're ahead of the curve in understanding the community, but most people with 19 rep do not understand what should be closed and not, which is a big driver for having the reputation system in the first place. (Heck, many with more rep don't understand it either, but that's a separate issue)
I'd say ignore it. Earn the rep, then you can start casting close votes as appropriate.
| {
"pile_set_name": "StackExchange"
} |
Q:
c# panel layout problem
I have created a panel in c# application that holds rows of 5 textboxes.
Textboxes are added to panel dynamically. It is 500 pixels in width and each textbox is 100 pixels wide.
First textbox is at x-position 0, second at 100, third at 200 and so on.
So the 5 textboxes should fill the panel horizontally. These are shown correctly at my computer but at another computer these textboxes appear as if their width is reduced and they do not extend to end of the panel. They leave blank space at the end of panel.
Can anyone tell me why is this difference in display of textboxes?
A:
There could be a few different reasons for this. Depending on if you are using WinForms (which I am assuming) or WPF. There is a system DPI that can be changed in windows. Windows Vista and 7 take advantage of this more. The other issue could be with the windows themes (play with the handicap themes). How to check your system DPI
| {
"pile_set_name": "StackExchange"
} |
Q:
Which activities are appropriate for which age group?
When preparing for an ESL lesson various activities are included in various stages of a lesson plan. For instance, milling, drilling, info Gap, Gap filling, text-matching, multiple-choice, true/false, picture-matching, and so on.
How do I know which activities are appropriate for, say, 7th-grade students, and which activities are appropriate, say, for 1st-grade students, and which activities are appropriate for say adults?
Kindly, give reference in favor of your answer.
A:
Individuals are very varied, so a lot needs to be adapted to an particular class.
Youngest children: no text activties. Everything should be structured as a game. Short attention spans, so each activity must be short. Probably still learning their native language, so can work very well with all instructions in target language.
Elementary school age: Increasing ability to work with text. Can start to do some more formal work (such as "gap filling"). In the "grammar gap" at which time they are too old to pick up grammar quickly as a native speaker does, but to young to learn grammar formally as an older learner can. Still a good mix of games is important. Still largely motivated by "fun".
Secondary school: External motivations such as "tests" become more important. Most can now work with texts effectively (but look out for undiagnosed dyslexia) Can be resistant to speaking in a foreign language. More able to take correction, can begin to learn about the target language. Longer activities, perhaps just "starter/main/plenary" become possible. These students understand "school". Building a good teacher/student relationship is difficult but important. You need to be very aware of them.
Adults: Wide range of motivations. Some will just want conversation, others will be aiming towards particular tests. Most will want something different from "school". Can discuss their individual requirements.
Some things vary monotonically: attention span increases with age. Other things change in different directions. Young children and adults both want spoken conversation, but in the middle textual work is preferred. Individuals will vary considerably, and so teacher judgement is required.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between :destroy and :delete for :dependent in has_one association
In Rails document Active Record Associations, The first 2 values of :dependent for has_one are:
4.2.2.4 :dependent
Controls what happens to the associated object when its owner is destroyed:
:destroy causes the associated object to also be destroyed
:delete causes the associated object to be deleted directly from the database (so callbacks will not execute)
My understanding about :destroy is for example, a customer has_one address. With :dependent => :destroy, if customer is deleted, then address will be deleted automatically from the database after customer is deleted from the database and we usually use :destroy. What's use of the :delete?
A:
Both does almost the same, I said almost, because:
dependent: :destroy - calls callbacks (before_destroy, after_destroy) in associated objects, and then you're able to break the transactions (raise error in callback).
dependent: :delete - doesn't call callbacks (it removes object directly from database by SQL like DELETE FROM ... WHERE ...)
A:
In order to complete Jan's answer destroy adds loading of an object to the memory before deleting it (and calling callbacks). Basically there is a quite a a difference, because using delete avoids callbacks/validations and it might breake referential integrity.
delete
Deletes the row with a primary key matching the id argument, using a SQL DELETE statement, and returns the number of rows deleted. Active Record objects are not instantiated, so the object’s callbacks are not executed, including any :dependent association options.
You can delete multiple rows at once by passing an Array of ids.
Note: Although it is often much faster than the alternative, #destroy, skipping callbacks might bypass business logic in your application that ensures referential integrity or performs other essential jobs.
destroy
Destroy an object (or multiple objects) that has the given id. The object is instantiated first, therefore all callbacks and filters are fired off before the object is deleted. This method is less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
This essentially finds the object (or multiple objects) with the given id, creates a new object from the attributes, and then calls destroy on it.
http://apidock.com/rails/ActiveRecord/Relation/destroy
For further discussion take a look at this post
Difference between Destroy and Delete
| {
"pile_set_name": "StackExchange"
} |
Q:
Calcular o total no boleto bancário
Talvez com a imagem dê para entender, eu tenho segundo a imagem, 2 produtos, na hora de gerar o boleto ele só pega o valor do primeiro produto, como fazer para resgatar o total corretamente?
O código PHP:
$conn = conecta();
$total = 0;
$linha = Array();
foreach ($_SESSION['shop'] as $id => $qtd) {
$cart = $conn->prepare("SELECT * FROM produtos WHERE id=$id");
$cart->setFetchMode(PDO::FETCH_ASSOC);
$cart->execute();
while ($linha = $cart->fetch()) {
$preco = $linha['preco'];
$linha['preco'] = str_replace(",",".",$linha['preco']);
$_SESSION['preco'] = $linha['preco'];
$sub = $linha['preco'] * $qtd;
$total += $linha['preco'] * $qtd;
// $total += $preco;
// ------------------------- DADOS DINÂMICOS DO SEU CLIENTE PARA A GERAÇÃO DO BOLETO (FIXO OU VIA GET) -------------------- //
// Os valores abaixo podem ser colocados manualmente ou ajustados p/ formulário c/ POST, GET ou de BD (MySql,Postgre,etc) //
// DADOS DO BOLETO PARA O SEU CLIENTE
$dias_de_prazo_para_pagamento = 5;
$taxa_boleto = 2.95;
$data_venc = date("d/m/Y", time() + ($dias_de_prazo_para_pagamento * 86400));
// Prazo de X dias OU informe data: "13/04/2006";
$valor_cobrado = $sub;
// Valor - REGRA: Sem pontos na milhar e tanto faz com "." ou "," ou com 1 ou 2 ou sem casa decimal
$valor_cobrado = str_replace(",", ".",$valor_cobrado);
$valor_boleto = number_format($valor_cobrado+$taxa_boleto, 2, ',', '');
$dadosboleto["nosso_numero"] = '12345678';
// Nosso numero - REGRA: Máximo de 8 caracteres!
$dadosboleto["numero_documento"] = '0123';
// Num do pedido ou nosso numero
$dadosboleto["data_vencimento"] = $data_venc;
// Data de Vencimento do Boleto - REGRA: Formato DD/MM/AAAA
$dadosboleto["data_documento"] = date("d/m/Y");
// Data de emissão do Boleto
$dadosboleto["data_processamento"] = date('d/m/Y');
// Data de processamento do boleto (opcional)
$dadosboleto["valor_boleto"] = $valor_boleto;
// Aqui eu quero inserir o valor total da compra.
}
}
E o JavaScript:
$(document).ready(function (e) {
$('input').change(function (e) {
id = $(this).attr('rel');
$index = this.value;
$preco = $('font#preco'+id)
.html().replace("R$ ",'');
console.log($preco);
$val = ($preco*$index).toFixed(2)
.replace(/(\d)(?=(\d{3})+\.)/g, '$1,');;
$('font#sub'+id).html('R$ '+$val);
clearInterval(timer);
});
});
A:
Tem 2 formas de fazer isso. Com o php e com o sql.
PHP
<?php
$conn = conecta();
$linha = Array();
// criei um array chamado totalGarel que usaremos mais tarde
$totalGeral = array();
// apaguei o looping while pois ele não é necessário uma vez
//que você seleciona apena 1 id de cada produto por vez
foreach ($_SESSION['shop'] as $id => $qtd) {
$cart = $conn->prepare("SELECT * FROM produtos WHERE id=$id");
$cart->setFetchMode(PDO::FETCH_ASSOC);
$cart->execute();
$linha = $cart->fetch()
$preco = $linha['preco'];
$preco = str_replace(",",".",$preco);
$_SESSION['preco'] = $preco;
$sub = $preco * $qtd;
$valor_cobrado = $sub;
$valor_cobrado = str_replace(",", ".",$valor_cobrado);
$totalGeral[] = $valor_cobrado;
}
// aqui vem a soma de todos os valores dos produtos selecionados
$ValorTotalBoleto = array_sum($totalGeral);
// REPARE QUE OS DADOS DO BOLETO ESTÃO FORA DO FOREACH
// POIS OS DADOS SÃO ÚNICOS
// DADOS DO BOLETO PARA O SEU CLIENTE
$dias_de_prazo_para_pagamento = 5;
$taxa_boleto = 2.95;
$data_venc = date("d/m/Y", time() + ($dias_de_prazo_para_pagamento * 86400));
// Prazo de X dias OU informe data: "13/04/2006";
// aqui eu incluí o valor para ser somado com as taxas
$valor_boleto = number_format($ValorTotalBoleto+$taxa_boleto, 2, ',', '');
$dadosboleto["nosso_numero"] = '12345678';
// Nosso numero - REGRA: Máximo de 8 caracteres!
$dadosboleto["numero_documento"] = '0123';
// Num do pedido ou nosso numero
$dadosboleto["data_vencimento"] = $data_venc;
// Data de Vencimento do Boleto - REGRA: Formato DD/MM/AAAA
$dadosboleto["data_documento"] = date("d/m/Y");
// Data de emissão do Boleto
$dadosboleto["data_processamento"] = date('d/m/Y');
// Data de processamento do boleto (opcional)
$dadosboleto["valor_boleto"] = $valor_boleto;
// Aqui eu quero inserir o valor total da compra.
?>
claro que pode haver algum erro, pois eu não fiz testes com o seu DB.
SQL
Com o sql você pode montar uma query que faça essa soma direto do DB.
$soma = $conn->prepare("SELECT SUM (preco) FROM produtos");
Porém não consegui imaginar aonde poderia colocar e como montar essa query pois não conheço seu banco de dados. E pelo que eu percebi o seu carrinho é montado apenas por sessão o que dificulta ainda mais a montagem dessa query
De qualquer forma o php deve resolver.
Se tiver algum erro, poste ele no comentário que eu tento arruma-lo.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I sort string arrays or convert IEnumerable to string array?
I'm trying to sort files into string arrays of extension .RAR and .ZIP to save for later usage. The args parameter will be usually be strings of filepaths and may differ in count.
eg.
args = {"..\test1.rar", "..\test2.rar", "..\source.txt", "..\randomfile.exe", "test3.zip"}
This code
public void ValidateFiles(string[] args) {
var validRar = from item in args
where Path.GetExtension(item) == ".rar" || Path.GetExtension(item) == ".r00"
select item;
var validZip = from item in args
where Path.GetExtension(item) == ".zip"
select item;
//do some more stuff
}
makes validRar and validZip of type IEnumerable<string>. How do I sort them to string[] instead?
Optimal result would be
string[] validRar = {"test1.rar", "test2.rar"}
string[] validZip = {"test3.zip"}
A:
You simply need to call ToArray:
public void ValidateFiles(string[] args)
{
var validRar = (from item in args
where Path.GetExtension(item) == ".rar" ||
Path.GetExtension(item) == ".r00"
select item).ToArray();
var validZip = (from item in args
where Path.GetExtension(item) == ".zip"
select item).ToArray();
//do some more stuff
}
Now, both validRar and validZip are string[].
| {
"pile_set_name": "StackExchange"
} |
Q:
List of completed Pull Request's through Azure DevOps Services Rest Api
Tyring to use the Azure DevOps Services Rest Api
https://docs.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1
Can anyone suggest the correct API to call to obtain a List of Completed Pull Requests for a Repository
I have been looking at the Git Api, but it seems that particular API only returns PR's that have not yet been completed.
A:
This example available on the Rest Api doc site: Just completed pull requests
GET https://dev.azure.com/fabrikam/_apis/git/repositories/3411ebc1-d5aa-464f-9615-0b527bc66719/pullrequests?searchCriteria.status=completed&api-version=5.1
| {
"pile_set_name": "StackExchange"
} |
Q:
how to use ajax on magento's default adminhtml form.php?
$event = $fieldset->addField('parent_id', 'select', array(
'label' => Mage::helper('gallery')->__('Parent'),
'required' => true,
'name'=>'parent_id',
'values'=>$ac,
'onchange'=>'CheckSelectedItem()',
));
$event->setAfterElementHtml('<script>
function CheckSelectedItem()
{
var ddllist= window.document.getElementById("parent_id");
var itemName= ddllist.options[ddllist.selectedIndex].value;
how to make an ajax call on form.php for the file that resides in root folder called "gallerydata.php".
i have an extension called "gallery" for uploading image from backend. so i want to get an id of artist from dropdown by using ajax which makes call to that file "gallerydata.php".
if(window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
xmlhttp1=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://122.170.97.189:81/electriccityusa/gallerydata.php?q="+itemName,true);
}
</script>');
A:
You can simply use ajax in adminhtml form as:
$event = $fieldset->addField('parent_id', 'select', array(
'label' => Mage::helper('gallery')->__('Parent'),
'required' => true,
'name' => 'parent_id',
'values' => $ac,
'onchange' => 'checkSelectedItem(this)',
));
$event->setAfterElementHtml("<script type=\"text/javascript\">
function checkSelectedItem(selectElement){
var reloadurl = '". $this->getUrl('your-module-controller-action')."parent_id/' + selectElement.value;
new Ajax.Request(reloadurl, {
method: 'get',
onLoading: function (transport) {
$('parent_id').update('Searching...');
},
onComplete: function(transport) {
$('parent_id').update(transport.responseText);
}
});
}
</script>");
Now you can fetch the select value and do operation as per required in your custom module controller action (mentioned in reloadurl).
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
start iPad application from another application built in Flash
Do you know is it possible to start iPad application from another application that is developed in Flash?
I need to create small iPad app with two buttons (and some graphics/animation) in Flash. Clicking on those buttons, another iPad application should be started.
My guess is that will use ExternallInterface, but I don't know what to send :)
Thank you!
A:
If you want to launch another app from your app then you can do it using URL Scheme provided by apple
Here is the documentation on this one http://developer.apple.com/library/ios/#featuredarticles/iPhoneURLScheme_Reference/Articles/PhoneLinks.html
And a useful link that gives url scheme for most of the apps available out there.
http://maniacdev.com/2010/07/find-ios-custom-url-schemes-from-thousands-of-apps-and-add-yours/
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I make something happen for a set number of frames?
I want to add a nitro boost feature to my racing game. I want the car to go faster for 45 frames when the nitro is used, but for whatever reason I can't make it work. I originally tried using a while loop but obviously that doesn't work for JavaScript physics. Here's what I have now:
this.nitro = function() {
if (this.hasNitro) {
this.nitroSpeed = this.carSpeed * 2;
this.speedCopy = this.carSpeed;
var refreshIntervalId = setInterval(function() {
this.carSpeed = this.nitroSpeed;
this.nitroCount--;
if(this.nitroCount==0){
this.endNitro();
}
}, 1000 / FRAMES_PER_SECOND);
}
}
this.endNitro = function(){
clearInterval(refreshIntervalId);
this.carSpeed = this.speedCopy;
this.hasNitro = false;
}
There are two cars in the game, each an instance of the car class. One of them is controlled with the arrow keys and the other is controlled with WASD. When the car's nitro button is pressed, nitro() is called on that car. The goal of the nitro is to double the car's speed for NITRO_TIME frames. When the car is initialized, nitroCount is set to NITRO_TIME.
A:
Assuming that you have these parameters in you Car class:
this.StandardSpeed = 33; // Your own units here; set this to your liking
this.NitroFactor = 2.0; // set this to your liking
this.NitroDuration = 45; // In frames; set this to your liking
I would suggest that once the 'nitro' button is pressed, enable a 'time left' counter to your Car object:
this.nitroFramesLeft = this.NitroDuration;
then in the 'update' method of your car (the 'move' method), apply the nitro if the counter is not zero:
var carSpeed = this.StandardSpeed;
if ( this.nitroFramesLeft > 0)
{
this.nitroFramesLeft = this.nitroFramesLeft - 1;
carSpeed = carSpeed * this.NitroFactor;
}
// Move the car with the modified (or not) carSpeed.
It's as simple as that :)
I've not done a lot of JavaScript in my life, so this might not be the exact syntax, but it will give you a good idea.
Also, typically, you'll want a single setInterval in your code as much as possible, and that's what is going to run your main loop.
Adding other calls to setInterval will eventually lead to headaches for debugging.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery hover interrupting toggleClass
so below is my script. I intend to do something really basic i.e. have different background-color on hover on different buttons (regular/inactive and active). And when clicked, toggle between the two states.
Now, this code does the hover correctly but doesn't toggles.
<script type="text/javascript">
$(".button").hover(
function() {
$(this).css("background-color", "#E4E4E4");
},
function() {
$(this).css("background-color", "#EDEDED");
}
);
$(".active").hover(
function() {
$(this).css("background-color", "#F5F9FF");
},
function() {
$(this).css("background-color", "#EBF3FF");
}
);
$(".button").click(function() {
alert("The button is clicked!");
$(this).toggleClass("active");
});
</script>
And, this code does toggles but I have to disable hover for it to happen
<script type="text/javascript">/*
$(".button").hover(
function() {
$(this).css("background-color", "#E4E4E4");
},
function() {
$(this).css("background-color", "#EDEDED");
}
);
$(".active").hover(
function() {
$(this).css("background-color", "#F5F9FF");
},
function() {
$(this).css("background-color", "#EBF3FF");
}
);*/
$(".button").click(function() {
alert("The button is clicked!");
$(this).toggleClass("active");
});
</script>
TL;DR I am not able to use hover() and toggleClass() together.
Note: The alert shows though.
A:
I join the comment above about the event you are trying to generate on an element which does not exist in the DOM at the time.
You can style your elements with css and then trigger the class on click with javascript.
$(".button").click(function() {
$(this).toggleClass("active");
});
button {
background-color: blue;
}
button:hover {
background-color: royalblue;
}
button.active {
background-color: purple;
}
button.active:hover {
background-color: rebeccapurple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button">
Click Me
</button>
<button class="button active">
Click Me
</button>
| {
"pile_set_name": "StackExchange"
} |
Q:
Find The Least Common Characters
Given a string, find the 10 least common alpha-numeric characters within that string.
Output should be formatted with numbers left-padded with spaces so they look like this:
e: 1
t: 16
c: 42
b: 400
z: 50000
a: 100000
Use this to test your program: here
Output for test case:
j: 2
x: 3
q: 9
k: 32
v: 67
c: 73
w: 79
f: 93
b: 94
p: 96
Shortest code wins. You can submit a program or a function.
A:
K, 60
{(-:|/#:'f)$f:10#$(!x)[i]!r i:<r:. x:#:'=_x@&x in,/.Q`a`A`n}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remove these unneeded permissions
I'm building project with android-studio gradle build system. I have two of below permissions
android.permission.ACCESS_NETWORK_STATE
android.permission.INTERNET
but build system adds these new permissions automatically.
android.permission.READ_EXTERNAL_STORAGE maxSdkVersion=18
android.permission.READ_PHONE_STATE
android.permission.WRITE_EXTERNAL_STORAGE maxSdkVersion=18
I don't understand why these permissions added. And how to remove these permissions?
Here is my build config
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "my.app.package.name"
minSdkVersion 8
targetSdkVersion 20
versionCode 2
versionName "1.0.1"
}
signingConfigs {
debug {
storeFile file(System.getProperty("user.home")+"/.android/debug.keystore")
}
release {
storeFile file("keystore.jks")
storePassword "password"
keyAlias "alias"
keyPassword "password"
}
}
buildTypes {
/*release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}*/
marketShareRelease {
debuggable false
jniDebuggable false
signingConfig signingConfigs.release
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:20.0.0'
compile 'com.viewpagerindicator:library:2.4.1'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.commonsware.cwac:merge:1.0.2'
}
My previous build almost same (on October 8, 2014). Simply Android studio and sdk are updated
A:
One of your libraries has a targetSdk <= 4. (Looks like your cwac-merge)
This causes the permissions to be auto added: http://developer.android.com/reference/android/Manifest.permission.html#READ_PHONE_STATE
| {
"pile_set_name": "StackExchange"
} |
Q:
bind10 cannot automatically tranfer zone from master to slave
I followed this guide to configure Zone transfer in bind10:
http://www.tokiwinter.com/bind-10-zone-transfers-tsig-and-ddns/
Everything worked ok except that It didn't automatically transfer zone from master to slave when I ran
nsupdate on master server.
It only transferred when I ran: > Xfrin retransfer example.com on slave server.
Did i miss something in configuration?
I'm using bind10 1.1.0.
Thanks in advance.
A:
Set a small refresh time in SOA record:
example.com. IN SOA ns1.example.com. hostmaster.example.com. ( 2013140201
172800 900 1209600 3600 )
Become:
example.com. IN SOA ns1.example.com. hostmaster.example.com. ( 2013140201
2 900 1209600 3600 )
So that the slave automatically send a request to transfer zone if any changes in that period of time (2 seconds).
That solved!
Thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
How to hide wrapped components in React
I need to be able to hide components that gets wrapped because it goes over the max width.
<div style={{width:100}}>
<div style={{width:50}}>
component1
</div>
<div style={{width:50}}>
component2
</div>
<div style={{width:50}}>
component3
</div>
</div>
//But I actually use map to render children
<div style={{width:100}}>
{components.map((item, index) => {
return <div style={{width:50}}>component{index + 1}</div>)
}}
</div>
as shown in the code above, the parent div is of with 100. So the last component (component3) would go over the width of the parent by 50px and will be rendered in the second line. However, I want any component that leaves the first line to be not rendered at all. How do I make sure that only component1 and component2 shows and excludes component3?
A:
You could add up the widths of all the components in a separate variable, and render null for all components remaining after the total width of those already rendered exceeds 100.
Example
class App extends React.Component {
state = {
components: [{ width: 50 }, { width: 50 }, { width: 50 }]
};
render() {
const { components } = this.state;
let totalWidth = 0;
return (
<div style={{ width: 100 }}>
{components.map((item, index) => {
totalWidth += item.width;
if (totalWidth > 100) {
return null;
}
return (
<div key={index} style={{ width: 50 }}>
component{index + 1}
</div>
);
})}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
DB grid : How to use a column of the current row of one as an index into another?
I am not sure if the question title is clear enough, please feel free to edit it.
Basically, I have two DB grids which reflect two database tables, each grid showing one.
When the user selects a row in the first table (let's call it oders), I want to update the second with details of any rows matching a column of the selected row of the first table.
Say, for instance that table orders has a column customer_id and I want to populate the second table (let's call it order_details) with details of all orders from that customer, one order per row.
I can connect up 2 @ datasource, query and connection to the two TDbGrids, but I am stuck as to how to code order_details SQL.
The SQL for orders is just SELECT * from orders, but the other?
I want something like SELECT * from order_details WHERE cutomer_id=<orderQuery>.currentRow.FieldByName("customer_id").AsInteger - but I don't know how to do that ...
Can someone help me with some Delphi code?
Also, once I set up that relationship, will selecting a new row in the orders DB grid automatically update the order_details DB grid? Or do I need to add code for that.
P.s I know that there is no books tag anymore (more's the pity), but can someone recommend a good book which explains the fundamentals of programming DB aware controls? I obviously need one. Thanks
A:
Use a parameterized query for the detail (child) database:
SELECT * FROM Order_Details od WHERE od.CustomerID = :CustomerID
Then set the child query's MasterSource to the parent (Order) datasource, and the MasterFields to CustomerID. (If there are multiple columns that link the two, separate them by ;, as in CustomerID;OrderNumber.)
Every time you scroll the parent (change the selected record in the parent DBGrid), the child query will be executed with the ID of the parent row passed as a parameter automatically.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to transfer a question from one StackExchange site to another?
I had asked a question in Android Enthusiasts which got closed as it was more relevant in StackExchange site.
Is there anyway to transfer that question without creating a new one?
A:
Flag it for moderator attention; the diamond mods have the ability to migrate from any site to any site.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sinon does not mock provided URL for GET with parameters
I am trying to develop test for my services in Angular app and facing some issues with it.
Here is the service code:
/**
* Sends http request to get client states and territories available for specific vertical
*
* @param {number} vertical id of specific vertical. The following mapping is used:
* 0 - Federal
* 1 - State
* 2 - Local
* 3 - Education
* @returns {Observable<State[]>} array of state objects with its display name and value as observable
*/
getClientsStatesByVertical(vertical: VerticalEnum): Observable<State[]> {
let params = new HttpParams();
if (vertical != null) {
params = params.append('vertical', String(vertical));
}
return this.http
.get(`${CLIENT_API_ENDPOINT}/csr/states`, {params: params}) as Observable<State[]>;
}
Here is my test:
it('#getClientsStatesByVertical with vertical provided', (done) => {
const expectation = [{label: 'Georgia', value: 'GA'}];
server.respondWith('GET', `${CLIENT_API_ENDPOINT}/csr/states?vertical=${VerticalEnum.Federal}`);
const o = service.getClientsStatesByVertical(VerticalEnum.Federal);
o.subscribe(response => {
expect(response).toEqual(expectation);
done();
});
server.respond();
});
I am getting the following error when I am running this test using karma:
HttpErrorResponse: Fake server request processing threw exception: Http failure response for http://localhost:19000/api/v1/clients/csr/states: 404 Not Found
Could you please point me to the issue, seems that I am missing smth simple, cause almost the same cases with shorter URLs are working perfectly
A:
Actually I forgot to add response into respondWith function :)
server.respondWith('GET', `${CLIENT_API_ENDPOINT}/csr/states?vertical=${VerticalEnum.Federal}`, JSON.stringify(expectation));
it solved the issue
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Cómo obtener el grupo de un usuario en linux [lenguaje C]
mi duda es la siguiente
Como puedo obtener el grupo de un usuario en el lenguaje C.
Mi código es el siguiente:
char *getGroup (gid_t gr){ (la cabecera de la función)
struct passwd *m;
if ((m = getpwuid(gr)) == NULL)
return "desconocido";
return (m -> pw_gid);
}
Cuando compilo me salta un warning, es el siguiente:
warning : return makes pointer from integer without a cast
return (m -> pw_gid);
Lo que tengo que hacer es obtener el grupo de el usuario, similar a lo que hace el comando ls -li en linux.
Un saludo, muchas gracias
A:
Simplemente, tienes que hacer una llamada a getgrgid:
#include <grp.h>
#include <pwd.h>
#include <string.h>
#include <sys/types.h>
char *getGroup( gid_t gr ) {
struct passwd *m;
struct group *group_info;
if ((m = getpwuid(gr)) == NULL)
return "desconocido";
group_info = getgrgid( m->pw_gid );
return strdup( group_info->gr_name );
}
Como ves, copio los datos que me interesan con strdup( ), puesto que sucesivas llamadas a getgrgid( ) sobreescriben su propio buffer interno.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get a specific child value from firebase depends on the date(DAY)
Here is my data structure
So the 0 is the 1st day of the month and so on. So basically it's looping but I have no idea what should I do. I need an idea where to start or what should I do.
What I want my output is
So if its the first day of the month so thats 0 on the child the price will be 1 and the next day will be 2
This is my code
mRef3 = mRef.child(key).child("promos").child("regular").child(ym).child("price").child("guest1/0");
mRef3.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String price = dataSnapshot.getKey()+": "+dataSnapshot.getValue();
holder.rPrice.setText("FROM " + getString(R.string.currency) + " " + price + " per night ");
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
CURRENT OUTPUT:
FROM USD 0:1 per night
A:
If you want to read the value from the database for a specific day, you can do something like this:
DatabaseReference dayRef = FirebaseDatabase.getInstance().getReference("price/guest1/0");
dayRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getKey()+": "+dataSnapshot.getValue(Long.class));
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
If you want to read the values for all days from the database, you'll attach the listener one level higher and loop over the children of the snapshot:
DatabaseReference dayRef = FirebaseDatabase.getInstance().getReference("price/guest1");
dayRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot daySnapshot: dataSnapshot.getChildren()) {
System.out.println(daySnapshot.getKey()+": "+daySnapshot.getValue(Long.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
If you want to get the 0-based day of the month:
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
| {
"pile_set_name": "StackExchange"
} |
Q:
Determining whether this congruence is solvable: $3x^2+6x+5 \equiv 0\pmod{89}$
I'm trying to figure out whether the following quadratic congruence is solvable: $3x^2+6x+5 \equiv 0\pmod{89}$.
It's impossible to divide $3x^2+6x+5$ to a form of $f(x) \cdot g(x)=3x^2+6x+5$ and then to check whether $f(x)\equiv 0
\pmod{89}$ or $g(x)\equiv 0(89)$, but $3x^2+6x+5 \equiv 0\pmod{89}$ is equal to $3(x+1)^2+2 \equiv 0\pmod{89}$ or $3(x+1)^2 \equiv -2\pmod{89}$ or $3(x+1)^2 \equiv 87\pmod{89}$ or
$(x+1)^2 \equiv 29\pmod{89}$. for $y=x+1$, I need to determine whether $y^2 \equiv 29\pmod{89}$ is solvable, and it is not. Am I able to conclude something about the original equation in this way? what is the correct way to solve this problem?
Thanks a lot!
A:
Yes, your inference is correct. Essentially it is a special case of the well-known discriminant test. Namely, if a quadratic $\rm\:f(x)\in R[x]\:$ has a root in a ring R, then its discriminant is a square in R. Said contrapositively, if the discriminant is not a square in R, then the quadratic has no root in R.
The proof by completing the square works in any ring R (so in $ \mathbb Z/89 = $ integers mod $89$), viz.
$$\rm\: \ \ 4a\:(a\:x^2 + b\:x + c = 0)\:\Rightarrow\: (2a\:x+b)^2 =\: b^2 - 4ac $$
When learning about (modular) arithmetic in new rings it is essential to keep in mind that, like above, any proofs from familiar concrete rings (e.g. $\mathbb Q,\mathbb R,\mathbb C)$ will generalize to every ring if they are purely ring theoretic, i.e. if the proof uses only universal ring properties, i.e. laws that hold true in every ring, e.g. commutative, associative, distributive laws. Thus many familar identities (e.g. Binomial Theorem, difference of squares factorization) are universal, i.e. hold true in every ring.
This is one of the great benefits provided by axiomatization: abstracting the common properties of familiar number systems into the abstract notion of a ring allows one to give universal proofs of ring theorems. It is not necessary to reprove these common ring properties every time one studies a new ring (such reproofs occurred frequently before rings was axiomatized).
| {
"pile_set_name": "StackExchange"
} |
Q:
Avoid creating backscatter on a Postfix forwarding server
I run a Postfix server that hosts a small, alias-based mailing list. Let's say people@myserver forwards to alice@someprovider and bob@someotherprovider. Now, alice@someprovider might use a more restrictive spam filter than I do.
When a spam mail from (forged) backscattervictim@somewhere to people@myserver arrives, and my spam filter detects it as spam, it is rejected in the SMTP phase --> no harm done.
However, when the same mail gets through my server, my server tries to forward it to alice, and her server rejects it during the SMTP phase, my server creates a bounce message to the innocent backscatter victim. (Which makes sense from the point of view of my server, but it's annoying for the backscatter victim.)
Is there a way to prevent this behavior? I don't want to turn off NDRs, since (in general) they serve a legitimate purpose.
A:
If it isn't flagged as spam, but alice rejects the mail, I can't see a way for your Postfix server to not bounce the mail back to the victim, without turning off NDR's :(
Perhaps if alice marked that mail as spam somewhere in the header back to you?
| {
"pile_set_name": "StackExchange"
} |
Q:
error at return response.meta[ ]
I was running the below code and the code seems to have some problems.
what is shown below is not my entire code, I will post the rest of the code if someone asks me for it:
from threading import Thread
from selenium import webdriver
from scrapy.http import Request
from urlparse import urlparse
from scrapy.spider import BaseSpider
class MySpider(BaseSpider):
name = "scrapy"
def get_url():
url = raw_input('Enter the url of your website (including the http)')
return url
start_url = str(get_url())
def parse(self,response):
return response
def get_depth():
scrapies = MySpider()
response= Request(scrapies.start_url)
return response.meta['depth']
The error occurs at return response.meta['depth']. the error message doesn't have a specific content, it just says key error: depth, so I am not sure how to fix that. Does this mean that the depth is not appropriate argument to the meta?
thanks..
A:
You need to use Yield to call get_depth and pass the meta values along with it. See the example below.
yield Request(url=someurl, callback=self.get_depth,meta={'key': value}, )
| {
"pile_set_name": "StackExchange"
} |
Q:
RegEx.Replace in a textbox
I have a Textbox and the following code to allow only numbers:
textBox1.Text = Regex.Replace(textBox1.Text, "[^\\d]", "");
Now when I type another key than numbers, the focus goes to the beginning of the Textbox...What do I need to not let this happen?
A:
Use MaskedTextBox instead, specifying the Mask property.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing the behaviour of the caret position movement in intellij
Let's assume we have the following line of code:
private final String |sourceCode = "int a";
where | is the caret position.
If pressing CTRL + RIGHT, the caret will currently go to
private final String sourceCode |= "int a";
yet I'd like it to go to
private final String source|Code = "int a";
as happens in many other IDEs. How to change that setting in intellij?
A:
Go to Settings->Editor->Smart Keys and enable "Use CamelHumps words". You can also disable the option "Honor CamelHumps words settings when selecting on double click" in Settings->Editor, to mimic better the behavior of other (Eclipse?) IDE's.
Regards
| {
"pile_set_name": "StackExchange"
} |
Q:
Greater caloric surplus on training days?
Imagine one being in a slight caloric surplus of roughly 500kcal above their maintenance value every day, but only training four times a week. Is it better to split the eating behavior in training and non-training days or stick to the same calorie intake every day?*
Since I'd imagine a subject like that would need like 300-500kcal extra in order to compensate for the training (weight lifting) on training days but not on non-training days.
I think a little example would describe the issue better:
An evenly distributed caloric surplus of 500kcal a day would result in 3500kcal for one whole week.
However going for a whopping 650kcal extra 4 days a week (training days) and only about 300kcal on the other day (in total also 3500kcal a week)
Would one of these options be better than the other? If yes, why? Or wouldn't that really take an effect at all?
*When training for muscle hypertrophy and eating to bulk up a little.
A:
I think as long as the net calorie surplus of the week stays at 3500kcal (for your example) it shouldn't make too much of a difference in overall "hypertrophy gains" or strength for that matter. As long as you're applying progressive overload, consistency and tracking your lifts the 650kcal surplus days shouldn't feel too different from the 500kcal surplus days.
With that being said, I think the only scenario you would need to increase the surplus more than usual would be if you was in a decefit for 1+ days during the week, then at that point it would be necessary to bump up the surplus for the remaining days of the week to make sure you meet your net surplus for that week.
| {
"pile_set_name": "StackExchange"
} |
Q:
JSON Value (UWP C#)
I writing app for Windows 10.
I have connection with WooCommerce with WooCommerce.Net plugin
Here it is plugin
I have JSON string.
Code:
RestAPI rest = new RestAPI("http://simplegames.com.ua/wp-json/wc/v1/", "ck_9d64c027d2c5f81b8bed3342eeccc6d337be813d", "cs_60697b1e6cbdeb8d62d19e0765e339f8e3334754");
WCObject wc = new WCObject(rest);
//Получение заказов
var orders = await wc.GetOrders()
string products = orders[1].line_items.ToFormattedJsonString();
Debug.WriteLine(products);
I have this JSON in Console
[
{
"id": 72,
"name": "Із лосося",
"sku": "344",
"product_id": 1134,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"price": 75.00,
"subtotal": 75.00,
"subtotal_tax": 0.00,
"total": 75.00,
"total_tax": 0.00,
"taxes": [
],
"meta": [
]
},
{
"id": 73,
"name": "Італьяно",
"sku": "340",
"product_id": 1138,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"price": 38.00,
"subtotal": 38.00,
"subtotal_tax": 0.00,
"total": 38.00,
"total_tax": 0.00,
"taxes": [
],
"meta": [
]
}
]
I need to write value from this JSON
for example name to variable.
How I can do this?
A:
It depends on the order line item from where you want to write value from. Assuming int X and int Y to be less than equal to orders.count, orders.line_items.count respectively, You can get the values directly with orders[X].line_items[Y].Propertyname
A better idea would be to create classes representing the business objects and then translating property values into your objects and using it for your application purposes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Including extra information in PUT response
Is it ok to return extra information in http PUT response such as createdDateTime or lastUpdateTime
E.g. PUT request comes as follows
properties
{
"name": "somename"
"addr": "someaddr"
}
In response along with sending the resource representation I am sending extra information
HTTP OK or CREATED
properties
{
"name": "somename"
"addr": "someaddr"
"lastUpdateTime": "somedatetime"
}
Is this a bad practice ?
A:
I see no problem with that. If the client needs that information, then the resource will have to include it as a property. The client can POST/PUT without it (NULL), or the server will ignore it anyway (since this is only set server-side), but it will have to reflect it afterwards.
You can always secure your API if you're going to expose it publicly (OAuth, API keys etc).
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Connect Via PHP
$serverName = "172.20.90.100";
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"correctdb");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
this is giving me this error:
Fatal error: Call to undefined function sqlsrv_connect() On LINE 23
I was wondering what I should change to establish a connection.
A:
sqlsrv_connect() is a php function embedded in the SQL server extension. The error shows you haven't enabled it yet.
You have to enable the extension. How this is done is described here in the manual.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between close and abort in RL_ARM's TCP mode
What's the difference between TCP's close and TCP's abort? Following is an example:
..//init the socket FD
while(1)
{
switch(socket_state)
{
case 0:
if(0 != FD)
{
tcp_connect(FD,rem_ip, 502, 0);
socket_state = 1;
break;
}
case 2:
if(TRUE == wait_ack)
{
return;
}
..//sending data
wait_ack = TRUE;
break;
case 3:
{
if(0 != FD)
{
tcp_close(FD); //or tcp_abort(FD);
tcp_release_socket(FD);
soc_state = 0;
}
}
break;
}
}
tcp_callback:
U16 Listener(U8 socket,U8 event,U8* ptr,U16 par)
switch(event)
{
case TCP_EVT_CONNECT:
soc_state = 2;
break;
case TCP_EVT_ACK:
wait_ack = __FALSE;
break;
case TCP_EVT_ABORT:
soc_state = 3;
break;
}
return (1);
Now, when I shut the server down, my client will receive a TCP_EVT_ABORT message, and set soc_state = 3. In while(1) loop, switch sees this and goes into case 3. Do I want it to close, or abort? In the next loop iteration, I go back to state 0. Why is the file descriptor still not 0?
How can I use abort or close mechnism correctly?
A:
A little hard to understand,When you use tcp_get_socket,then the socket is allocated and its state is TCP_STATE_CLOSED.After that,using tcp_connect to connect remote server.Its state will change to TCP_STATE_SYN_REC.When connection is established,state become TCP_STATE_CONNECT.When server side is shut down,Client side will receive EVENT : TCP_EVT_ABORT. I close current socket using tcp_release_socket. Also when data is sent completed,using this function close socket.Next time ,we should invoke tcp_get_socket before tcp_connect with the old socket. For short,every connection,every tcp_get_socket.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove some options from room config MUC
When owner join and the room and open room config panel when few config options appears.
I want to remove some options from config panel like
Maximum number of users > max limit is 200 but i want to set max limit to 30 and field is uneditable. (No one can change 30 limit)
Pressence real Jids to - (Default is Moderator)
i want to set default value is Everyone and field hidden.
Roles of which presence is broadcast
(Default is selected all). just want to hide this field. Nothing change.
Make room moderated (just want to hide this field. Unchecked.)
Default users as participant (just want to hide this field. Checked by default)
Allow visitors to send status text in presence broadcast (Just want to hide this field. Unchecked)
Allow visitor to change nickname (just want to hide this field. Unchecked)
Allow visitor to send voice request (Just want to Uncheck and hide this field)
Allow Subscribtion (Just want to Uncheck and hide this field)
I know these all modification will done in .erl file and i try to do but nothing happens. Can anyone know how to do this.
Please help.
A:
As a server admin, you can set default room values in ejabberd.yml with this mod_muc option: default_room_options, see https://docs.ejabberd.im/admin/configuration/#mod-muc
Then you have to modify mod_muc_room.erl to hide the field, and also to not use the options if a clever room owner adds them manually. Later you compile this file (or all ejabberd), and install the modified mod_muc_room.beam, overwritting the old one, and finally restart ejabberd. If you don't see the changes, maybe you copied the beam file to another place (maybe you have two ejabberd installed, one that is running and other that is old and is confusing you?).
I think this change includes all the options you wanted, but better you verify, maybe I forgot some. I tried this change in ejabberd 18.09, and it hides several options in the room config formulary:
diff --git a/src/mod_muc_room.erl b/src/mod_muc_room.erl
index 267514b20..a6fc0e73f 100644
--- a/src/mod_muc_room.erl
+++ b/src/mod_muc_room.erl
@@ -58,7 +58,7 @@
-include("mod_muc_room.hrl").
-define(MAX_USERS_DEFAULT_LIST,
- [5, 10, 20, 30, 50, 100, 200, 500, 1000, 2000, 5000]).
+ [30]).
-define(DEFAULT_MAX_USERS_PRESENCE,1000).
@@ -3363,23 +3363,23 @@ get_config(Lang, StateData, From) ->
MaxUsersRoom
| ?MAX_USERS_DEFAULT_LIST]),
N =< ServiceMaxUsers]},
- {whois, if Config#config.anonymous -> moderators;
- true -> anyone
- end},
- {presencebroadcast, Config#config.presence_broadcast},
+ %{whois, if Config#config.anonymous -> moderators;
+ % true -> anyone
+ % end},
+ %{presencebroadcast, Config#config.presence_broadcast},
{membersonly, Config#config.members_only},
- {moderatedroom, Config#config.moderated},
- {members_by_default, Config#config.members_by_default},
+ %{moderatedroom, Config#config.moderated},
+ %{members_by_default, Config#config.members_by_default},
{changesubject, Config#config.allow_change_subj},
{allow_private_messages, Config#config.allow_private_messages},
{allow_private_messages_from_visitors,
Config#config.allow_private_messages_from_visitors},
{allow_query_users, Config#config.allow_query_users},
{allowinvites, Config#config.allow_user_invites},
- {allow_visitor_status, Config#config.allow_visitor_status},
- {allow_visitor_nickchange, Config#config.allow_visitor_nickchange},
- {allow_voice_requests, Config#config.allow_voice_requests},
- {allow_subscription, Config#config.allow_subscription},
+ %{allow_visitor_status, Config#config.allow_visitor_status},
+ %{allow_visitor_nickchange, Config#config.allow_visitor_nickchange},
+ %{allow_voice_requests, Config#config.allow_voice_requests},
+ %{allow_subscription, Config#config.allow_subscription},
{voice_request_min_interval, Config#config.voice_request_min_interval},
{pubsub, Config#config.pubsub}]
++
@@ -3440,27 +3440,27 @@ set_config(Opts, Config, ServerHost, Lang) ->
C#config{allow_private_messages = V};
({allow_private_messages_from_visitors, V}, C) ->
C#config{allow_private_messages_from_visitors = V};
- ({allow_visitor_status, V}, C) -> C#config{allow_visitor_status = V};
- ({allow_visitor_nickchange, V}, C) ->
- C#config{allow_visitor_nickchange = V};
+ %({allow_visitor_status, V}, C) -> C#config{allow_visitor_status = V};
+ %({allow_visitor_nickchange, V}, C) ->
+ %C#config{allow_visitor_nickchange = V};
({publicroom, V}, C) -> C#config{public = V};
({public_list, V}, C) -> C#config{public_list = V};
({persistentroom, V}, C) -> C#config{persistent = V};
- ({moderatedroom, V}, C) -> C#config{moderated = V};
- ({members_by_default, V}, C) -> C#config{members_by_default = V};
+ %({moderatedroom, V}, C) -> C#config{moderated = V};
+ %({members_by_default, V}, C) -> C#config{members_by_default = V};
({membersonly, V}, C) -> C#config{members_only = V};
({captcha_protected, V}, C) -> C#config{captcha_protected = V};
({allowinvites, V}, C) -> C#config{allow_user_invites = V};
- ({allow_subscription, V}, C) -> C#config{allow_subscription = V};
+ %({allow_subscription, V}, C) -> C#config{allow_subscription = V};
({passwordprotectedroom, V}, C) -> C#config{password_protected = V};
({roomsecret, V}, C) -> C#config{password = V};
({anonymous, V}, C) -> C#config{anonymous = V};
({presencebroadcast, V}, C) -> C#config{presence_broadcast = V};
- ({allow_voice_requests, V}, C) -> C#config{allow_voice_requests = V};
+ %({allow_voice_requests, V}, C) -> C#config{allow_voice_requests = V};
({voice_request_min_interval, V}, C) ->
C#config{voice_request_min_interval = V};
- ({whois, moderators}, C) -> C#config{anonymous = true};
- ({whois, anyone}, C) -> C#config{anonymous = false};
+ %({whois, moderators}, C) -> C#config{anonymous = true};
+ %({whois, anyone}, C) -> C#config{anonymous = false};
({maxusers, V}, C) -> C#config{max_users = V};
({enablelogging, V}, C) -> C#config{logging = V};
({pubsub, V}, C) -> C#config{pubsub = V};
There's an option that disallows visitors to change nickname. If you want this option to also disallow participants, apply this change:
diff --git a/src/mod_muc_room.erl b/src/mod_muc_room.erl
index 267514b20..16ce21ba1 100644
--- a/src/mod_muc_room.erl
+++ b/src/mod_muc_room.erl
@@ -1031,7 +1031,7 @@ do_process_presence(Nick, #presence{from = From, type = available, lang = Lang}
StateData#state.host,
From, Nick),
{(StateData#state.config)#config.allow_visitor_nickchange,
- is_visitor(From, StateData)}} of
+ is_visitor_or_participant(From, StateData)}} of
{_, _, {false, true}} ->
Packet1 = Packet#presence{sub_els = [#muc{}]},
ErrText = <<"Visitors are not allowed to change their "
@@ -1501,6 +1501,11 @@ get_default_role(Affiliation, StateData) ->
is_visitor(Jid, StateData) ->
get_role(Jid, StateData) =:= visitor.
+is_visitor_or_participant(Jid, StateData) ->
+ (get_role(Jid, StateData) =:= visitor)
+ or
+ (get_role(Jid, StateData) =:= participant).
+
-spec is_moderator(jid(), state()) -> boolean().
is_moderator(Jid, StateData) ->
get_role(Jid, StateData) =:= moderator.
On the other hand, if you want to disallow all roles to change the nick, the change is smaller:
diff --git a/src/mod_muc_room.erl b/src/mod_muc_room.erl
index 267514b20..2ef75e6ed 100644
--- a/src/mod_muc_room.erl
+++ b/src/mod_muc_room.erl
@@ -1032,7 +1032,7 @@ do_process_presence(Nick, #presence{from = From, type = available, lang = Lang}
From, Nick),
{(StateData#state.config)#config.allow_visitor_nickchange,
is_visitor(From, StateData)}} of
- {_, _, {false, true}} ->
+ {_, _, {false, _}} ->
Packet1 = Packet#presence{sub_els = [#muc{}]},
ErrText = <<"Visitors are not allowed to change their "
"nicknames in this room">>,
| {
"pile_set_name": "StackExchange"
} |
Q:
"Unable to resolve..." in NetBeans 6.7.1, Linux, C++
I am working with a small group on a C++ project in NetBeans.
For some reason, NetBeans is reporting things like "string", "endl", "cout" as "Unable to Resolve" even though the correct libraries have been included.
The project compiles and runs as expected, so at the end of the day, it is no big deal, it is just that having everything marked as an error makes it quite annoying.
I haven't been able to find anything on this bug. Just one vague reference in a blog. Has anyone else experienced it?
Obviously it isn't wide-spread, so there must be a setting/configuration that causes it. Does anyone know who to prevent this from happening?
EDIT:
No, these "errors" are solely in the IDE. The code compiles fine and runs. The developer has used "using namespace std;" so there should be no issues. It appears that the NetBeans IDE is buggy.
Sample code:
#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
string test;
test = "Why?";
cout << test << endl;
return (EXIT_SUCCESS);
}
This code compiles and prints out "Why?" but has "string", "cout" and "endl" marked as errors in the IDE. Explicitly using std:: makes no difference
Clean up Edit:
For anyone interested, a few days later I had 6 updates available for NetBeans. After installing this updates, the problem was rectified, despite the code not changing. So, apparently it was a NetBeans bug.
A:
For anyone interested, a few days later I had 6 updates available for NetBeans. After installing this updates, the problem was rectified, despite the code not changing. So, apparently it was a NetBeans bug.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dependency Injection And UI Orginization
In the UI button click, I have to instantiate a DAL object before I can instantiate a BLL object. This seems cumbersome, to create the object dependencies before the object itself (more code than if the dependency was instantiated inside of BLL). Is this just the price you have to pay for using dependency injection?
It just bugs me that the preparation that is needed to instantiate BLL is in the UI. Is this the correct way to do dependency injection? Is there a way to separate the UI and BLL preparation logic cleanly?
class DAL{
//Data access layer
}
class BLL{
public BLL(DAL dal){
this.dal = dal;
}
private DAL dal;
}
buttonRun_Click(object sender, EventArgs e){
DAL dal = new DAL();
BLL bll = new BAL(dal);
bll.DoStuff();
}
A:
If you need to create these BLL objects on-the-fly, I would use a factory object. The UI could have the factory injected into it, or if you're not using injection there, it could be instantiated in the constructor.
buttonRun_Click(object sender, EventArgs e){
BLL bll = balFactory.Create();
bll.DoStuff();
}
The factory object is then responsible for instantiating an instance of BLL, and knowing exactly how that is done.
But if you DON'T need a new one with each click, why not just inject a BLL instance into the UI itself?
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display fixed size text on UIView using pinchgesturerecognizer?
I have one view(myView) and some labels are created on myView because of display text on myView. I applied pinchgesturerecognizer on myView. It's worked very well. What my problem is when i pinch on myView the size of text of labels will be changed either increase or decrease depend on pinching. If you pinch (zoom in) myView, the sizes of text of labels are very small so we can't see the text. If you pinch (zoom out) myView, the sizes of text of labels are big.
So i would like to fix size of text of labels whatever you zoom in or zoom out myView. I have tried but i did not get answer. I also use setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth but i didn't get it. I don't know how to use it. Please help me. Thanks in advance.
My Code is:
In ViewController.m,
- (void)viewDidLoad
{
MyView *myView = [[MyView alloc] initWithFrame:CGRectMake(0, 100, 200, 100)];
[self.view addSubview:myView];
[super viewDidLoad];
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scalePiece:)];
[pinchGesture setDelegate:self];
[myView addGestureRecognizer:pinchGesture];
[pinchGesture release];
}
- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer
{
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
[gestureRecognizer view].transform = CGAffineTransformScale([[gestureRecognizer view] transform], [gestureRecognizer scale], [gestureRecognizer scale]);
//[gestureRecognizer setScale:1];
}
}
In MyView.m,
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 35, 20)];
label1.font = [UIFont fontWithName:@"Helvetica-Bold" size:10];
label1.text = @"label1";
[self addSubview:label1];
label2 = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 35, 20)];
label2.font = [UIFont fontWithName:@"Helvetica-Bold" size:10];
label2.text = @"label2";
[self addSubview:label2];
label3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 35, 20)];
label3.font = [UIFont fontWithName:@"Helvetica-Bold" size:10];
label3.text = @"label1";
[self addSubview:label3];
label4 = [[UILabel alloc] initWithFrame:CGRectMake(40, 40, 35, 20)];
label4.font = [UIFont fontWithName:@"Helvetica-Bold" size:10];
label4.text = @"label4";
[self addSubview:label4];
}
return self;
}
I would like to fix the texts of label1, label2,label3, label4.
A:
It sounds like you are trying to zoom in on some items but not on others. There are two ways to approach this. Neither is very simple. You could break out the labels to their own view and manually reposition them after a pinch gesture on the other view. Or you could leave them in this view and manually rescale and position them after a pinch. Either way you'll have to do some math.
| {
"pile_set_name": "StackExchange"
} |
Q:
What do obs, ov and nv stand for in javafx listeners?
Here is an example from some javafx book:
package sample;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.SVGPath;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
* A login form to demonstrate lambdas, properties and bindings.
* @author cdea
*/
public class Main extends Application {
private final static String MY_PASS = "xyz";
private final static BooleanProperty GRANTED_ACCESS = new SimpleBooleanProperty(false);
private final static int MAX_ATTEMPTS = 3;
private final IntegerProperty ATTEMPTS = new SimpleIntegerProperty(0);
@Override
public void start(Stage primaryStage) {
// create a model representing a user
User user = new User();
// create a transparent stage
primaryStage.initStyle(StageStyle.TRANSPARENT);
Group root = new Group();
Scene scene = new Scene(root, 320, 112, Color.rgb(0, 0, 0, 0));
primaryStage.setScene(scene);
// all text, borders, svg paths will use white
Color foregroundColor = Color.rgb(255, 255, 255, .9);
// rounded rectangular background
Rectangle background = new Rectangle(320, 112);
background.setX(0);
background.setY(0);
background.setArcHeight(15);
background.setArcWidth(15);
background.setFill(Color.rgb(0, 0, 0, .55));
background.setStrokeWidth(9.5);
// background.setStroke(foregroundColor);
background.setStroke(Color.rgb(12, 233, 233));
// a read only field holding the user name.
Text userName = new Text();
userName.setFont(Font.font("SanSerif", FontWeight.BOLD, 30));
userName.setFill(foregroundColor);
userName.setSmooth(true);
userName.textProperty().bind(user.userNameProperty());
// wrap text node
HBox userNameCell = new HBox();
userNameCell.prefWidthProperty().bind(primaryStage.widthProperty().subtract(45));
userNameCell.getChildren().add(userName);
// pad lock
SVGPath padLock = new SVGPath();
padLock.setFill(foregroundColor);
padLock.setContent("M24.875,15.334v-4.876c0-4.894-3.981-8.875-8.875-8.875s-8.875,3.981-8.875,8.875v4.876H5.042v15.083h21.916V15.334H24.875zM10.625,10.458c0-2.964,2.411-5.375,5.375-5.375s5.375,2.411,5.375,5.375v4.876h-10.75V10.458zM18.272,26.956h-4.545l1.222-3.667c-0.782-0.389-1.324-1.188-1.324-2.119c0-1.312,1.063-2.375,2.375-2.375s2.375,1.062,2.375,2.375c0,0.932-0.542,1.73-1.324,2.119L18.272,26.956z");
// first row
HBox row1 = new HBox();
row1.getChildren().addAll(userNameCell, padLock);
// password text field
PasswordField passwordField = new PasswordField();
passwordField.setFont(Font.font("SanSerif", 20));
passwordField.setPromptText("Password");
passwordField.setStyle("-fx-text-fill:black; "
+ "-fx-prompt-text-fill:gray; "
+ "-fx-highlight-text-fill:black; "
+ "-fx-highlight-fill: gray; "
+ "-fx-background-color: rgba(255, 255, 255, .80); ");
passwordField.prefWidthProperty().bind(primaryStage.widthProperty().subtract(55));
user.passwordProperty().bind(passwordField.textProperty());
// error icon
SVGPath deniedIcon = new SVGPath();
deniedIcon.setFill(Color.rgb(255, 0, 0, .9));
deniedIcon.setStroke(Color.WHITE);//
deniedIcon.setContent("M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z");
deniedIcon.setVisible(false);
SVGPath grantedIcon = new SVGPath();
grantedIcon.setFill(Color.rgb(0, 255, 0, .9));
grantedIcon.setStroke(Color.WHITE);//
grantedIcon.setContent("M2.379,14.729 5.208,11.899 12.958,19.648 25.877,6.733 28.707,9.561 12.958,25.308z");
grantedIcon.setVisible(false);
StackPane accessIndicator = new StackPane();
accessIndicator.getChildren().addAll(deniedIcon, grantedIcon);
accessIndicator.setAlignment(Pos.CENTER_RIGHT);
grantedIcon.visibleProperty().bind(GRANTED_ACCESS);
// second row
HBox row2 = new HBox(3);
row2.getChildren().addAll(passwordField, accessIndicator);
HBox.setHgrow(accessIndicator, Priority.ALWAYS);
// user hits the enter key
passwordField.setOnAction(actionEvent -> {
if (GRANTED_ACCESS.get()) {
System.out.printf("User %s is granted access.\n", user.getUserName());
System.out.printf("User %s entered the password: %s\n", user.getUserName(), user.getPassword());
Platform.exit();
} else {
deniedIcon.setVisible(true);
}
ATTEMPTS.set(ATTEMPTS.add(1).get());
System.out.println("Attempts: " + ATTEMPTS.get());
});
// listener when the user types into the password field
passwordField.textProperty().addListener((obs, ov, nv) -> {
boolean granted = passwordField.getText().equals(MY_PASS);
GRANTED_ACCESS.set(granted);
if (granted) {
deniedIcon.setVisible(false);
}
});
// listener on number of attempts
ATTEMPTS.addListener((obs, ov, nv) -> {
if (MAX_ATTEMPTS == nv.intValue()) {
// failed attemps
System.out.printf("User %s is denied access.\n", user.getUserName());
Platform.exit();
}
});
VBox formLayout = new VBox(4);
formLayout.getChildren().addAll(row1, row2);
formLayout.setLayoutX(12);
formLayout.setLayoutY(12);
root.getChildren().addAll(background, formLayout);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I don't quite understand these two listeners:
// listener when the user types into the password field
passwordField.textProperty().addListener((obs, ov, nv) -> {
boolean granted = passwordField.getText().equals(MY_PASS);
GRANTED_ACCESS.set(granted);
if (granted) {
deniedIcon.setVisible(false);
}
});
// listener on number of attempts
ATTEMPTS.addListener((obs, ov, nv) -> {
if (MAX_ATTEMPTS == nv.intValue()) {
// failed attemps
System.out.printf("User %s is denied access.\n", user.getUserName());
Platform.exit();
}
});
In the first listener none of obs, ov or nv are used, in the second, only nv is used. What are obs, ov and nv exactly here?
A:
https://docs.oracle.com/javafx/2/api/javafx/beans/value/ChangeListener.html
changed(ObservableValue<? extends T> observable, T oldValue, T newValue)
It's because when using lambdas you don't have to provide the types. If you're keyboarding it out manually, then it's easier to use obs, ov, nv. In just about any changeListener I've written, I only usually access the newValue - nv.
The code example could be changed
boolean granted = passwordField.getText().equals(MY_PASS);
could be
boolean granted = nv.equals(MY_PASS);
| {
"pile_set_name": "StackExchange"
} |
Q:
how to use multiple or_where on same field in codeigniter
I need to run a query with conditions of where and or_where on the same field using codeigniter. There are where operations performed other fields to. The code,
function get_newTapal($off, $status)
{
$p = $this->db->select('*')
->from('tbl_tapal')
->join('tbl_subjectmain', 'tbl_subjectmain.Msub_Cd = tbl_tapal.Tmain_sub')
->join('tbl_subject_all', 'tbl_subject_all.Sub_Cd = tbl_tapal.Tsub_sub')
->join('tbl_seat', 'tbl_seat.SeatCd = tbl_tapal.Tseat')
->where('tbl_tapal.Tstatus', $status)
->where('tbl_tapal.Toffice_id', $off)
->where('tbl_tapal.Tmain_sub !=', 1)
->where('tbl_tapal.Tsub_sub !=', 2)
->or_where('tbl_tapal.Tstatus', 2)
;
$query = $p->get();
$new_tapal=$query->result();
foreach($new_tapal as $row){ echo $row->Toffice_id.'/'.$row->Tapal_no.'/'.$row->Tyear.'<br>'; }
}
When i run the query without the or_where condition it woks properly according to the code. I need the rows which satisfies all where conditions where the status value is either '1' or '2'. But when i add the or_where condition it doesn't check the other conditions at that part of query. i.e, The query returns rows satisfying first 4 where conditions together plus the rows which satisfies just the or_where condition.
Could someone help me about that?
A:
You can use $this->db->or_where_in() for checking the multiple or condition in where.
Ex:
$status= array('1', '2', '3');
$this->db->or_where_in('tbl_tapal.Tstatus', $status);
| {
"pile_set_name": "StackExchange"
} |
Q:
issue when trying to move a div up and down
i'm trying to move the div with class player top and down when i click on the arrow keys using this code :
JavaScript
var playerPosition = 0;
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if(key = 38) {
playerPosition += 10;
} else if(key = 40) {
playerPosition -= 10;
}
var players = document.getElementsByClassName('player');
for(var i = 0; i < players.length; i++)
players[i].style.marginTop = playerPosition+"px";
}
the problem is when i hit any key the div goes down !
http://jsfiddle.net/b5eaey58/
2nd problem that the movement of the div isn't smooth
A:
you're calling the wrong operator, you're trying to evaluate = instead of ===. (FYI You may have the keys reversed unless you want the div to go up when you press down) For it being not smooth it's because you're firing the function onkeyup which means the user has to release the key before the movement triggers. Use onkeydown instead so the user can hold down the key and make it run smoother:
FIDDLE
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retrieve the 'last sync' time for an account?
Is it possible to retrieve the time an account was last synchronized, like the system Settings->Accounts&Sync app does? I'm using Android 2.2.
Looking at the 2.2 source for AccountSyncSettings.java, I see the status is retrieved using:
SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority);
but SyncStatusInfo and getSyncStatus don't seem to be part of the public API (marked with @hide). Is there some other way to get at this info?
A:
You can use reflection to achieve this purpose.Here is my code to implement this
private long getLasySyncTime() {
long result = 0;
try {
Method getSyncStatus = ContentResolver.class.getMethod(
"getSyncStatus", Account.class, String.class);
if (mAccount != null && mSyncAdapter != null) {
Object status = getSyncStatus.invoke(null, mAccount,
mSyncAdapter.authority);
Class<?> statusClass = Class
.forName("android.content.SyncStatusInfo");
boolean isStatusObject = statusClass.isInstance(status);
if (isStatusObject) {
Field successTime = statusClass.getField("lastSuccessTime");
result = successTime.getLong(status);
TLog.d(WeixinSetting.class, "get last sync time %d", result);
}
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
TLog.d(WeixinSetting.class, e.getMessage() + e.getCause().getMessage());
} catch (IllegalArgumentException e) {
} catch (ClassNotFoundException e) {
} catch (NoSuchFieldException e) {
} catch (NullPointerException e) {
}
return result;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
frielndy url with GET form
Im trying to make friendly url form my search result
right now my form look like this
<form action="/index.php" method=get id="wyszukaj">
<input type="hidden" name=metoda value=search>
<input type=text id="project" name=nazwa size=10 placeholder="Wpisz nazwę szukanej rośliny" />
<input type="hidden" id="project-id" />
<a id="loop-icon" onclick="wyszukaj_submit();"></a>
</form>
When I type "borowka" and hit search button, page shows link:
index.php?metoda=szukaj&nazwa=borowka
But I want to produce link like that /search/borowka
How can I do that?
A addes this line to htaccess
RewriteRule ^search/([^/\.]+)$ index.php?metoda=search&nazwa=$1
and if I type /search/borowka direct in address bar, it work fine
I cant firure out redirect to /search/borowka from htaccess
Anybody can help me with that?
A:
You may need to tweak this a little depending on how you want to handle or translate szukaj to search... not sure if you intend metda to be fixed value or dynamic, but try the following:
RewriteCond %{THE_REQUEST} /index\.php\?metoda=(?:[^&\s]+)&nazwa=([^\s&]+) [NC]
RewriteRule ^(.+)$ /search/%1? [R,L]
RewriteRule ^search/([^/\.]+)$ index.php?metoda=search&nazwa=$1 [L]
| {
"pile_set_name": "StackExchange"
} |
Q:
What does overriding virtual function differs only by calling convention mean?
I am trying to implement IUnknown. I followed the instruction to the tee but it isn't working. When I try to compile I get:
Error 2 error C2695: 'testInterfaceImplementation::AddRef': overriding virtual function differs from 'IUnknown::AddRef' only by calling convention c:\users\seanm\desktop\test\test\source.cpp 6 1 test
Error 3 error C2695: 'testInterfaceImplementation::QueryInterface': overriding virtual function differs from 'IUnknown::QueryInterface' only by calling convention c:\users\seanm\desktop\test\test\source.cpp 14 1 test
Error 4 error C2695: 'testInterfaceImplementation::Release': overriding virtual function differs from 'IUnknown::Release' only by calling convention c:\users\seanm\desktop\test\test\source.cpp 22 1 test
from this code:
#include <Windows.h>
#include <tchar.h>
class testInterfaceImplementation : public IUnknown {
protected:
ULONG AddRef()
{
MessageBox(NULL,
_T("TEST1"),
_T("TEST1"),
NULL);
return 0;
}
HRESULT QueryInterface(IN REFIID riid, OUT void **ppvObject)
{
MessageBox(NULL,
_T("TEST2"),
_T("TEST2"),
NULL);
return S_OK;
}
ULONG Release() {
MessageBox(NULL,
_T("TEST3"),
_T("TEST3"),
NULL);
return 0;
}
};
A:
Add STDMETHODCALLTYPE for each of the methods.
ULONG STDMETHODCALLTYPE AddRef()
HRESULT STDMETHODCALLTYPE QueryInterface(IN REFIID riid, OUT void **ppvObject)
ULONG STDMETHODCALLTYPE Release()
The base class(IUnknown) methods are declared as STDMETHODCALLTYPE (which is a macro for __stdcall). When you override a virtual method, it has to have the same calling convention as the original which in this case is __stdcall
| {
"pile_set_name": "StackExchange"
} |
Q:
EBA Stress Test Arbitrage
The EBA stress test defines specific shocks to yield curves that are applied to positions as at year end. There is no account for cashflows - it is simply an immediate shock.
Suppose the interest rate shock was 50 bps which is a reasonably large value for some interest rate markets, then the purchase of a 50bps wide strangle with an expiry that is soon after the year end would cost very little, yet it might entirely hedge 25bps of the shock in either direction.
Whilst I am sure that regulators would disapprove of the direct specificity of this trade, my question is whether anyone has any experience with similar structured products, in terms of regulatory hedges and if they are indeed permitted?
A:
I would not be surprised that you can perform some regulatory arbitrage by mean of little financial engineering as you suggest, see for example: https://www.risk.net/our-take/7046041/in-stress-test-window-dressing-timing-is-everything.
In principle, why wouldn't you be allowed to take such a market position? It is a default of the regulatory approach. In the above linked articles, it is said that regulators try to prevent this problem by specifying a "random" window for stress tests a posteriori.
Note however that the picture might change with increased and periodical regulatory oversight such as with the Fundamental Review of Trading Book.
My guess is that these issues are indeed existing with any regulation that takes the balance sheet at a specific date. You could also look for example at Solvency II on the insurance side.
As a financial institution, you are taking a serious risks by doing such arbitrage:
- What happens if the regulation changes rapidly and you are not able to do the trick anymore and you end up with inadequate capital?
- What happends if the same cheap regulatory hedge is no longer that cheap later on and you end up with inadequate capital? (I am more familiar with insurance where your balance sheet can't change that rapidly)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Turn Multiple Union Statements into a Single Row in SQL Server
How would I turn this query into a single row with different column names.
Select count(distinct accountid) as x
from table1
where active = 1
and expiredate >= GetDate()
and acceptedon is not null
union
Select count(distinct accountid) as x
from table1
where active = 1
and expiredate <= GetDate()
and acceptedon is not null
I get
x
5
4
I would like
x y
5 4
A:
You want simple conditional aggregation :
Select count(distinct case when expiredate >= GetDate() then accountid end) as x,
count(distinct case when expiredate <= GetDate() then accountid end) as y
from table1
where active = 1 and acceptedon is not null;
| {
"pile_set_name": "StackExchange"
} |
Q:
Token based authentication in Play filter & passing objects along
I've written an API based on Play with Scala and I'm quite happy with the results. I'm in a stage where I'm looking at optimising and refactoring the code for the next version of the API and I had a few questions, the most pressing of which is authentication and the way I manage authentication.
The product I've written deals with businesses, so exposing Username + Password with each request, or maintaining sessions on the server side weren't the best options. So here's how authentication works for my application:
User authenticates with username/password.
Server returns a token associated with the user (stored as a column in the user table)
Each request made to the server from that point must contain a token.
Token is changed when a user logs out, and also periodically.
Now, my implementation of this is quite straightforward – I have several forms for all the API endpoints, each one of which expects a token against which it looks up the user and then evaluates if the user is allowed to make the change in the request, or get the data. So each of the forms in the authenticated realm are forms that need a token, and then several other parameters depending on the API endpoint.
What this causes is repetition. Each one of the forms that I'm using has to have a verification part based on the token. And its obviously not the briefest way to go about it. I keep needing to replicate the same kind of code over and over again.
I've been reading up about Play filters and have a few questions:
Is token based authentication using Play filters a good idea?
Can a filter not be applied for a certain request path?
If I look up a user based on the supplied token in a filter, can the looked up user object be passed on to the action so that we don't end up repeating the lookup for that request? (see example of how I'm approaching this situation.)
case class ItemDelete(usrToken: String, id: Long) {
var usr: User = null
var item: Item = null
}
val itemDeleteForm = Form(
mapping(
"token" -> nonEmptyText,
"id" -> longNumber
) (ItemDelete.apply)(ItemDelete.unapply)
verifying("unauthorized",
del => {
del.usr = User.authenticateByToken(del.usrToken)
del.usr match {
case null => false
case _ => true
}
}
)
verifying("no such item",
del => {
if (del.usr == null) false
Item.find.where
.eq("id", del.id)
.eq("companyId", del.usr.companyId) // reusing the 'usr' object, avoiding multiple db lookups
.findList.toList match {
case Nil => false
case List(item, _*) => {
del.item = item
true
}
}
}
)
)
A:
Take a look at Action Composition, it allows you to inspect and transform a request on an action. If you use a Play Filter then it will be run on EVERY request made.
For example you can make a TokenAction which inspects the request and if a token has been found then refine the request to include the information based on the token, for example the user. And if no token has been found then return another result, like Unauthorized, Redirect or Forbidden.
I made a SessionRequest which has a user property with the optionally logged in user, it first looks up an existing session from the database and then takes the attached user and passes it to the request
A filter (WithUser) will then intercept the SessionRequest, if no user is available then redirect the user to the login page
// Request which optionally has a user
class SessionRequest[A](val user: Option[User], request: Request[A]) extends WrappedRequest[A](request)
object SessionAction extends ActionBuilder[SessionRequest] with ActionTransformer[Request, SessionRequest] {
def transform[A](request: Request[A]): Future[SessionRequest[A]] = Future.successful {
val optionalJsonRequest: Option[Request[AnyContent]] = request match {
case r: Request[AnyContent] => Some(r)
case _ => None
}
val result = {
// Check if token is in JSON request
for {
jsonRequest <- optionalJsonRequest
json <- jsonRequest.body.asJson
sessionToken <- (json \ "auth" \ "session").asOpt[String]
session <- SessionRepository.findByToken(sessionToken)
} yield session
} orElse {
// Else check if the token is in a cookie
for {
cookie <- request.cookies.get("sessionid")
sessionToken = cookie.value
session <- SessionRepository.findByToken(sessionToken)
} yield session
} orElse {
// Else check if its added in the header
for {
header <- request.headers.get("sessionid")
session <- SessionRepository.findByToken(header)
} yield session
}
result.map(x => new SessionRequest(x.user, request)).getOrElse(new SessionRequest(None, request))
}
}
// Redirect the request if there is no user attached to the request
object WithUser extends ActionFilter[SessionRequest] {
def filter[A](request: SessionRequest[A]): Future[Option[Result]] = Future.successful {
request.user.map(x => None).getOrElse(Some(Redirect("http://website/loginpage")))
}
}
You can then use it on a action
def index = (SessionAction andThen WithUser) { request =>
val user = request.user
Ok("Hello " + user.name)
}
I hope this will give you an idea on how to use Action Composition
| {
"pile_set_name": "StackExchange"
} |
Q:
How to configure firewall on user defined Docker bridge?
I created a user-defined bridge using the docker command:
docker network create --driver bridge mynetwork
This command resulted in a bridge being created, as shown by netstat -i:
Iface MTU RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg
br-000f1 1500 0 0 0 0 0 0 0 0 BMRU
In the same way that I previously trusted the docker0 bridge, I need to add this new bridge to my firewall trust zone:
firewall-cmd --permanent --zone=trusted --add-interface=Docker0
I don't see a way to infer or specify the bridge device name, so I'm not sure how I can add it to my trust zone in an automated way.
I would appreciate any help.
A:
Elaborating on Marek's Answer of setting the bridge name at creation time.
docker network create --driver bridge -o \
"com.docker.network.bridge.name"="mynetwork_name" mynetwork
or if using a docker-compose file the following in the networks section
version: '3'
.
.
.
networks:
mynetwork:
driver_opts:
com.docker.network.bridge.name: mynetwork_name
| {
"pile_set_name": "StackExchange"
} |
Q:
Bulk change in database through the rails console
I got a User model, where a user can be Gold or not (it's a boolean).
I would like to update specific users (more than 500) from Gold: false to Gold: true thanks to their user_id
How can I do it through the rails console ?
Thanks
A:
Easiest way is to use #update_all. If you have the ids:
User.where(id: ids).update_all(gold: true)
It's fast as it sends a single SQL command to db and doesn't invoke validation or callbacks.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the major differences between the different versions of the PS3?
Recently, I've preordered myself a PS3 game. Now I think it's a good time for me to purchase a PS3 to play it on! Now, I was going to go with what I assumed to be a normal setup, but then I was told about a sale on a "Slim" version, which seemed like a good deal. But I imagine that in being Slim, it has some corners cut, so there's going to be differences.
What are the actual differences between the different versions of the PS3? And how many are there, anyway?
A:
Actually the only version being produced is the slim version ... you won't find a new -fat- version anymore... (unless someone sells them like diamonds).
Anyways.
The difference among the new models (slim ones) is based in their hard drive size. The actual versions are 120Gb and 250Gb ... but beware, this month Sony Japan will release new Slim versions in white color with higher high drives ... !!!
You can read further information on technical differences here: http://en.wikipedia.org/wiki/PS3#Model_comparison
A:
The Playstation 3 Wikipedia article has a pretty good breakdown of all the different models and their capabilities.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this query safe to use? Prepared statement?
Is this query safe to use? I'm not sure how I'd convert it to a prepared statement as it's not using any values from the user:
$result = mysqli_query($cxn, "SELECT * FROM table WHERE datetime > DATE_SUB(NOW(), INTERVAL 15 DAY) ORDER BY RAND() LIMIT 1");
while ($row = mysqli_fetch_array($result)) {
$title = $row['title'];
echo $title;
}
Is this safe to use? How can I improve it?
Thanks.
A:
Yes, it's safe. There is no user input used there at all; nothing that has the potential to mess up the query syntax or manipulate the outcome in any way.
As for improvements, there is no need to return every field in the table if you are only using the title field. In general, you should avoid the wild-card (*) for SELECT queries, except for testing purposes.
Also, the DATE_SUB(NOW(), INTERVAL 15 DAY) can be reduced to just NOW() - INTERVAL 15 DAY. Shorter and sweeter; no unnecessary function calls.
| {
"pile_set_name": "StackExchange"
} |
Q:
Class 'ZipArchive' not found in Laravel phpword
I have installed phpword package in my laravel project. Now when I try to read a docx file using this code
public function upload(Request $request){
$file = $request->file('file');
$phpWord = \PhpOffice\PhpWord\IOFactory::load($file);
foreach($phpWord->getSections() as $section) {
foreach($section->getElements() as $element) {
if(method_exists($element,'getText')) {
echo $element->getText() . "<br>";
}
}
}
}
I am getting an error
Class 'ZipArchive' not found
/vendor/phpoffice/common/src/Common/XMLReader.php line no 54
zip already installed in my php.
A:
Please run command for cache clear and dump-autoload like php artisan config:cache and composer dump-autoload
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I hide the window when I run a exe
I have this
static std::string exec(char* cmd) {
FILE* pipe = _popen(cmd, "r");
if (!pipe) return "ERROR -22";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
_pclose(pipe);
return result;
}
But the problem i have is that i want to hide the program that lunches how can I do that? thx
A:
As Hans Passant mentioned in the comments, you have to use CreateProcess to spawn the child process instead of _popen, since _popen does not give you any control over the window creation process.
To hide the console window, use the CREATE_NO_WINDOW process creation flag for the dwCreationFlags parameter.
In order to capture the output of the process, you need to create a pipe for its standard output stream with CreatePipe. Assign that pipe handle to the hStdOutput member of the STARTUPINFO structure you pass in, and make sure to set the STARTF_USESTDHANDLES flag in the startup info's dwFlags so it knows that that member is valid. Then, to read data, you just use ReadFile on the pipe handle.
Hans also provided a link to a good example of creating pipes with a child process here, although that example is doing more than you need to do—it's creating pipes for all three streams (stdin, stdout, and stderr), whereas you only need to capture stdout.
| {
"pile_set_name": "StackExchange"
} |
Q:
Exception in Spring Integration - Multiple channels defined on declaring a channel bean
I'm a newbie to spring integration and I'm using the following code,
package services.api;
public interface GreetingService {
public void greetUsers(String userName);
}
package services.impl;
import services.api.GreetingService;
public class GreetServiceImpl implements GreetingService {
@Override
public void greetUsers(String userName) {
if (userName != null && userName.trim().length() > 0) {
System.out.println("Hello " + userName);
}
}
}
package main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.support.MessageBuilder;
public class Main {
public static void main(String[] args)
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
MessageChannel messageChannel = applicationContext.getBean(MessageChannel.class);
Message<String> message = MessageBuilder.withPayload("World").build();
messageChannel.send(message);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://springframework.org/schema/integration http://springframework.org/schema/integration/spring-integration.xsd">
<channel id="pushChannel" />
<service-activator input-channel="pushChannel" ref="service"
method="greetUsers" />
<beans:bean id="service" class="services.impl.GreetServiceImpl" />
</beans:beans>
I'm getting the following error, eventhough I've declared only one message channel
Mar 04, 2014 4:46:23 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@34d0cdd0: startup date [Tue Mar 04 16:46:23 IST 2014]; root of context hierarchy
Mar 04, 2014 4:46:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Mar 04, 2014 4:46:23 PM org.springframework.beans.factory.config.PropertiesFactoryBean loadProperties
INFO: Loading properties file from URL [jar:file:/D:/Personal%20Data/Softwares/spring-framework-4.0.0.RELEASE-dist/SpringIntegration/spring-integration-3.0.0.RELEASE-dist/spring-integration-3.0.0.RELEASE/libs/spring-integration-core-3.0.0.RELEASE.jar!/META-INF/spring.integration.default.properties]
Mar 04, 2014 4:46:23 PM org.springframework.integration.config.xml.IntegrationNamespaceHandler registerHeaderChannelRegistry
INFO: No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
Mar 04, 2014 4:46:23 PM org.springframework.integration.config.xml.DefaultConfiguringBeanFactoryPostProcessor registerErrorChannel
INFO: No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
Mar 04, 2014 4:46:23 PM org.springframework.integration.config.xml.DefaultConfiguringBeanFactoryPostProcessor registerTaskScheduler
INFO: No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
Mar 04, 2014 4:46:23 PM org.springframework.beans.factory.config.PropertiesFactoryBean loadProperties
INFO: Loading properties file from URL [jar:file:/D:/Personal%20Data/Softwares/spring-framework-4.0.0.RELEASE-dist/SpringIntegration/spring-integration-3.0.0.RELEASE-dist/spring-integration-3.0.0.RELEASE/libs/spring-integration-core-3.0.0.RELEASE.jar!/META-INF/spring.integration.default.properties]
Mar 04, 2014 4:46:23 PM org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler initialize
INFO: Initializing ExecutorService 'taskScheduler'
Mar 04, 2014 4:46:23 PM org.springframework.context.support.DefaultLifecycleProcessor start
INFO: Starting beans in phase -2147483648
Mar 04, 2014 4:46:23 PM org.springframework.integration.endpoint.EventDrivenConsumer logComponentSubscriptionEvent
INFO: Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
Mar 04, 2014 4:46:23 PM org.springframework.integration.channel.PublishSubscribeChannel adjustCounterIfNecessary
INFO: Channel 'org.springframework.context.support.ClassPathXmlApplicationContext@34d0cdd0.errorChannel' has 1 subscriber(s).
Mar 04, 2014 4:46:23 PM org.springframework.integration.endpoint.EventDrivenConsumer start
INFO: started _org.springframework.integration.errorLogger
Mar 04, 2014 4:46:23 PM org.springframework.context.support.DefaultLifecycleProcessor start
INFO: Starting beans in phase 0
Mar 04, 2014 4:46:23 PM org.springframework.integration.endpoint.EventDrivenConsumer logComponentSubscriptionEvent
INFO: Adding {service-activator} as a subscriber to the 'pushChannel' channel
Mar 04, 2014 4:46:23 PM org.springframework.integration.channel.DirectChannel adjustCounterIfNecessary
INFO: Channel 'org.springframework.context.support.ClassPathXmlApplicationContext@34d0cdd0.pushChannel' has 1 subscriber(s).
Mar 04, 2014 4:46:23 PM org.springframework.integration.endpoint.EventDrivenConsumer start
INFO: started org.springframework.integration.config.ConsumerEndpointFactoryBean#0
Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.integration.MessageChannel] is defined: expected single matching bean but found 3: pushChannel,nullChannel,errorChannel
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:312)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:985)
at main.Main.main(Main.java:17)
A:
I suggest you to read more Docs:
http://docs.spring.io/spring-integration/docs/3.0.1.RELEASE/reference/html
http://www.manning.com/fisher
As you see the framework provides two explicit channels: nullChannel, errorChannel.
And they aren't the last beans which are populated by framework.
To fix your issue just provide the id of your channel to applicationContext.getBean
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP- find which names in variable appear in page
I've spent countless days trying to figure this out... I have a list of names I want to check for on my page. How can I check for these in a string. The last thing I tried was str_word_count
$members = "anne, barb, max"
print_r(str_word_count($members, 1));
Obviously that just returns an array of the $members variable. I want to check for the variables in my file and return which names were found.
I know this is probably a super easy question but, as my username suggests, I am a SuperN00b.
A:
index.php
$data = file_get_contents('page.php');
$names = ['simon', 'jeff'];
foreach($names as $name)
{
if(strpos($data, $name))
{
echo $name . " Is in file! <br>";
}
}
page.php
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
anna barry simon puma george jessica michael
jamil adil john jeff
</body>
</html>
Output of this specific code
simon Is in file!
jeff Is in file!
Is this along the lines of what you were looking for?
| {
"pile_set_name": "StackExchange"
} |
Q:
PowerShell tab separated file contents import
I have a requirement to import a tab separated file without any headers. I am looking for the best way to achieve this as I am currently only familiar with comma-separated imports with headers. The file to import will be named datafile.out
I have tried the below, but I am unable to access a single value from a row by using $contents[3]; this will get the forth row. I want to get the value after each tab separation:
$contents = Add-Content $file -delimted "'t"
A:
It's not really clear what you are asking, but if you are trying to import a tab-separated file that doesn't have a header line, then you could do it like this:
$contents = Import-Csv SomeFile.txt -Delimiter "`t" -Header ColumnName1,ColumnName2,ColumnName3
Change the column names in the -Header switch as necessary.
| {
"pile_set_name": "StackExchange"
} |
Q:
Merge dll's with Costura, Microsoft.Data.Sqlite throws errors and cannot add-migrations etc
I have a project with at least 50 dll's. And I don't what them in the root folder with .exe of application. I am using Fody/Costura to solve this problem.
But... I want to rewrite the entire database to the sqlite. Something that end-user doesn't need to configure and what would be an easy solution for me.
But when is the Costura turned on it cannot allow me instance.Database.Migrate() and a lot of other commands.
https://gyazo.com/4c2adaf6d279c562cee44b096f123ae5
And when I remove that context with from the App.xaml.cs and try to add-migration it writes:
Your startup project 'x' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.
When I turn off Costura everything works. But the dll's are in the root folder :(
So...
Is there any way how to hide the dlls and have sqlite database in a project?
Or is there any other alternative to the serverless database? What works with Costura?
I have no problem with some dll's in the root folder but don't want them 50.
EDIT:
When I call it as the embedded resource the same problem as in the picture.
EmbeddedAssembly.Load("Project.Microsoft.Data.Sqlite.dll", "Microsoft.Data.Sqlite.dll");
A:
duplicated: Using Fody Costura with Entity Framework Core migrations
quote from the thread:
Thanks to Tronald for putting me on the right track. For anyone else who comes across this, for me the trick was to exclude all the SQLitePCLRaw DLLs like this:
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<Costura >
<ExcludeAssemblies>
SQLitePCLRaw.*
</ExcludeAssemblies>
</Costura>
</Weavers>
This solution works on Migrate(), but doesn't work on add-migration xxx It s a little problem... I just uninstall fody every time when I create a new migration. And then install it again.
If I don't uninstall Fody then add-migration writes:
Your startup project 'InstaGTO' doesn't reference
Microsoft.EntityFrameworkCore.Design. This package is required for the
Entity Framework Core Tools to work. Ensure your startup project is
correct, install the package, and try again.
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding an affine transformation
I am trying to implement a modified version of sift tracking.
I found a matlab implementation of sift to track objects in which, basically, they take the indices of the matches and compute the following transform:
pts = [x;y]'; % pts contains the points x and their transform y
pt1 = [point,ones(size(pts,1),2),ones(size(pts,1),2)];
pt2 = [ones(size(pts,1),2),pts,ones(size(pts,1),2)];
m1= [1,0,0,0,0,0;0,1,0,0,0,0;0,0,0,0,0,0;0,0,0,0,0,0;0,0,0,0,1,0;0,0,0,0,0,0];
m2= [0,0,0,0,0,0;0,0,0,0,0,0;0,0,1,0,0,0;0,0,0,1,0,0;0,0,0,0,0,0;0,0,0,0,0,1];
t1=pt1*m1;
t2=pt2*m2;
A = reshape([t1(:) t2(:)]',size(t1,1)+size(t2,1), []);
b = reshape(npoint(:),2*size(npoint,2),1); % npoints are the indices of the points
transformation = inv(A'*A)*A'*b
I don't understand how the transform is computed nor what is represents.
Has anyone an idea on this?
A:
inv(A'*A)*A'*b looks like a least squares approximation. You can approximate
$$ A\cdot x \approx b $$
by solving
$$ \left(A^T\cdot A\right)\cdot x = A^T\cdot b $$
which can be solved for $x$ as
$$ x = \left(A^T\cdot A\right)^{-1}\cdot A^T\cdot b $$
You can also fiond this forumla in the section Model verification by linear least squares in the Wikipedia article on SIFT.
Let's also translate these matrices into math notation:
$$
M_1= \begin{bmatrix}
1&0&0&0&0&0\\
0&1&0&0&0&0\\
0&0&0&0&0&0\\
0&0&0&0&0&0\\
0&0&0&0&1&0\\
0&0&0&0&0&0
\end{bmatrix}
\qquad
M_2= \begin{bmatrix}
0&0&0&0&0&0\\
0&0&0&0&0&0\\
0&0&1&0&0&0\\
0&0&0&1&0&0\\
0&0&0&0&0&0\\
0&0&0&0&0&1
\end{bmatrix}
$$
The matrices pt1 and pt2 seem to look something like this:
$$
\textit{pt}_1 = \begin{bmatrix}
x_1 & y_1 & 1 & 1 & 1 & 1 \\
x_2 & y_2 & 1 & 1 & 1 & 1 \\
\vdots & & & & & \vdots \\
x_n & y_n & 1 & 1 & 1 & 1
\end{bmatrix}
\qquad
\textit{pt}_2 = \begin{bmatrix}
1 & 1 & x_1 & y_1 & 1 & 1 \\
1 & 1 & x_2 & y_2 & 1 & 1 \\
\vdots & & & & & \vdots \\
1 & 1 & x_n & y_n & 1 & 1
\end{bmatrix}
$$
The above formulation disregards the difference between pointand pts. Multiplying those $M$ matrices from the right sets certain columns to zero, so you end up with
$$
t_1 = \begin{bmatrix}
x_1 & y_1 & 0 & 0 & 1 & 0 \\
x_2 & y_2 & 0 & 0 & 1 & 0 \\
\vdots & & & & & \vdots \\
x_n & y_n & 0 & 0 & 1 & 0
\end{bmatrix}
\qquad
t_2 = \begin{bmatrix}
0 & 0 & x_1 & y_1 & 0 & 1 \\
0 & 0 & x_2 & y_2 & 0 & 1 \\
\vdots & & & & & \vdots \\
0 & 0 & x_n & y_n & 0 & 1
\end{bmatrix}
$$
The reshape then stacks these matrices.
$$
A = \begin{bmatrix}
x_1 & y_1 & 0 & 0 & 1 & 0 \\
x_2 & y_2 & 0 & 0 & 1 & 0 \\
\vdots & & & & & \vdots \\
x_n & y_n & 0 & 0 & 1 & 0 \\
0 & 0 & x_1 & y_1 & 0 & 1 \\
0 & 0 & x_2 & y_2 & 0 & 1 \\
\vdots & & & & & \vdots \\
0 & 0 & x_n & y_n & 0 & 1
\end{bmatrix}
$$
These are the same lines you also find in the Wikipedia article, although Wikipedia has them interleaved, so they are in a different order.
Now the right side is built from npoint. Despite the comment, I assume that this is not point indices, but instead the new positions of the points, after the transformation was applied. Wikipedia calls this $u$ and $v$. So you have
$$
b = \begin{bmatrix}
u_1 \\
u_2 \\
\vdots \\
u_n \\
v_1 \\
v_2 \\
\vdots \\
v_n
\end{bmatrix}
$$
So what you are doing is you are solving the following least squares approximation problem:
$$
\begin{bmatrix}
x_1 & y_1 & 0 & 0 & 1 & 0 \\
x_2 & y_2 & 0 & 0 & 1 & 0 \\
\vdots & & & & & \vdots \\
x_n & y_n & 0 & 0 & 1 & 0 \\
0 & 0 & x_1 & y_1 & 0 & 1 \\
0 & 0 & x_2 & y_2 & 0 & 1 \\
\vdots & & & & & \vdots \\
0 & 0 & x_n & y_n & 0 & 1
\end{bmatrix}
\cdot
\begin{bmatrix}
m_1 \\ m_2 \\ m_3 \\ m_4 \\ t_x \\ t_y
\end{bmatrix}
\approx
\begin{bmatrix}
u_1 \\
u_2 \\
\vdots \\
u_n \\
v_1 \\
v_2 \\
\vdots \\
v_n
\end{bmatrix}
$$
which is just another way of writing
$$
\begin{bmatrix}m_1 & m_2 \\ m_3 & m_4\end{bmatrix}
\cdot\begin{bmatrix}x_i \\ y_i\end{bmatrix}
+\begin{bmatrix}t_x \\ t_y\end{bmatrix}
\approx\begin{bmatrix}u_i \\ v_i\end{bmatrix}
$$
So in the end, your transformation will be a vector of six elements, namely $(m_1, m_2, m_3, m_4, t_x, t_y)$, which define the affine transformation
$$
\begin{bmatrix}x \\ y\end{bmatrix} \mapsto
\begin{bmatrix}m_1 & m_2 \\ m_3 & m_4\end{bmatrix}
\cdot\begin{bmatrix}x \\ y\end{bmatrix}
+\begin{bmatrix}t_x \\ t_y\end{bmatrix}
$$
Note that I wouldn't program things that way. I'd rather treat this as two systems of equations, since rows related to $u$ don't influence those related to $v$. So I'd write something like
$$
\begin{bmatrix}
x_1 & y_1 & 1 \\
x_2 & y_2 & 1 \\
\vdots & & \vdots \\
x_n & y_n & 1
\end{bmatrix}
\cdot
\begin{bmatrix}
m_1 & m_3 \\
m_2 & m_4 \\
t_x & t_y
\end{bmatrix}
\approx
\begin{bmatrix}
u_1 & v_1 \\
u_2 & v_2 \\
\vdots & \vdots \\
u_n & v_n
\end{bmatrix}
$$
This should translate into matlab like this:
pts = [x;y]';
A = [pts, ones(size(pts,1),1)];
transformation = (inv(A'*A)*A'*npoint)'
| {
"pile_set_name": "StackExchange"
} |
Q:
Recovering data lost in Google Apps transition
I use Google Apps for my domain. Until recently, I was required to sustain a Google Account separate from my Google Apps Account for products like Reader or Analytics. This changed when Google began a consolidation of such split accounts, ostensibly merging Account data into Apps Account Data. I have so called "conflicting" Accounts owing to my use of the same email address for both Accounts.
On forced transition day, however, I lost the data associated with my Reader and Analytics account. Both are now empty. Google's help forums have not been helpful. Moreover, the support documentation asserts that I should have:
been presented with a conflict resolution page, allowing me to change the account name on the non-Apps Account
been able to successfully consolidate data into the Apps Account.
Neither proved true. I am unable to login to my old Account and cannot rescue the Reader data meticulously collected over several years. Presumably Google still holds the data I so desire to export, but I cannot attract the attention of staff so that I might get my data.
What are my options?
A:
It might be a long shot, but try Twitter. I was able to get the attention of the right authorities which lead to a speedy resolution—they were different companies.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spark 2.3.1 on YARN : how to monitor stages progress programatically?
I have a setup with Spark running on YARN, and my goal is to programmatically get updates of the progress of a Spark job by its application id.
My first idea was to parse HTML output of the YARN GUI. However, the problem of such GUI, is that the progress bar associated to a spark job don't get updated regularly and even don't change most of time : when the job start, the percent is something like 10%, and it stuck to this value until the job finish. So such YARN progress bar is just irrelevant for Spark Jobs.
When I click to the Application Master link corresponding to a Spark Job, I'm redirected to the Spark GUI that is temporarily binded during the job run. The stages page is very relevant about progress of the Spark job. However it is plain HTML, so it is a pain to parse. On the Spark documentation, they talk about a JSON API, however it seems that I can't access to it as I'm under YARN and I'm accessing Spark GUI trough YARN proxy pages.
May be a solution, in order to have access to more things, could be to access to the real Spark GUI ip:port, and not the YARN proxied one, but I don't know if I can get such source URL easily...
All of that sound complicated to just get Spark job progress... As of 2018, could you please tell us what are the preferred methods to get relevant stages progress of a Spark Job running on YARN ?
A:
From within the application itself, you can get informations on stage progress by using spark.sparkContext.statusTracker, you can look how e.g. Zeppelin Notebook implemented a progress bar for Spark 2.3: https://github.com/apache/zeppelin/blob/master/spark/spark-scala-parent/src/main/scala/org/apache/zeppelin/spark/JobProgressUtil.scala
| {
"pile_set_name": "StackExchange"
} |
Q:
Debug Assertion Failed! (string subscript out of range)
OK. So I am making a simple program to experiment with strings, and during one portion of the program, a for loop displays each letter of the string in order, vertically. I ran the program normally to check on its progress throughout coding, however when I put this in, the error occurred. Here is my code:
int main()
{
std::string word1 = "Chicken";
std::string word2("Nuggets");
std::string word3(3, '!');
std::string phrase = word1 + " " + word2 + word3;
std::cout << "The phrase is: " << phrase << "\n\n";
std::cout << "This phrase has " << phrase.size() << " letters!" << "\n\n";
std::cout << "The character at position zero is " << phrase[0] << "\n\n";
phrase[0] = 'S';
std::cout << "The phrase is now... " << phrase << "\n\n";
for (unsigned int i = 0; i <= phrase.size(); ++i)
{
std::cout << "Position " << i << "'s character is " << phrase[i] << "\n";
}
}
Any help would be greatly appreciated, as is feedback on my code (as I am a rookie).
P.S. <iostream> and <string> were included, I'm just having trouble showing it to you on
the website. Sorry!
A:
for (unsigned int i = 0; i <= phrase.size(); ++i)
You're going between 0 and phrase.size(), inclusive, which is too long. You should be going to phrase.size() - 1. Either change it to that, or change the <= to a < and you should be okay.
Example Fix 1:
for (unsigned int i = 0; i < phrase.size(); i++)
Example Fix 2:
for (unsigned int i = 0; i <= phrase.size() - 1; i++)
Edit - Longer/More Detailed Explanation:
Because if you have a String with 5 letters: "Hello", your actual indeces are:
string[0] = 'H'
string[1] = 'e'
string[2] = 'l'
string[3] = 'l'
string[4] = 'o'
meaning that string[5] is going too far in this case. Since you're using 0-based indexing (as do most programming languages), you have to go from 0 to size-1
| {
"pile_set_name": "StackExchange"
} |
Q:
CSV import looping duplicate times
Rather new to the Python world. I wrote the following script to convert my csv file and overwrite the existing JSON file, ready to upload to Firebase. Problem is, the script is reading each row 4 times which is odd. My code is below, would be great to know where I'm going wrong.
import csv
import json
from collections import OrderedDict
fieldnames = ("Code", "Currency", "Rate", "Last Updated")
entries = []
with open('rates.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile, fieldnames)
for row in reader:
entry = OrderedDict()
for field in fieldnames:
entry[field] = row[field]
entries.append(entry)
output = {
"rates": entries
}
with open('rates2.json', 'w') as jsonfile:
json.dump(output, jsonfile, indent=2, ensure_ascii=False)
jsonfile.write('\n')
Example of the CSV
CSV IMAGE
Example Output
{
"rates": [
{
"Code": "AED ",
"Currency": " UAE Dirham",
"Rate": "4.2499",
"Last Updated": "18/02/2020 10:13"
},
{
"Code": "AED ",
"Currency": " UAE Dirham",
"Rate": "4.2499",
"Last Updated": "18/02/2020 10:13"
},
{
"Code": "AED ",
"Currency": " UAE Dirham",
"Rate": "4.2499",
"Last Updated": "18/02/2020 10:13"
},
{
"Code": "AED ",
"Currency": " UAE Dirham",
"Rate": "4.2499",
"Last Updated": "18/02/2020 10:13"
},
{
"Code": "AUD ",
"Currency": " Australian Dollar",
"Rate": "1.8299",
"Last Updated": "18/02/2020 10:13"
},
{
"Code": "AUD ",
"Currency": " Australian Dollar",
"Rate": "1.8299",
"Last Updated": "18/02/2020 10:13"
},
{
"Code": "AUD ",
"Currency": " Australian Dollar",
"Rate": "1.8299",
"Last Updated": "18/02/2020 10:13"
},
{
"Code": "AUD ",
"Currency": " Australian Dollar",
"Rate": "1.8299",
"Last Updated": "18/02/2020 10:13"
}
]
}
A:
Just un-indent entries.append(...):
with open('rates.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile, fieldnames)
for row in reader:
entry = OrderedDict()
for field in fieldnames:
entry[field] = row[field]
entries.append(entry)
otherwise you are appending a new row for every field, when you in fact only want to do this once per row, not once per field.
| {
"pile_set_name": "StackExchange"
} |
Q:
Use Bert to predict multiple tokens
I'm looking for suggestions on using Bert and Bert's masked language model to predict multiple tokens.
My data looks like:
context: some very long context paragraph
question: rainy days lead to @placeholder and the answer for this @placeholder is wet weather. In the model, wet environment is the answer to predict.
So at the pre-processing stage, should I change the text into rainy days lead to [MASK] or something like rainy days lead to [MASK] [MASK]? I know that the masked LM works well on the single token prediction, do you think the masked LM can work well on the multiple tokens prediction? If no, do you have any suggestions on how to pre-process and train this kind of data?
Thanks so much!
A:
So there are 3 questions :
First,
So at the pre-processing stage, should I change the text into rainy
days lead to [MASK] or something like rainy days lead to [MASK]
[MASK]?
In a word point of view, you should set [MASK] [MASK]. But remember that in BERT, the mask is set at a token point of view. In fact, 'wet weather' may be tokenized in something like : [wet] [weath] [##er], and in this case, you should have [MASK] [MASK] [MASK]. So one [MASK] per token.
Second,
I know that the masked LM works well on the single token prediction,
do you think the masked LM can work well on the multiple tokens
prediction?
As you can read it in the original paper, they said :
The training data generator chooses 15% of the token positions at
random for prediction. If the i-th token is chosen, we replace the
i-th token with (1) the [MASK] token 80% of the time (2) a random
token 10% of the time (3) the unchanged i-th token 10% of the time.
They notice no limitation in the amount of MASKED token per sentence, you have several MASKED token during pre-training BERT.
In my own experience, I pre-trained BERT several times and I noticed that there were almost non differences between the prediction made on MASKED token if there were only one or more MASKED token in my input.
Third,
If no, do you have any suggestions on how to pre-process and train
this kind of data?
So the answer is yes, but if you really want to MASK elements you choose (and not randomly like in the paper), you should adapt the MASK when the data will be tokenized because the number of MASKED token will be greater (or equal) that the number of MASK in the word space you set (like the example I gave you : 1 word is not equals to 1 token, so basically, 1 MASKED word will be 1 or more MASK token). But honestly, the process of labellisation will be so huge I recommend you to increase the 15% of probability for MASK tokien or make a process that MASK the 1 or 2 next token for each MASKED token (or something like this)..
| {
"pile_set_name": "StackExchange"
} |
Q:
Django DRF APITestCase chain test cases
For example I want to write several tests cases like this
class Test(APITestCase):
def setUp(self):
....some payloads
def test_create_user(self):
....create the object using payload from setUp
def test_update_user(self):
....update the object created in above test case
In the example above, the test_update_user failed because let's say cannot find the user object. Therefore, for that test case to work, I have to create the user instead test_update_user again.
One possible solution, I found is to run create user in setUp. However, I would like to know if there is a way to chain test cases to run one after another without deleting the object created from previous test case.
A:
Rest framework tests include helper classes that extend Django's existing test framework and improve support for making API requests.
Therefore all tests for DRF calls are executed with Django's built in test framework.
An important principle of unit-testing is that each test should be independent of all others. If in your case the code in test_create_user must come before test_update_user, then you could combine both into one test:
def test_create_and_update_user(self):
....create and update user
Tests in Django are executed in a parallell manner to minimize the time it takes to run all tests.
As you said above if you want to share code between tests one has to set it up in the setUp method
def setUp(self):
pass
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.net Identity Disable User
Using the new ASP.net Identity in MVC 5, How do we disable a user from logging in? I don't want to delete them, maybe just disable their account for a time period.
Does anyone have any ideas on this as I don't see a status column or anything on the ASPNetUsers table.
A:
await userManager.SetLockoutEnabledAsync(applicationUser.Id, true);
await userManager.SetLockoutEndDateAsync(DateTime.Today.AddYears(10));
A:
Update: As CountZero points out, if you're using v2.1+, then you should try and use the lockout functionality they added first, before trying the solution below. See their blog post for a full sample: http://blogs.msdn.com/b/webdev/archive/2014/08/05/announcing-rtm-of-asp-net-identity-2-1-0.aspx
Version 2.0 has the IUserLockoutStore interface that you can use to lockout users, but the downside is that there is no OOB functionality to actually leverage it beyond the pass-through methods exposed by the UserManager class. For instance, it would be nice if it would actually increment the lockout count as a part of the standard username/password verification process. However, it's fairly trivial to implement yourself.
Step #1: Create a custom user store that implements IUserLockoutStore.
// I'm specifying the TKey generic param here since we use int's for our DB keys
// you may need to customize this for your environment
public class MyUserStore : IUserLockoutStore<MyUser, int>
{
// IUserStore implementation here
public Task<DateTimeOffset> GetLockoutEndDateAsync(MyUser user)
{
//..
}
public Task SetLockoutEndDateAsync(MyUser user, DateTimeOffset lockoutEnd)
{
//..
}
public Task<int> IncrementAccessFailedCountAsync(MyUser user)
{
//..
}
public Task ResetAccessFailedCountAsync(MyUser user)
{
//..
}
public Task<int> GetAccessFailedCountAsync(MyUser user)
{
//..
}
public Task<bool> GetLockoutEnabledAsync(MyUser user)
{
//..
}
public Task SetLockoutEnabledAsync(MyUser user, bool enabled)
{
//..
}
}
Step #2: Instead of UserManager, use the following class in your login/logout actions, passing it an instance of your custom user store.
public class LockingUserManager<TUser, TKey> : UserManager<TUser, TKey>
where TUser : class, IUser<TKey>
where TKey : IEquatable<TKey>
{
private readonly IUserLockoutStore<TUser, TKey> _userLockoutStore;
public LockingUserManager(IUserLockoutStore<TUser, TKey> store)
: base(store)
{
if (store == null) throw new ArgumentNullException("store");
_userLockoutStore = store;
}
public override async Task<TUser> FindAsync(string userName, string password)
{
var user = await FindByNameAsync(userName);
if (user == null) return null;
var isUserLockedOut = await GetLockoutEnabled(user);
if (isUserLockedOut) return user;
var isPasswordValid = await CheckPasswordAsync(user, password);
if (isPasswordValid)
{
await _userLockoutStore.ResetAccessFailedCountAsync(user);
}
else
{
await IncrementAccessFailedCount(user);
user = null;
}
return user;
}
private async Task<bool> GetLockoutEnabled(TUser user)
{
var isLockoutEnabled = await _userLockoutStore.GetLockoutEnabledAsync(user);
if (isLockoutEnabled == false) return false;
var shouldRemoveLockout = DateTime.Now >= await _userLockoutStore.GetLockoutEndDateAsync(user);
if (shouldRemoveLockout)
{
await _userLockoutStore.ResetAccessFailedCountAsync(user);
await _userLockoutStore.SetLockoutEnabledAsync(user, false);
return false;
}
return true;
}
private async Task IncrementAccessFailedCount(TUser user)
{
var accessFailedCount = await _userLockoutStore.IncrementAccessFailedCountAsync(user);
var shouldLockoutUser = accessFailedCount > MaxFailedAccessAttemptsBeforeLockout;
if (shouldLockoutUser)
{
await _userLockoutStore.SetLockoutEnabledAsync(user, true);
var lockoutEndDate = new DateTimeOffset(DateTime.Now + DefaultAccountLockoutTimeSpan);
await _userLockoutStore.SetLockoutEndDateAsync(user, lockoutEndDate);
}
}
}
Example:
[AllowAnonymous]
[HttpPost]
public async Task<ActionResult> Login(string userName, string password)
{
var userManager = new LockingUserManager<MyUser, int>(new MyUserStore())
{
DefaultAccountLockoutTimeSpan = /* get from appSettings */,
MaxFailedAccessAttemptsBeforeLockout = /* get from appSettings */
};
var user = await userManager.FindAsync(userName, password);
if (user == null)
{
// bad username or password; take appropriate action
}
if (await _userManager.GetLockoutEnabledAsync(user.Id))
{
// user is locked out; take appropriate action
}
// username and password are good
// mark user as authenticated and redirect to post-login landing page
}
If you want to manually lock someone out, you can set whatever flag you're checking in MyUserStore.GetLockoutEnabledAsync().
| {
"pile_set_name": "StackExchange"
} |
Q:
WinForms or WPF control with a buffer to show constantly updating text
Possible Duplicate:
Elegant Log Window in WinForms C#
I need a log-viewer to check the DB for new logs every few seconds and append them to a WinForms or WPF control. The control can have a buffer like command prompt and keep only the last [buffer size] lines.
What can I use for this?
A:
If you are going to use WPF, then ListBox control can work as display control. You can define various templates using ItemTemplate property of ListBox(based on log type)
This ListBox can be bound to Observable collection of ViewModel/DataContext.
You can then define your business logic in viewmodel to add/ remove entries from ObservableCollection. Changes in ObservableCollection will get reflected in Xaml UI due to binding.
[Note - You can use any other itemscontrol, there is no compulsion of using ListBox]
| {
"pile_set_name": "StackExchange"
} |
Q:
PickMeUp date picker - disable array of dates
I am using PickMeUp datepicker for selecting multiple dates. I would like to be able to pass an array of dates, disable these dates and display them in a different colour.
I currently only have the following code:
$('.multiple').pickmeup('clear');
$('.multiple').pickmeup({
flat: true,
mode: 'multiple'
});
If anyone knows how to do this, I would highly appreciate it.
A:
What you need to do is load the dates into an array. You can then check this array with PickMeUp's object render event and check every date against the dates from the array. If any of the dates coincide, you simply return the object disabled: true and the user won't be able to select the dates.
Additionally, I also return the class disabled to improve the disabled dates' CSS colors. This because PickMeUp's default color-scheme for disabled dates is black; this makes it hard to see them.
The following Javascript/jQuery achieves what you want:
// Creating some 'sample' dates
var datesArray = [];
var d = new Date();
for (i = 2; i < 7; i++) {
var tempDay = new Date(); tempDay.setHours(0,0,0,0);
tempDay.setDate(d.getDate()+i);
datesArray.push(tempDay.getTime());
}
$(function () {
$('.multiple').pickmeup({
flat: true,
mode: 'multiple',
// Before rendering each date, deselect dates if in the array
render: function(date) {
if ($.inArray(date.getTime(), datesArray) > -1){
return {
disabled : true,
class_name : 'disabled'
}
}
}
});
});
// Little hack to deselect current day: PickMeUp forces you to have a default date :(
$('.pmu-today').click();
With the following CSS:
.disabled {
color: #5C5C8A !important;
background: #000033;
}
DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
cannot resolve method error for method practicing
public class MainForm {
String varpass = "This is a string that has to be passed.";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void place1 (){
//=======================================Method calls from another class========================================
//Calls from another class. It is non-static and thus requires it to be instantiated. EG. class var = new class();
Methods call = new Methods();
System.out.println(call.t1());
//Calls from another class. It is non-static void and thus requires it to be instantiated and be called straight.
call.t3();
//Calls from another class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(Methods.t2());
//Calls from another class. It is static void and thus does not require it to be instantiated.
Methods.t4();
//Trying to call a variable that was sent.
Methods.getvar(varpass);
call.getvar(varpass);
//=======================================Method calls from current class========================================
MainForm mcall = new MainForm();
//Calls from within the same class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(mcall.t1());
mcall.t3();
System.out.println(t2());
t4();
}
public static void main(String[] args) {
MainForm place = new MainForm();
place.place1();
}
}
public class Methods {
String var1 = "This is a public String variable";
String getVar = "Initial";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void getvar(String varsent){
String msg = "getver() Variables are varsent("+varsent+"), getVar("+getVar+"), getVar(";
getVar = varsent;
msg = msg + getVar+")";
System.out.println(msg);
}
}
Here is the errors below
Methods.getvar(varpass);
call.getvar(varpass);
top one is giving non-static cannot be referenced from a static context
bottom one is saying cannot resolve method 'println(void)'
You can tell im using this as practice to call methods.
Here im trying to pass a variable varpass that contains a string. I want it pass that variable to getvar in Methods. in that getvar it takes a variable in Methods displays it before altering it then again after alter.
Im trying to understand how this works. Any insight would be appreciated.
A:
This line
Methods.getvar(varpass);
is a static call. You try to call the static Method getvar from your Methods class. This method however is not static and therefor requires an instance of Method.
This line
call.getvar(varpass);
works fine. It in fact is the solution to the first line, where you reffere a non-static method from a static context
| {
"pile_set_name": "StackExchange"
} |
Q:
Need header node height of TreeViewItem
I have an issue were i need to find the node i have my mouse over during another source drag is happening. I manage to trap the mouse location no matter the app the drag came from. anyhow from the mouse point i am able to get the item by point and i get the TreeViewItem perfectly. One major issue is that if the node i am dropping on is expanded the TreeViewItem is including all it's child visually so when checking for my TreeViewItem height i get height in the thousands. when it's collapse it works perfectly i get something like 200(W) x 25(H). is there a way to grab juste the header of the node size and not including all his child ?
since it can have TreeViewItem in a TreeViewItem in-definitively and that the header is technically a TreeViewItem I don't understand how with PARTS i can get what i am looking for since they are all the same.
A:
Created a new control myself as we couldn't find any help online for this. Took about 20-25 man hours to build a new treeview. Shame that by default the winform treeview works perfectly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Live Data Feed and Scrollbar Position
I am retrieving data from a MySQL database and displaying it on a website using the EventSource API. So far everything is working as expected, but I want to display the data in a fixed height div, and fix the scrollbar to the bottom of this div - i.e always show the latest feed results first.
Now when I load the page the scrollbar is fixed to the top.
I have tried the suggestion here but it doesn't seem work. Is it because I am working with live data and AJAX requests in order to populate the div?
My cose so far is;
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<style type="text/css">
#result {
overflow: auto;
max-height:224px;
width: 500px;
}
</style>
<script type="text/javascript">
// scrollbar to bottom
$("document").ready(function(){
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
});
// retrieve data from server and display in div
$("document").ready(function(){
var source = new EventSource("data.php");
var offline;
$.ajax({
type: "POST",
url: 'data.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
$.each(data, function(key, value) {
document.getElementById("result").innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
} // end success
});
});//end dom ready
</script>
</head>
<body>
<div id="result"><!--Server response inserted here--></div>
</body>
</html>
The strange this is, whenever I remove the live feed javascript and manually add some (lorem ipsum) text into the <div id="result"> it works, the scrollbar appears at the bottom of the div.
I could be doing something very silly :)
Any advice is appreciated.
A:
When you load more data via ajax, the size of the content will change. Have you tried setting the scroll again after you've rendered the content? i.e.:
success: function(data){
var objDiv = document.getElementById("result");
$.each(data, function(key, value) {
objDiv.innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
objDiv.scrollTop = objDiv.scrollHeight;
} // end success
});
Thus setting the scroll value the same way you do when the page loads.
Alternatively, here's another completely different option:
If you want the most recent values to be most prominent, you could simply output them in reverse order, so the newest ones are at the top of the div, where the user will see them first. You can use jQuery's .prepend() method to add content to the beginning of the div, above the previous results. Then there's no need for messing about with scrolling. http://api.jquery.com/prepend/ I'd argue this is more user-friendly, but it's up to you obviously.
| {
"pile_set_name": "StackExchange"
} |
Q:
Зачем нужна папка "\\\\.\\ "?
Что хранится по этому пути? Знаю только, что там есть файл PhysicalDrive0, в котором хранятся данные о запуске системы.
A:
Никакой папки \\\\.\\ не существует. Существует префикс \\.\ (при записи в строковых константах в Си-подобных языках обратная косая черта удваивается), который используется для передачи в функцию CreateFile имени устройства вместо имени файла. Например \\.\PhysicalDrive0 соответствует диску, \\.\COM1 - последовательному порту и т.п.
Подробнее см. в Win32 Device Namespaces
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem on a query with NHibernate
I have a very simple scenario, using NHibernate:
one abstract base class "animal";
two concrete subclass "cat" and "dog" with discriminator column (1 for dog and 2 for cat);
one normal class Person;
Person have a many-to-one of animal.
I want retrieve a list of person with a dog.
How can I do this?
thx a lot
A:
If I understand well, something like this :
var list = session.CreateCriteria(typeof(Person))
.CreateCriteria("Animal")
.Add(Expression.Eq("discriminatorField", 1))
.List<Person>();
above is "Criteria API" but you can use "HQL" it's more something like this :
StringBuilder query = new StringBuilder();
query.Append("from Person pers where ");
query.Append("from Animal ani ... and :wichAnimal");
query.Append("and cus.IsActive = :wichAnimal");
IList<Person> list = session
.CreateQuery(query.ToString())
.SetInt16("wichAnimal",1)
.List<Person>();
HTH
| {
"pile_set_name": "StackExchange"
} |
Q:
This is question about integration. I want you to check error.
!This is the solution that I tried, but the answer is wrong. I cannot find any
mistakes, or did I approach this problem to the wrong way?
Please tell me which part is wrong, or if there are better solution, please let me know. Thanks.
A:
Since I am almost blind, I cannot read your notes. So, I propose something.
Let us consider first $$I=\int \sqrt{x^2+a^2} dx$$ Change variable using $x=a\sinh(y)$, so $dx=a \cosh(y)dy$ and then $$I=a^2\int \cosh^2(y)dy$$ Now, use $$\cosh(2y)=2\cosh^2(y)-1$$ So, $$I=\frac{a^2}{2} \int\Big(1+\cosh(2y)\Big)dy=\frac{a^2}{2}\Big(y+\frac{1}{2}\sinh(2y)\Big)=\frac{a^2}{2} \Big(y+\sinh (y) \cosh (y)\Big)$$ and you need now to integrate for $y$ between $0$ and $\sinh^{-1}(1)$. So, the result is $$\frac{a^2}{2} \left(\sqrt{2}+\sinh ^{-1}(1)\right)$$
I am sure that you can take from here.
| {
"pile_set_name": "StackExchange"
} |
Q:
BibLaTeX: Suppress comma after editor names
I am trying to get my bibliography to my needs, and there is one comma which I don't know how to remove.
In entry [2] ('inbook') it is correct, but in entry [1] ('book' without author, just editor) there shouldn't be the comma.
It is really difficult for me to understand all the biblatex commands, so it would be great if someone could help me with this issue.
My minimal working example:
\documentclass{scrreprt}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage[backend=biber,style=authoryear]{biblatex}
\usepackage{csquotes}
\usepackage{filecontents}
\begin{filecontents*}{bib.bib}
@book{awv_stmk,
editor = "{Hans Wurst}",
title = "{Das Leben}"
}
@inbook{book2,
author = "Hans Wurst",
booktitle = "Das Leben",
editor = "Biene Maja",
title = "Artikel"
}
\end{filecontents*}
\addbibresource{bib.bib}
% Put editor string in parentheses
\DeclareFieldFormat{editortype}{\mkbibparens{#1}}
% Like editor+others but without comma before editor string and dash checks
\newbibmacro*{ineditor+others}{%
\ifboolexpr{ test \ifuseeditor and not test {\ifnameundef{editor}} }
{\printnames{editor}%
\setunit{\addspace}%
\usebibmacro{editor+othersstrg}%
\clearname{editor}}
{}}
% Print editors before "in" title
\renewbibmacro{in:}{%
\ifentrytype{article}{}{\printtext{\bibstring{in}\intitlepunct}}%
\usebibmacro{ineditor+others}%
\newunit
\clearname{editor}}
\begin{document}
\nocite{*}
\printbibliography
\end{document}
A:
Edit: For authoryear style, you modify the bbx:editor macro to put in a space instead of a comma and space. Try adding this:
\usepackage{xpatch}
\xpatchbibmacro{bbx:editor}
{\addcomma\space}{\addspace}{}{}
You can also do an equivalent change for bbx:translator.
| {
"pile_set_name": "StackExchange"
} |
Q:
can I require a return value to be a pointer to a constant
say I have two 'modules'. For instance the hardware-interface layer of a RS-232 port and a layer above it to make it more abstract.
I have a receive buffer like this: U8BIT myBuffer[MAX]. U8BIT is typedeffed: typedef unsigned char
There are however two type of messages that can be received. One that has a header and another one that doesn't have a header. The logic for this is already written.
The 'layer above' will access this buffer but it should have no knowledge whether this is a header or header-less message.
Thus I have a function like this:
U8BIT * fooBuffer(U8BIT * maxLength)
{
U8BIT * retval;
if( isHeaderless() )
{
retval = &(myBuffer[0]);
*maxLength = MAX;
}
else
{
retval = &(myBuffer[5]);
*maxLength = MAX - 5;
}
return retval;
}
How can I make sure that any function calling this function is not able to alter the contents of the returned pointer?
Yes I know it will always be possible. And not trying to make it harder for others to do try to modify it. I want it to be 'not possible' so that it will be less easier to make mistakes because the compiler will complain if you do try to modify a const.
Can I just declare the function as follows: const U8BIT * fooBuffer(U8BIT * maxLength)
A:
Use const U8BIT * as the return type of the function.
For example in your function:
const U8BIT * fooBuffer(U8BIT * maxLength)
{
U8BIT * retval;
// code
return (const U8BIT *) retval;
}
If retvalpointer is not dereferenced inside your fooBuffer function, declare it also as const U8BIT * and then the cast in the return statement is no longer needed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Working of intrensic Lock
public class Check {
public boolean toChange = false;
public synchronized boolean getChange() {
return tochange
}
public synchronized setChange(boolean change) {
this.tochange = change
}
}
When 2 different threads try to access get and set simultanoesuly , will it happen in a synchronous way due to lock on check object?
A:
Since both the methods are non-static and synchronous, no 2 threads at any instance of time, can execute both the methods simultaneously, IF they belong to same INSTANCE.
So yes, it will happen in a synchronous way, within instances of this class.
When you create Check c = new Check();
and 2 threads namely t1, t2 try to access c.getChange() and c.setChange() simultaneously, only one thread will be given the access to monitor (which is instance c) and the other thread has to wait until the previous thread finishes work and releases the monitor.
Here the instance c is the default monitor used to synchronize the access
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get the count of number of times user didSelectRowAtIndexPath?
On my UITableView I want to check how many times user has tapped the same row.
If user has tapped the same row three times I want to delete the row from the UITableView.
Can anyone please lead me to the solution? I tried doing:
for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {
count = count + 1;
NSLog(@"rowCount %d indexPath.row %@", count, indexPath);
}
But this doesn't increment the count number of times the row was tapped by user.
A:
Assuming you want to delete the row only if the user select three times a row the same cell.
Create another variable lastSelectedRow where you keep the last selected row. (create underneath the implementation line)
@implementation myViewController
{
NSInteger = lastSelectedRow;
}
Next, you should verify that the row is equal to the last one selected, increment and check if the row have to be deleted:
for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {
// If the last selected row is the same, increment the counter, else reset the counter to 1
if (indexPath.row == lastSelectedRow) count++;
else
{
lastSelectedRow = indexPath.row;
count = 1;
}
// Now we verify if the user selected the row 3 times and delete the row if so
if (count >= 3) [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
NSLog(@"rowCount %d indexPath.row %@", count, indexPath);
}
Hope it helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
cfqueryparam questions/help
Via this question I've been told to start using cfqueryparam for my data, to prevent SQL injection attacks.
How do I use it for my forms? Right now I've been going over Ben Forta's book, Vol 1 and been passing data to my form, then to a form processor that calls a CFC. The CFC takes them in as a cfargument then injects that into the database with any type="x" validation.
Io use the cfqueryparam, I use that on the query itself and not even declare cfargument?
A:
You can still use a CFC, but remember that string data passed as a function argument will still need <cfqueryparam>. Here is an example:
<cffunction name="saveData" access="public" returntype="void" output="false">
<cfargument name="formVar" type="string" required="true" />
<cfquery name="LOCAL.qSave" datasource="myDSN">
insert into myTable (col1)
values (<cfqueryparam cfsqltype="cf_sql_varchar" value="#ARGUMENTS.formVar#" />)
</cfquery>
</cffunction>
The important habit to get into is to always use <cfqueryparam>, even in CFCs.
Here is some more info on those edge-cases where you might find it hard to use <cfqueryparam>.
Hope that helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding Paragraph Spacing in Longtables
I am trying to add spacing between paragraphs inside the cells of a longtable. I don't want to spread out every line, just the paragraphs, just like regular paragraphs in my document.
\documentclass[a4paper,10pt]{article}
\usepackage{longtable}
\begin{longtable}{|p{51 pt}|p{370 pt}|}
\textsc{Aug 2017}&\Large{{Sample Project Title}}\\
\textsc{\hfill -Present}&Shortly before my start at Somewhere Industries, a catastrophic failure of one of the system conveyor occurred.
I also drove the inventory management, document management and SAP system re-implementation to ensure all site-specific technical aspects were adequately addressed and integrated with asset management system and strategic initiatives.
\end{longtable}
\end{document}
(BTW: I don't want to use columns. The longtable format works best for what I need. I also don't want to learn a new environment. I like longtable :) )
A workaround I've found is using parskip INSIDE the cell as in this MWE:
\documentclass[a4paper,10pt]{article}
\usepackage{longtable}
\usepackage{parskip}
\begin{longtable}{|p{51 pt}|p{370 pt}|}
\textsc{Aug 2017}&\Large{{Sample Project Title}}\\
\textsc{\hfill -Present}&{\setlength{\parskip}{6pt}Shortly before my start at Somewhere Industries, a catastrophic failure of one of the system conveyor occurred.
I also drove the inventory management, document management and SAP system re-implementation to ensure all site-specific technical aspects were adequately addressed and integrated with asset management system and strategic initiatives.
\end{longtable}
\end{document}
But I'd like it to a global setting.
Thanks
A:
You can use the array package to inject code in every cell.
\documentclass[a4paper,10pt]{article}
\usepackage{longtable,array}
\begin{longtable}{|p{51 pt}|>{\setlength\parskip{1ex}}p{370 pt}|}
\textsc{Aug 2017}&\Large Sample Project Title \\
\textsc{\hfill -Present}&Shortly before my start at Somewhere Industries, a catastrophic failure of one of the system conveyor occurred.
I also drove the inventory management, document management and SAP system re-implementation to ensure all site-specific technical aspects were adequately addressed and integrated with asset management system and strategic initiatives.
\end{longtable}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Get byte representation of int, using only 3 bytes
What's a nice, readable way of getting the byte representation (i.e. a byte[]) of an int, but only using 3 bytes (instead of 4)? I'm using Hadoop/Hbase and their Bytes utility class has a toBytes function but that will always use 4 bytes.
Ideally, I'd also like a nice, readable way of encoding to as few bytes as possible, i.e. if the number fits in one byte then only use one.
Please note that I'm storing this in a byte[], so I know the length of the array and thus variable length encoding is not necessary. This is about finding an elegant way to do the cast.
A:
A general solution for this is impossible.
If it were possible, you could apply the function iteratively to obtain unlimited compression of data.
Your domain might have some constraints on the integers that allow them to be compressed to 24-bits. If there are such constraints, please explain them in the question.
A common variable size encoding is to use 7 bits of each byte for data, and the high bit as a flag to indicate when the current byte is the last.
You can predict the number of bytes needed to encode an int with a utility method on Integer:
int n = 4 - Integer.numberOfLeadingZeros(x) / 8;
byte[] enc = new byte[n];
while (n-- > 0)
enc[n] = (byte) ((x >>> (n * 8)) & 0xFF);
Note that this will encode 0 as an empty array, and other values in little-endian format. These aspects are easily modified with a few more operations.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery: Don't want "Open Hover" state on accordion menu
Hi Everyone
I have an accordion menu that I've adapted from this one I found on DynamicDrive.com.
Instead of the typical UL type accordion, this one hides and reveals DIVs.
I need 3 states for the headings:
Closed (black text / white background)
Closed Hover (white text / black background)
Open (red text / white background)
At the moment there is a 4th state (Open Hover), but I don't want this.
How do I make the open state have no hover? (or have it's on unique hover state). At the moment the script applies the same closed-hover css style to the open-hover state.
Here is the code on JSFiddle. I know there is a lot of JavaScript there, but any help would be greatly appreciated.
A:
do you mean like this: Updated fiddle
if that's what you're after the only changes are in the CSS.. I had to make the .openheader link rule more specific (by putting the a in front of it) to match the specificity of the a.menuitem links.. then made sure all the a.menuitem rules were preceding the a.openheader one
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the integer portion of a float column in pandas
Suppose I have a dataframe df as shown below
qty
0 1.300
1 1.909
Now I want to extract only the integer portion of the qty column and the df should look like
qty
0 1
1 1
Tried using df['qty'].round(0) but didn't get the desired result as it rounds of the number to the nearest integer.
Java has a function intValue() which does the desired operation. Is there a similar function in pandas ?
A:
Convert values to integers by Series.astype:
df['qty'] = df['qty'].astype(int)
print (df)
qty
0 1
1 1
If not working above is possible use numpy.modf for extract values before .:
a, b = np.modf(df['qty'])
df['qty'] = b.astype(int)
print (df)
qty
0 1
1 1
Or by split before ., but it should be slow if large DataFrame:
df['qty'] = b.astype(str).str.strip('.').str[0].astype(int)
Or use numpy.floor:
df['qty'] = np.floor(df['qty']).astype(int)
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I convert the string to URL which include a ? in the string by Swift 4.2
As the title, I am using Google Places API, the URL has a question mark, when I send a request, it will become %3F, how can I modify my code by Swift 4.2??
I found a lot of information but they were using Swift 2 or 3, so it is unavailable for me!
UPDATE my code
let urlString = "\(GOOGLE_MAP_API_BASEURL)key=\(GMS_HTTP_KEY)&input=\(keyword)&sessiontoken=\(ver4uuid!)"
print(urlString)
if let encodedString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics
.union(CharacterSet.urlPathAllowed)
.union(CharacterSet.urlHostAllowed)) {
print("encodedString: \(encodedString)")
A:
You are supposed to encode only the query parameters (although probably only keyword actually needs encoding), not the whole URL.
func urlEncode(_ string: String) -> String {
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "!*'();:@&=+$,/?%#[]")
return string.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
)
let urlString = "\(GOOGLE_MAP_API_BASEURL)key=\(urlEncode(GMS_HTTP_KEY))&input=\(urlEncode(keyword))&sessiontoken=\(urlEncode(ver4uuid!))"
print(urlString)
Also see Swift - encode URL about the correct way to encode URL parameters.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create custom pdf annotation using PDPageContentStream class of pdfbox library?
I have implemented functionality to create cloud markups using the addBezier curve methods of the PDPageContentStream class. Now, I want create this markups as page annotation, so that I can delete these markups. I tried creating custom annotation using the PDAnnotation.createAnnotation method but it requires COSBase variable. So, how do I create a COSBase variable using the PDPageContentStream class to specify the shape of annotation.
A:
You can do something alone the lines of
PDAnnotation annot = new PDAnnotationMarkup();
PDAppearanceDictionary appearance = new PDAppearanceDictionary();
PDAppearanceStream appearanceStream = new PDAppearanceStream(new COSStream());
appearance.setNormalAppearance(appearanceStream);
annot.setAppearance(appearance);
PDPageContentStream contentStream = new PDPageContentStream(pdfDocument, appearanceStream);
contentStream.addBezier(....);
..... more additions to the content stream
I've left the code to add the annotation to the page etc. of as this can be viewed from the AddAnnotations.javaexample in the examples package.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I invert the direction of blocks in a structure?
I have a structure with some blocks facing in the 'normal' direction:
nn nn nn nn
| || || || |
-- -- -- --
I would like to somehow connect a layer above this that has the blocks facing the other way so that I end up with:
-- -- -- --
| || || || |
uu uu uu uu
nn nn nn nn
| || || || |
-- -- -- --
How can I achieve this?
A:
It depends on how close they need to be.
The following solution works, if you're happy to have things sticking out around the join:
"Brick 1x2 M. 2 Holes Ø 4,87", [part:32000:7]; There's also a 1x1 brick with a hole, [part:6541:7].
Which could be used as:
For tighter coupling, the Minifig Wrench [part:6246d:0] can also fit over a stud, and is deeper than one stud, allowing two bricks to be inserted:
Respect goes to Erik Amzallag for this one.
I guess it comes down to how you want to hide the join - you could use tiles on the studs that stick out, which wouldn't be possible with the wrench method.
A:
Holger Matthes has a good page on SNOT building which includes a few techniques on how to get stud-down orientation.
Also, don't underestimate tiles, sometimes you can just lock the upside-down part into place without attaching it with studs at all (I did this when I was a kid to use a black 3943 — Cone 4 x 4 x 2 as a train chimney as the inverted part didn't exist at the time:
None of the inverted parts are actually attached, but they are locked in place by surrounding parts. You can see inverted parts in orange in this partial build; the blue parts are tiles in the usual direction:
Another good part to inverse stud direction is the 4081b — Plate 1 x 1 with Clip Light - Type 2 ( as the studs are exactly one plate apart. You'll need to hide it in the construction somehow, but it can be very handy.
For example, both that part and the tile-on-tile technique are used in this window roof to inverse the below arch:
It all rests on a tan Tile 4 x 4 with Studs on Edge, which is also used higher with a Train Roof 6 x 6 Double Slope 45 / Slope 33 to finish the roof. The following image illustrate a partial build, will all upside-down parts colored orange:
Edit: there are of course more techniques to be found on the Internet, but some are more simple or place-efficient than others. For plates for example, the use of levers is as compact as you'll ever find. For bricks, you can also stuff a Technic axle in the tubes, as illustrated here. Simple and efficient.
Another edit, this time answering the question with the intended stud direction.
On a 2x4 brick/plate, place a 3185 — Fence 1 x 4 x 2, then add two 87580 — Plate 2 x 2 with 1 Stud with the stud facing down in one of the empty holes of the fence. This is probably the smallest offset you'll get, but the thickness of the fence isn't really standard, so whether it's useful or not depends on the rest of your creation.
If you're willing, there's also the Clikits Bead, Ring Thick Small with Hole which accepts a stud in both directions.
A:
This is very old-school, but that's how I was doing SNOT in the early 80's: a plate, or a tile (as shown) snaps between 2 studs. I prefer tiles to plates, as I don't have studs-alignment issues, but I've used both, and both work.
| {
"pile_set_name": "StackExchange"
} |
Q:
MVC security role check in the ViewModel
Is it good security practice putting a security related property in the ViewModel, for use in a View, i.e. showing/hiding "stuff" depending on the user's role?
For example:
ViewModel property AdminRole. Setting it's value in the Controller (User.IsInRole), then in the View accessing the property: if (Model.AdminRole) { show admin stuff... }
I've read other SO posts and (some) people are doing it this way, but questioning if this is safe, i.e. exposing a security property in the ViewModel. If there is a better, more secure way please let me know.
Off topic, but related: IMHO this is far better than calling User.IsInRole in the View directly.
A:
If by "ViewModel" you are referring to DTOs used for MVC views (as opposed to the ViewModel in an MVVM framework) then no, this is not a good design.
First of all, it's a bad design from a security perspective because:
You are relying on your view to actually enforce the security rules (e.g. by checking AdminRole to conditionally render content). This is difficult to test or review effectively.
You run the risk of unintentionally leaking private security information to the client, due to bugs or just sloppy coding.
You run the risk of accidentally having this property used in POST, PUT, or other "write" action without proper sanitization.
But more importantly, it's simply bad design from an MVC perspective, as it's missing the point of what a View Model is supposed to be.
View Models are meant to contain information about how to display a view. They are supposed to abstract the business logic that would otherwise go in a view, not just pass it on.
A better design for this scenario is something like this:
ViewModel
public class IndexViewModel
{
public bool CanDeleteItems { get; set; }
public bool IsAdminMenuVisible { get; set; }
// Other properties...
}
Controller
public ActionResult Index()
{
return View(new IndexViewModel
{
CanDeleteItems = User.IsInRole("ContentManager"),
IsAdminMenuVisible = User.IsInRole("Administrator"),
// Other properties...
});
}
View
@if (Model.IsAdminMenuVisible)
{
<!-- Markup for admin menu -->
}
@foreach (var item in Model.Items)
{
<!-- Markup for item -->
<button type="submit" @((Model.CanDeleteItems) ? "disabled" : "")>Delete</button>
}
The idea here is that the ViewModel contains only properties that are specific to the view itself. The view doesn't get to decide under what business conditions a certain element is visible, disabled, etc. The view model will tell it exactly what to display and when, using properties named after the specific view elements that they are bound to.
This is better for maintainability as well. What happens if you decide that users should be able to delete items if they have the "ContentManager" OR the "Administrator" role? In your version, you'd end up modifying the view; in the above version, you'd only need to modify the controller. If you find yourself having to modify views for reasons other than changing the look and feel, it means you've made a mistake in your architecture. Security checks should happen in the controller.
Note, depending on your architectural style it may also be acceptable for you to implement these as derived properties in your ViewModel, for example:
public class IndexViewModel
{
private readonly IPrincipal user;
public IndexViewModel(IPrincipal user)
{
this.user = user;
}
public bool CanDeleteItems
{
get { return user.IsInRole("ContentManager"); }
}
public bool IsAdminMenuVisible
{
get { return user.IsInRole("Administrator"); }
}
}
This is a somewhat more object-oriented design and is equally acceptable because the view model doesn't actually expose the underlying rules to the view, and is just as testable as a controller. Like I said above, it's more of a matter of personal preference, and whether you want your ViewModels to be intelligent (as in MVVM) or just dumb DTOs (more MVC style).
A:
If your ViewModel is being passed into your action method and variable assignment is done by model binding then, yes, it could get hijacked using the Mass Assignment Vulnerability. If this is a concern, the I would use any of the other approaches to get data into your view.
| {
"pile_set_name": "StackExchange"
} |
Q:
Concatenating multilevel objects for filtering
This looks way bigger than it actually is, it's just the objects that making the question look large. But I think you'll need to see the shape of the whole thing
I have a bit of an issue with the shape of my object. When I click on check boxes it filters the object to return unique entries based on the id of the item. The object being filtered is an assignment of two arrays year and sector
const filterObject = {...years, ...sectors};
which looks like this:
filterObject =
{
"2016": [
{
"id": 0,
"name": "charity1",
"sector": "Conservation",
"year": 2016,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.3397,
"longitude": 12.3731,
"donations": 50000,
"image": "https://lorempixel.com/321/200/nature",
"logo": "https://lorempixel.com/100/50/abstract"
},
{
"id": 3,
"name": "charity4",
"sector": "Sport",
"year": 2016,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 50.5764627,
"longitude": 9.2230577,
"donations": 74000,
"image": "https://lorempixel.com/321/200/sport",
"logo": "https://lorempixel.com/100/50/abstract"
}
],
"2017": [
{
"id": 1,
"name": "charity2",
"sector": "Children",
"year": 2017,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.0504,
"longitude": 13.7373,
"donations": 100000,
"image": "https://lorempixel.com/321/200/abstract",
"logo": "https://lorempixel.com/100/50/abstract"
}
],
"2018": [
{
"id": 2,
"name": "charity3",
"sector": "Seniors",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.5413,
"longitude": 9.9158,
"donations": 70000,
"image": "https://lorempixel.com/321/200/people",
"logo": "https://lorempixel.com/100/50/abstract"
},
{
"id": 4,
"name": "charity5",
"sector": "Homeless",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.9500019,
"longitude": 7.4836722,
"donations": 60000,
"image": "https://lorempixel.com/321/200/city",
"logo": "https://lorempixel.com/100/50/abstract"
},
{
"id": 5,
"name": "charity6",
"sector": "Homeless",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 50.9500019,
"longitude": 6.4836722,
"donations": 60000,
"image": "https://lorempixel.com/321/200/city",
"logo": "https://lorempixel.com/100/50/abstract"
}
],
"Conservation": [
{
"id": 0,
"name": "charity1",
"sector": "Conservation",
"year": 2016,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.3397,
"longitude": 12.3731,
"donations": 50000,
"image": "https://lorempixel.com/321/200/nature",
"logo": "https://lorempixel.com/100/50/abstract"
}
],
"Children": [
{
"id": 1,
"name": "charity2",
"sector": "Children",
"year": 2017,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.0504,
"longitude": 13.7373,
"donations": 100000,
"image": "https://lorempixel.com/321/200/abstract",
"logo": "https://lorempixel.com/100/50/abstract"
}
],
"Seniors": [
{
"id": 2,
"name": "charity3",
"sector": "Seniors",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.5413,
"longitude": 9.9158,
"donations": 70000,
"image": "https://lorempixel.com/321/200/people",
"logo": "https://lorempixel.com/100/50/abstract"
}
],
"Sport": [
{
"id": 3,
"name": "charity4",
"sector": "Sport",
"year": 2016,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 50.5764627,
"longitude": 9.2230577,
"donations": 74000,
"image": "https://lorempixel.com/321/200/sport",
"logo": "https://lorempixel.com/100/50/abstract"
}
],
"Homeless": [
{
"id": 4,
"name": "charity5",
"sector": "Homeless",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.9500019,
"longitude": 7.4836722,
"donations": 60000,
"image": "https://lorempixel.com/321/200/city",
"logo": "https://lorempixel.com/100/50/abstract"
},
{
"id": 5,
"name": "charity6",
"sector": "Homeless",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 50.9500019,
"longitude": 6.4836722,
"donations": 60000,
"image": "https://lorempixel.com/321/200/city",
"logo": "https://lorempixel.com/100/50/abstract"
}
]
}
I think my filters are correct,
const markerObject = filterObject[self.id];
const markerID = markerObject["id"];
mapMarkers.filter(marker => marker[0].id !== markerID);
but when the check box is checked I get this:
[
[
{
"id": 4,
"name": "charity5",
"sector": "Homeless",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.9500019,
"longitude": 7.4836722,
"donations": 60000,
"image": "https://lorempixel.com/321/200/city",
"logo": "https://lorempixel.com/100/50/abstract"
},
{
"id": 5,
"name": "charity6",
"sector": "Homeless",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 50.9500019,
"longitude": 6.4836722,
"donations": 60000,
"image": "https://lorempixel.com/321/200/city",
"logo": "https://lorempixel.com/100/50/abstract"
}
],
[
{
"id": 2,
"name": "charity3",
"sector": "Seniors",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.5413,
"longitude": 9.9158,
"donations": 70000,
"image": "https://lorempixel.com/321/200/people",
"logo": "https://lorempixel.com/100/50/abstract"
},
{
"id": 4,
"name": "charity5",
"sector": "Homeless",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 51.9500019,
"longitude": 7.4836722,
"donations": 60000,
"image": "https://lorempixel.com/321/200/city",
"logo": "https://lorempixel.com/100/50/abstract"
},
{
"id": 5,
"name": "charity6",
"sector": "Homeless",
"year": 2018,
"description": "lorem ipsum",
"address": "",
"Postleitzahl": "",
"bundesland": "",
"latitude": 50.9500019,
"longitude": 6.4836722,
"donations": 60000,
"image": "https://lorempixel.com/321/200/city",
"logo": "https://lorempixel.com/100/50/abstract"
}
]
]
As you can see there are duplicate entries, I think it's caused by the shape of the origional object 'filterObject'.
Here's the whole code https://codepen.io/sharperwebdev/pen/rdeeeY?editors=0011 lines 266 to 302
Any help would be greatly appreciated.
A:
You could flat the result array and then filter duplicates out by using Set with a closure.
var array = [[{ id: 4, name: "charity5", sector: "Homeless", year: 2018, description: "lorem ipsum", address: "", Postleitzahl: "", bundesland: "", latitude: 51.9500019, longitude: 7.4836722, donations: 60000, image: "https://lorempixel.com/321/200/city", logo: "https://lorempixel.com/100/50/abstract" }, { id: 5, name: "charity6", sector: "Homeless", year: 2018, description: "lorem ipsum", address: "", Postleitzahl: "", bundesland: "", latitude: 50.9500019, longitude: 6.4836722, donations: 60000, image: "https://lorempixel.com/321/200/city", logo: "https://lorempixel.com/100/50/abstract" }], [{ id: 2, name: "charity3", sector: "Seniors", year: 2018, description: "lorem ipsum", address: "", Postleitzahl: "", bundesland: "", latitude: 51.5413, longitude: 9.9158, donations: 70000, image: "https://lorempixel.com/321/200/people", logo: "https://lorempixel.com/100/50/abstract" }, { id: 4, name: "charity5", sector: "Homeless", year: 2018, description: "lorem ipsum", address: "", Postleitzahl: "", bundesland: "", latitude: 51.9500019, longitude: 7.4836722, donations: 60000, image: "https://lorempixel.com/321/200/city", logo: "https://lorempixel.com/100/50/abstract" }, { id: 5, name: "charity6", sector: "Homeless", year: 2018, description: "lorem ipsum", address: "", Postleitzahl: "", bundesland: "", latitude: 50.9500019, longitude: 6.4836722, donations: 60000, image: "https://lorempixel.com/321/200/city", logo: "https://lorempixel.com/100/50/abstract" }]],
result = array
.reduce((r, a) => r.concat(a), [])
.filter((s => o => !s.has(o.id) && s.add(o.id))(new Set));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
| {
"pile_set_name": "StackExchange"
} |
Q:
Why (?<!index)\.html? can't match 'abc.html'
m = re.match('(?<!index)\.html?', 'abc.html')
print(m)
can't match, on my memory it should work...
i'm a rookie,please help me. thanks a lot.
A:
re.match includes an implicit start of string anchor. The (?<!index) says the . can't be preceded by index, but it doesn't match anything that isn't index either, so the implicit anchor means that this effectively matches only strings that begin .html?.
To fix, either use re.search instead of re.match (removing the implicit anchor), or capture the preceding text explicitly (with the negative lookbehind assertion still excluding anything that ends with index):
m = re.match('.*(?<!index)\.html?', 'abc.html') # Use re.fullmatch to prevent arbitrary suffixes
# ^^ added
To allow things that end with index, but aren't exactly index, you can use an alternation:
m = re.match('(?:.{6,}|.{,5}(?<!index))\.html?', 'aindex.html')
where we allow a match if the name is at least six characters or it's five or less and they're not index.
I'll note, the complexity here means I'd be inclined to skip the regex entirely; plain string methods are going to be pretty good. For example, assuming this is just testing, not using the resulting match object, you could replace:
if re.match('(?:.{6,}|.{,5}(?<!index))\.html?', filename):
with either:
if filename.endswith(('.htm', '.html')) and filename not in ('index.htm', 'index.html'):
or:
root, ext = os.path.splitext(filename)
if ext in ('.htm', '.html') and root != 'index':
Sure it's slightly longer, but it's far less complicated/error-prone.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to implement a camera for a TiledMap with SDL2 and Box2d?
I m writing a game engine using mainly SDL2 and box2D,
I implemented TiledMap class that loads a tmx map and everything is fine it even support animation and objects that later will generate Box2D bodies for collision
Everything is fine till Camera came in I implemented camera class and its working fine for the sprites and the map but something is annoying me the bodies that get generated will stay at their position when the camera moves!
To illustrate the problem see these screenshots:
Without moving the camera the result is normal:
I tried to come up with some solution one of them is to translate all of the map bodies backward. The solution honestly worked but have some side effects that made me not satisfied at all with the result
Expensive (specially if your setting the camera every frame)
Results in a non physical behavior !
Finally I will show some code so the reader will understand exactly what Im doing:
Camera Class:
void Camera::addObjectToCamera(TiledMap* map)
{
m_CameraAttachedObjects.emplace_back(map);
}
void Camera::moveCamera(Vec2i p_Offset)
{
m_CamPos += p_Offset;
for (auto& obj : m_CameraAttachedObjects)
{
p_Offset.x = -p_Offset.x;
obj->translateMap(p_Offset);
}
}
void Camera::setCameraPosition(Vec2i p_Pos)
{
m_CamPos = p_Pos;
for (auto& obj : m_CameraAttachedObjects)
{
obj->setPosition(p_Pos);
}
}
TiledMap class:
void TiledMap::render(float dt)
{
SDL_RenderCopy(r, m_MapTexture, &m_MapSrc, NULL);
}
void TiledMap::setPosition(Vec2i pos)
{
static Vec2i LastPositionTranslated = Vec2i(0, 0);
if (Utility::IsInBox(Vec2i(pos.x, pos.y), Vec2i(0,0), Vec2i(m_MapDst.w, m_MapDst.h))) {
m_Position = pos;
m_MapSrc.x = pos.x;
m_MapSrc.y = pos.y;
for (auto& itr : m_cachedAnimatiedTiles) {
auto current_rect = itr->tiledLayerData->DestDraw;
itr->tiledLayerData->DestDraw->x = current_rect->x - (pos.x - LastPositionTranslated.x);
itr->tiledLayerData->DestDraw->y = current_rect->y - (pos.y - LastPositionTranslated.y);
}
for (auto& phyObj : m_allMapBodies) {
Vec2f old_transform = phyObj->GetTransform().p;
phyObj->SetTransform
(
Vec2f(old_transform.x-float(pos.x - LastPositionTranslated.x), old_transform.y-float(pos.y - LastPositionTranslated.y))
,0.f
);
}
LastPositionTranslated = pos;
}
}
void TiledMap::translateMap(Vec2i pos)
{
if (Utility::IsInBox(Vec2i(m_MapSrc.x - pos.x, m_MapSrc.y - pos.y), Vec2i(0, 0), Vec2i(m_MapDst.w, m_MapDst.h))) {
m_Position += pos;
m_MapSrc.x -= pos.x;
m_MapSrc.y -= pos.y;
for (auto& itr : m_cachedAnimatiedTiles) {
auto current_rect = itr->tiledLayerData->DestDraw;
itr->tiledLayerData->DestDraw->x = current_rect->x + pos.x;
itr->tiledLayerData->DestDraw->y = current_rect->y + pos.y;
}
for (auto& phyObj : m_allMapBodies) {
Vec2f old_transform = phyObj->GetTransform().p;
phyObj->SetTransform(old_transform + Vec2f((float)(pos.x), (float)(pos.y)), 0.f);
}
}
}
Game class (game manager):
body->SetLinearVelocity(Vec2f(20.f, body->GetLinearVelocity().y));
cam->moveCamera(Vec2i(10, 0));
the current code is translating the bodies too which is i consider a bad solution of my initial problem anyone have better solution to scroll in box2d? (See another part of the box2d world)
I aiming later (after fixing this problem) to position the camera to follow my player.
Note: I know my camera is kinda fake and its just change which part of the map texture to draw but there is no other way to do it .
A:
Looking at your code, it looks like your camera actually moves the physics objects in the world. This is not a common approach. It's hard to judge what you do with the visual objects, but it seems like you only move the position where they are rendered, and not their logical world position, is that correct?
In any case, the pattern I use when creating cameras, is keeping the camera offset in the camera, and only applying it to the sprite objects when rendering the level. This way the world simulation keeps running just fine, and the rendering code is also nicely decoupled from the movement code.
So, you would move your camera just like you currently are, but don't apply the offset to the objects in your world. Instead, in your rendering function for the level, do something like the following:
void Level::Render()
{
auto cameraOffset = m_Camera->GetOffset();
for (auto& object : m_Objects)
{
Sprite* sprite = object->GetSprite();
sprite->SetPosition(object->GetWorldPosition() + cameraOffset);
Renderer::RenderSprite(sprite);
}
if (Globals::DoDebugRendering)
{
for (auto& geometry : m_Geometry)
{
Renderer:RenderShapeAt(geometry, geometry->GetOrigin() + cameraOffset);
}
}
}
So just to clarify, the goal is to keep the position changes caused by the camera totally visual, and unrelated to the objects' positions in the game world.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to react on submit in Page_Load?
i have many radio buttons:
<asp:RadioButtonList ID="selectedYesNoQuestionBlock1" runat="server" RepeatDirection="Horizontal"
OnSelectedIndexChanged="Question1GotAnswered" AutoPostBack="true">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:RadioButtonList>
<asp:RadioButtonList ID="selectedYesNoQuestionBlock2" runat="server" RepeatDirection="Horizontal"
AutoPostBack="true" OnSelectedIndexChanged="Question2GotAnswered">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:RadioButtonList>
etc.
for each radio button i have their method:
protected void Question1GotAnswered(object sender, EventArgs e)
{}
i want to react on this in Page_Load before method Question1GotAnswered() will be called. i'am trying it but everything is unsuccessuful.
tried something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (sender.ToString() == "Question1GotAnswered")
{}
}
please help i need it much!
A:
The only way to do it is to check the if (Request.Form["__EVENTTARGET"] == control.ClientID) { } to see that the control posting back is the given control that caused the postback. So this should be the ID of your radio button causing the postback.
HTH.
| {
"pile_set_name": "StackExchange"
} |
Q:
Two data sets on R line graph, but using same X and Y axis?
I'm trying to plot two lines on a graph in R. The data is related to death row, with the CSV having three columns: first column is the year, second is death row population and third column is the number of executions that year.
I've gotten to the point where I can draw two lines with the X-axis the same, but the Y is messed up as the range of values overlap each other.
As an example, each given year is like this:
...
Year: 1968 Population: 1244 Executions: 34
Year: 1969 Population: 1456 Executions: 11
...
Note the big difference between population and executions.
I've been running this:
deathrow <- read.csv("death_row_by_year.csv", sep=",", header=T)
plot(deathrow$Year, deathrow$Population, type="l", col="red")
par(new=T)
plot(deathrow$Year, deathrow$Executions, type="l", col="green")
Anyway I can plot the execution numbers using the Y axis from plotting population?
A:
Here is how I would do it:
deathrow <- read.csv("death_row_by_year.csv", sep=",", header=T)
plot(range(deathrow$Year, na.rm=T), range(c(deathrow$Population, deathrow$Executions)), na.rm=T), type='n')
lines(deathrow$Year, deathrow$Population, col="red")
lines(deathrow$Year, deathrow$Executions, col="green")
The most important piece here is the call to plot with type='n', so there is no point plotted but the axis are set up to the right limits. Arguably, you may also specify these limits with xlim=range(...) and ylim=range(...) in the calls to lines.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to avoid loops to make this code faster?
Is there a way to avoid loops to make this code faster ?
"var" is the desired result.
"AA" and "BB" are vectors whose values are known.
The four principal lines of this code are based on the logic: 00,01,10,11 ( 0 for <= and 1 for > )
for i=3:1:2000
for j=1:50011
if AA(i) == j && BB(i)<=BB(i-1) && BB(i-1)<=BB(i-2)
var(i)=j;
else
if AA(i) == j && BB(i)<=BB(i-1) && BB(i-1)>BB(i-2)
var(i)=j+50011;
else
if AA(i) == j && BB(i)>BB(i-1) && BB(i-1)<=BB(i-2)
var(i)=j+2*50011;
else
if AA(i) == j && BB(i)>BB(i-1) && BB(i-1)>BB(i-2)
var(i)=j+3*50011;
end
end
end
end
end
end
A:
I managed to vectorize your code into one line of code! Going from a couple of seconds down to under a millisecond:
out = [0 0 AA(3:end) + ([1 2] * (diff(BB(hankel(1:3, 3:numel(BB)))) > 0)).*50011];
To understand how to get there, let's incrementally improve the original code.
1)
First we start with the double-loop you have:
tic
var0 = zeros(size(AA));
for i=3:numel(AA)
for j=1:N
if AA(i) == j && BB(i)<=BB(i-1) && BB(i-1)<=BB(i-2)
var0(i)=j;
else
if AA(i) == j && BB(i)<=BB(i-1) && BB(i-1)>BB(i-2)
var0(i)=j+50011;
else
if AA(i) == j && BB(i)>BB(i-1) && BB(i-1)<=BB(i-2)
var0(i)=j+2*50011;
else
if AA(i) == j && BB(i)>BB(i-1) && BB(i-1)>BB(i-2)
var0(i)=j+3*50011;
end
end
end
end
end
end
toc
2)
As @SpamBot noted, the nested if/else statements can be simplified by chaining them instead. Also you're evaluating the same test AA(i)==j multiple times. If the test is false, the whole for-loop is skipped. So we can eliminate this second for-loop, and directly use j=AA(i).
Here is new the code:
tic
var1 = zeros(size(AA));
for i=3:numel(AA)
j = AA(i);
if BB(i)<=BB(i-1) && BB(i-1)<=BB(i-2)
var1(i) = j;
elseif BB(i)<=BB(i-1) && BB(i-1)>BB(i-2)
var1(i) = j + 50011;
elseif BB(i)>BB(i-1) && BB(i-1)<=BB(i-2)
var1(i) = j + 2*50011;
elseif BB(i)>BB(i-1) && BB(i-1)>BB(i-2)
var1(i) = j + 3*50011;
end
end
toc
This is a huge improvement, and the code will run in a fraction of the original time. Still we can do better...
3)
As you mentioned in your question, the if/else conditions correspond to the pattern 00, 01, 10, 11 where 0/1 or false/true are the results of performing a binary x>y test over adjacent numbers.
Using this idea, we get the the following code:
tic
var2 = zeros(size(AA));
for i=3:numel(AA)
val = (BB(i) > BB(i-1)) * 10 + (BB(i-1) > BB(i-2));
switch (val)
case 00
k = 0;
case 01
k = 50011;
case 10
k = 2*50011;
case 11
k = 3*50011;
end
var2(i) = AA(i) + k;
end
toc
4)
Let's replace that switch statement with a table-lookup operation. This gives us this new version:
tic
v = [0 1 2 3] * 50011; % 00 01 10 11
var3 = zeros(size(AA));
for i=3:numel(AA)
var3(i) = AA(i) + v((BB(i) > BB(i-1))*2 + (BB(i-1) > BB(i-2)) + 1);
end
toc
5)
In this final version, we can get rid of the loop entirely by noting that each iteration accesses the slice BB(i-2:i) in a sliding-window manner. We can neatly use the hankel function to create a sliding window over BB (each returned as a column).
Next we use diff to perform vectorized comparisons, then map the resulting 0/1 of the two tests as [0 1 2 3]*50011 values. Lastly we add the vector AA appropriately.
This gives us our final one-liner, completely vectorized:
tic
var4 = [0, 0, AA(3:end) + ([1 2] * (diff(BB(hankel(1:3, 3:numel(BB)))) > 0)).*50011];
toc
Comparison
To verify the above solutions, I used the following random vectors as testing data:
N = 50011;
AA = randi(N, [1 2000]);
BB = randi(N, [1 2000]);
assert(isequal(var0,var1,var2,var3,var4))
I get the following times matching the solutions in the order presented:
>> myscript % tested in MATLAB R2014a
Elapsed time is 1.663210 seconds.
Elapsed time is 0.000111 seconds.
Elapsed time is 0.000099 seconds.
Elapsed time is 0.000089 seconds.
Elapsed time is 0.000417 seconds.
>> myscript % tested in MATLAB R2015b (with the new execution engine)
Elapsed time is 2.816541 seconds.
Elapsed time is 0.000233 seconds.
Elapsed time is 0.000158 seconds.
Elapsed time is 0.000157 seconds.
Elapsed time is 0.000339 seconds.
Hope this post wasn't too long, I just wanted to show how to tackle this type of problems by making incremental changes.
Now take your pick at which solution you like best :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why isn't the Transition Altitude depicted on SID charts?
Why isn't the Transition Altitude depicted on SID charts?
I would assume it would be a relevant information to be presented on this type of chart.
A:
FAA
Because it is a fixed value at 18,000 feet.
ICAO-style and Jeppesen
They show the TA (and sometimes the TL) on SID charts.
ICAO Annex 4 confirms the depiction on SID charts (chapter 9):
9.9.4.1 The components of the established relevant air
traffic services system shall be shown.
(...)
5) transition altitude/height to the nearest higher 300 m or
1 000 ft;
| {
"pile_set_name": "StackExchange"
} |
Q:
Right to left languages - list of language options
I am redesigning setting options for mobile application. One of them is "edition" which includes many languages and also Right to Left languages. Currently it is in a list where LtR languages are aligned left but the other RtL languages are are aligned to the other side and it just looks sh*t. There is also flag to represent each edition. example:
[flag] International__________
[flag] America______________
[flag] India_________________
[flag]_________________עברית
My question is, would they understand if this was aligned left ? Should I be thinking of different solution for example making it into a grid ? How well do RtL languages read if they are aligned to the centre if it was to be made into a grid? The only thing I read about RtL languages is from the google material design doc that they published but it says nothing about when both RtL and LtR are displayed at the same time. Are there any other guidelines written for this ? Also if the user was to change the edition to Right to Left language edition, would they expect the other labels to be aligned right then ?
Thank you in advance
A:
Yes it's perfectly understandable, see wikipedia
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing XML android throwing exception
I am trying to parse the below XML in android but I am running into a problem:
<?xml version="1.0" encoding="utf-8"?>
<ServerInformation>
<ConnectionInfo>
<Command>ConnectToServer</Command>
</ConnectionInfo>
<Devices>
<Device>
<Hostname>Android1</Hostname>
<IP>127.0.0.1</IP>
<MAC>hello</MAC>
<TCPSocket>100</TCPSocket>
</Device>
<Device>
<Hostname>Android2</Hostname>
<IP>127.0.0.1</IP>
<MAC>helo1</MAC>
<TCPSocket>200</TCPSocket>
</Device>
</Devices>
</ServerInformation>
I don't need to find the value of everything in the XML. I am just checking the hostname and the IP but when it gets to the MAC it throws an exception.
Below is the code I am using to parse the XML:
try
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(xmlWriter.returnXmlOutput()));
int eventType = xpp.getEventType();
String tagName = xpp.getName();
while (eventType != XmlPullParser.END_DOCUMENT)
{
tagName = xpp.getName();
if (tagName != null)
{
if (tagName.equalsIgnoreCase("Command"))
{
Log.d("Command", xpp.nextText());
}
else if (tagName.equalsIgnoreCase("Hostname"))
{
Log.d("Hostname", xpp.nextText());
}
else if (tagName.equalsIgnoreCase("IP"))
{
Log.d("IP", xpp.nextText());
}
}
xpp.nextTag();
}
}
catch (Exception ex)
{
Log.e("XML Exception", ex.toString());
}
Below is the exception I am getting:
06-18 18:43:55.168: E/XML Exception(2134): org.xmlpull.v1.XmlPullParserException: unexpected type (position:TEXT hello@9:14 in java.io.StringReader@5271e300)
Thanks for any help you can provide!
A:
You need to use the getText method instead of nextText because you want the content of the tag, not the next text.
Also, use this format:
while (eventType != XmlPullParser.END_DOCUMENT){
tagName = xpp.getName();
if(eventType == XmlPullParser.START_TAG){
if (tagName != null){
if (tagName.equalsIgnoreCase("Command")){
Log.d("Command", xpp.getText());
}
...
}
}
eventType = xpp.next();
}
Add a root element, like <Configuration> that englobes the whole file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Call linked server procedure
If I call procedure on linked server, I get the following error:
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.
It works in SSMS, also it works with classic asp, but not here. I have found some similar questions, but no answer. And I wont(can't) connect directly to linked server and execute procedure locally. It must be executed as : myLinkedServer.Database.dbo.myProcedure
Any idea?
using (SqlCommand getOutput = new SqlCommand())
{
getOutput.CommandText = "myLinkedServer.Database.dbo.myProcedure";
getOutput.CommandType = CommandType.StoredProcedure;
getOutput.CommandTimeout = 300;
getOutput.Connection = conn;
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(getOutput))
{
da.AcceptChangesDuringFill = false;
da.Fill(exportData);//here error happened
conn.Close();
da.Dispose();
A:
I have found a solution:
getOutput.CommandText = "EXEC myLinkedServer.Database.dbo.myProcedure";
getOutput.CommandType = CommandType.Text;
When calling a procedure on linked server, command type should be as text.
| {
"pile_set_name": "StackExchange"
} |
Q:
Question on Measurable function on $L^P$
Let $(X,M,\mu)$ be a measure space, and let $p$ be number such that $1\le p < \infty$. Suppose $f_n, n \ge 1$, is a sequence of $M-$measuarable function on $X$ such that $f_n \rightarrow f$ $\mu-$almost everywhere on $X$. Suppose also that $|f_n(x)|\le g(x)$ for all $n\ge1$ and $x\in X$ , where $g\in L^p$.
How to prove that $\left\lVert f-f_n \right\rVert_p \rightarrow 0$ as $ n\rightarrow \infty$.
Any help appreciated.
A:
You can prove this like you prove LDCT: use the basic inequality $|a+b|^p \le 2^p(|a|^p + |b|^p)$ to obtain
$$
2^p |f_n|^p + 2^p |f|^p - |f_n - f|^p \ge 0.
$$
Since $|f_n| \le g$ almost everywhere and $f_n \to f$ almost everywhere, you also have $|f| \le g$ almost everywhere. Thus
$$2^{p+1} g^p - |f_n - f|^p \ge 0.
$$
Now apply the Fatou lemma:
$$
\int_X 2^{p+1} g^p \, d\mu = \int_X \lim_{n \to \infty} \left( 2^{p+1} g^p - |f_n - f|^p \right) \, d\mu \le \liminf_{n \to \infty} \int_X \left( 2^{p+1} g^p - |f_n - f|^p \right) \, d\mu.$$
Some basic properties of the liminf imply
$$\liminf_{n \to \infty} \int_X \left( 2^{p+1} g^p - |f_n - f|^p \right) \, d\mu = \int_X 2^{p+1} g^p \, d\mu - \limsup_{n \to \infty} \int_X |f_n - f|^p \, d\mu.$$
Thus
$$\limsup_{n \to \infty} \int_X |f_n - f|^p \, d\mu \le 0.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Solve Exponential Equation with square
Solve equality with square
$2^{2x}=7\cdot 2^{x+\sqrt{x-1}}+8\cdot 2^{2\sqrt{x-1}}$
$x-1\ge0 \\\sqrt{x-1}=t\ge0\Rightarrow x-1=t^2\Rightarrow x=t^2+1\\2^{2(t^2+1)}=7\cdot2^{t^2+1+t}+2^{3+2t}$
It looks very complicated and I don't know how to move it.
Is there a better way to approach this task?
A:
Hint
If $$2^x=a,2^{\sqrt{x-1}}=b$$
Now for real $y,2^y>0$
we have $$0=a^2-7ab-8b^2=(a-8b)(a+b)$$
So, $$2^x=2^{3+\sqrt{x-1}}$$
Set $\sqrt{x-1}=p\ge0\implies x=p^2+1$
Like Find all real numbers $x$ for which $\frac{8^x+27^x}{12^x+18^x}=\frac76$
as $2\ne\pm1$
$$\implies p^2+1=3+p\iff(p-2)(p+1)=0$$
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.