text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
MS SQL Server organization and memory
I have a MS SQL server that I've start working with and I think I have an idea on the organization of MS SQL Server but I'm not absolutely sure of that idea's correctness. In relation to this idea, I have a question about a memory setting that might be an issue if my assumptions are correct.
My assumptions:
I know you can have multiple SQL servers on a Host server and that they are connected to by SSMS as separate connections.
You can have multiple Databases under the given server.
The host server has 24GB of RAM. From what I can tell, there is only one MS SQL server running. Under this SQL Server there are several databases.
While digging around in the settings I found a setting that set the "Maximum server memory (in MB)" to 8192MB.
Based on my assumptions that the databases are not separate "servers", would
it be correct to say that all of those databases are sharing the 8192MB of RAM?
A:
Based on my assumptions that the databases are not separate "servers", would it be correct to say that all of those databases are sharing the 8192MB of RAM?
That's Right..
You are assigning memory to an instance of sqlserver(multiple instances can coexist in same box) and databases share memory available to them
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS media queries ( media screen )
I have the following queries on my WordPress theme, and they are alot ;/
I am new to WordPress so i can't understand them correctly, but i am sure i will understand your explanation .
here is what I don't understand.
1: I don't understand for which screen's they are.
2: I don't understand what the "max" ( this one is very strange )
3: will the max width terminate the setting or something ? because we have min 600 and max 600
here is the code.
A:
1) screen here means the screen of the device itself (not a print as print is the common one). But this has same effect as
@media (min-width: 312px)
Just you are specifying that you want the max-width of the screen on that the website loaded, that's it
2) the max means the maximum width of the device screen to which the following styles are applied.
for eg:
@media screen and (max-width: 768px){
//These styles will apply only if the screen size is less than or equal to 768px
}
3) There is no termination. If you have max and min with 600px, then the styles will applied as per the position of the code. The code that comes below will apply (if min code is at line number 10 and max code at line number 20 then max will work)
| {
"pile_set_name": "StackExchange"
} |
Q:
reading a long type from a text file in Java
i'm trying to read long types from a text file with using readLine() method of BufferedReader class and then i parse the first token (which is long type number) with using StringTokenizer but i'm facing with an exception error which is java.lang.NumberFormatException
this is an example of my text file;
2764841629 Quaroten Ilen
1398844030 Orden Nenama
1185252727 Inja Nenaptin
2370429126 Quaren Inaja
1502141743 Otin Una
1993687334 Quarwennaja Nenoten
1015934104 Polen Meritna
2363674760 Otja Ie
1904629749 Neninin Ordja
3047965620 Algnaja Nenja
here is the code i read from a text file and assing the long value to my long variable
private void registerData() throws FileNotFoundException{
try {
String regPatName;
String regPatSurname;
long regPatID;
FileInputStream fis = new FileInputStream("src\\assignment_3\\injuredPersonList.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while( ( line = reader.readLine() ) != null) {
StringTokenizer st = new StringTokenizer(line, " ");
while(st.hasMoreTokens()){
regPatID = Long.parseLong(st.nextToken());
regPatName = st.nextToken();
regPatSurname = st.nextToken();
Patient regPatient = new Patient(regPatName, regPatSurname, regPatID);
hashMethod(regPatient);
}
}
} catch (IOException ex) {
Logger.getLogger(personTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void hashMethod(Patient regPatient){
Long idPat = new Long(regPatient.getPatientID());
int keyID;
keyID = (int) Math.sqrt(Integer.parseInt(idPat.toString().substring(0, 5) + idPat.toString().substring(5, 10))) % (50000);
System.out.println(keyID);
}
and finally this the error which i'm facing;
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "2481765933 Otna"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:419)
at java.lang.Long.parseLong(Long.java:468)
at assignment_3.personTest.registerData(personTest.java:58)
at assignment_3.personTest.<init>(personTest.java:33)
at assignment_3.personTest$1.run(personTest.java:161)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
i will be very appreciated if you can help me and also thanks anyway.
A:
Clearly you're trying to parse a non-numeric string, the stack trace shows it: 2481765933 Otna. You should split the input and parse the numeric part, something like this:
String[] data = line.split("\\s+");
regPatID = Long.parseLong(data[0]);
regPatName = data[1];
regPatSurname = data.length == 3 ? data[2] : "";
The above is much simpler than using StringTokenizer. In fact, the usage of StringTokenizer is discouraged, practically deprecated - nowadays, the preferred way to parse a string is either using the split() method for simple cases or the Scanner class for complex cases.
A:
You probably have a tab character instead of spaces to separate your fields. Add the tab to your set of delimiters (" \t").
Also, always close your streams and readers in a finally block (only the outermost one must be closed: closing the BufferedReader will close the InputStreamReader, which will close the FileInputStream).
A:
You are using the wrong delimiter (" ") since your text file may contain more than one space character between tokens. StringTokenizer is a legacy class, don't use it unless you have a good reason to. String.split() should suffice:
String[] result = line.split("\\s+");
regPatID = Long.parseLong(result[0]);
regPatName = result[1];
regPatSurname = result[2];
But I think that Scanner is the best fit for your problem:
// Java 7 try-with-resources synthax.
// If you are using Java <=6, declare a finally block after the catch
// to close resources.
try (InputStream myFile = ClassLoader.getSystemResourceAsStream("MyTextFile.txt");
Scanner sc = new Scanner(myFile)) {
while (sc.hasNext()) {
regPatID = sc.nextLong();
regPatName = sc.next();
regPatSurname = sc.next();
System.out.printf("%d - %s %s\n", regPatID, regPatName, regPatSurname);
}
} catch (Exception e) {
// Do something about exceptions
}
Both versions correctly parses your example input.
Here is a third fully working Java 6 Version.
| {
"pile_set_name": "StackExchange"
} |
Q:
Idiomatic way in F# to establish adherence to an interface on type rather than instance level
What's the most idiomatic way in F# to deal with the following. Suppose I have a property I want a type to satisfy that doesn't make sense on an instance level, but ideally I would like to have some pattern matching available against it?
To make this more concrete, I have defined an interface representing the concept of a ring (in the abstract algebra sense). Would I go for:
1.
// Misses a few required operations for now
type IRing1<'a when 'a: equality> =
abstract member Zero: 'a with get
abstract member Addition: ('a*'a -> 'a) with get
and let's assume I'm using it like this:
type Integer =
| Int of System.Numerics.BigInteger
static member Zero with get() = Int 0I
static member (+) (Int a, Int b) = Int (a+b)
static member AsRing
with get() =
{ new IRing1<_> with
member __.Zero = Integer.Zero
member __.Addition = Integer.(+) }
which allows me to write things like:
let ring = Integer.AsRing
which then lets me to nicely use the unit tests I've written for verifying the properties of a ring. However, I can't pattern match on this.
2.
type IRing2<'a when 'a: equality> =
abstract member Zero: 'a with get
abstract member Addition: ('a*'a -> 'a) with get
type Integer =
| Int of System.Numerics.BigInteger
static member Zero with get() = Int 0I
static member (+) (Int a, Int b) = Int (a+b)
interface IRing2<Integer> with
member __.Zero = Integer.Zero
member __.Addition with get() = Integer.(+)
which now I can pattern match, but it also means that I can write nonsense such as
let ring = (Int 3) :> IRing2<_>
3.
I could use an additional level of indirection and basically define
type IConvertibleToRing<'a when 'a: equality>
abstract member UnderlyingTypeAsRing : IRing3<'a> with get
and then basically construct the IRing3<_> in the same way as under #1.
This would let me write:
let ring = ((Int 3) :> IConvertibleToRing).UnderlyingTypeAsRing
which is verbose but at least what I'm writing doesn't read as nonsense anymore. However, next to the verbosity, the additional level of complexity gained doesn't really "feel" justifiable here.
4.
I haven't fully thought this one through yet, but I could just have an Integer type without implementing any interfaces and then a module named Integer, having let bound values for the Ring interfaces. I suppose I could then use reflection in a helper function that creates any IRing implementation for any type where there is also a module with the same name (but with a module suffix in it's compiled name) available? This would combine the benefits of #1 and #2 I guess, but I'm not sure whether it's possible and/or too contrived?
Just for background: Just for the heck of it, I'm trying to implement my own mini Computer Algebra System (like e.g. Mathematica or Maple) in F# and I figured that I would come across enough algebraic structures to start introducing interfaces such as IRing for unit testing as well as (potentially) later for dealing with general operations on such algebraic structures.
I realize part of what is or isn't possible here has more to do with restrictions on how things can be done in .NET rather than F#. If my intention is clear enough, I'd be curious to here in comments how other functional languages work around this kind of design questions.
A:
Regarding your question about how can you implement Rings in other functional languages, in Haskell you will typically define a Type Class Ring with all Ring operations.
In F# there are no Type Classes, however you can get closer using inline and overloading:
module Ring =
type Zero = Zero with
static member ($) (Zero, a:int) = 0
static member ($) (Zero, a:bigint) = 0I
// more overloads
type Add = Add with
static member ($) (Add, a:int ) = fun (b:int ) -> a + b
static member ($) (Add, a:bigint) = fun (b:bigint) -> a + b
// more overloads
type Multiply = Multiply with
static member ($) (Multiply, a:int ) = fun (b:int ) -> a * b
static member ($) (Multiply, a:bigint) = fun (b:bigint) -> a * b
// more overloads
let inline zero() :'t = Zero $ Unchecked.defaultof<'t>
let inline (<+>) (a:'t) (b:'t) :'t= (Add $ a) b
let inline (<*>) (a:'t) (b:'t) :'t= (Multiply $ a) b
// Usage
open Ring
let z : int = zero()
let z': bigint = zero()
let s = 1 <+> 2
let s' = 1I <+> 2I
let m = 2 <*> 3
let m' = 2I <*> 3I
type MyCustomNumber = CN of int with
static member ($) (Ring.Zero, a:MyCustomNumber) = CN 0
static member ($) (Ring.Add, (CN a)) = fun (CN b) -> CN (a + b)
static member ($) (Ring.Multiply, (CN a)) = fun (CN b) -> CN (a * b)
let z'' : MyCustomNumber = zero()
let s'' = CN 1 <+> CN 2
If you want to scale up with this approach you can have a look at FsControl which already defines Monoid with Zero (Mempty) and Add (Mappend). You can submit a pull request for Ring.
Now to be practical if you are planning to use all this only with numbers why not use GenericNumbers in F#, (+) and (*) are already generic then you have LanguagePrimitives.GenericZero and LanguagePrimitives.GenericOne.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jest how to modify the global object value for each unit test
I'm writing unit tests that require the window.location.href to be defined
The first unit test is created as follows
describe('myMethod()', () => {
beforeEach(() => {
global.window = Object.create(window);
Object.defineProperty(window, 'location', {
configurable: true,
value: {
href: 'http://localhost:7777/mainPoint?param=val1',
},
});
});
it('should call with val1', () => {
myMethod();
expect(myService.detectURLCall).toHaveBeenCalledWith('http://localhost:7777/mainPoint?param=val1'); // passes
});
describe('mySecondMethod()', () => {
beforeEach(() => {
global.window = Object.create(window);
Object.defineProperty(window, 'location', {
configurable: true,
value: {
href: 'http://localhost:7777/mainPoint?param=val2',
},
});
});
it('should call with val2', () => {
myMethod();
expect(myService.detectURLCall).toHaveBeenCalledWith('http://localhost:7777/mainPoint?param=val2'); // fails, the received call was ending with =val1
})
I know that the jest unit tests run in parallel, I tried doing clearMocks() in an afterEach() inside myMethod() test suite but it did not help and my second test suit still detects what we defined in the first one..
A:
The following looks to be a good solution for your issue:
https://github.com/simon360/jest-environment-jsdom-global
(built on top of jest's built-in jest-environment-jsdom, and has a good readme that directly relates)
This ensures that you have one defined environment per file, which would definitely be the root issue as you said.
| {
"pile_set_name": "StackExchange"
} |
Q:
Synchronized thread method is executing concurrently - why?
I have one question about thread. I have following Thread class and creating 2 thread objects.
public class MyThread extends Thread{
String name="";
public MyThread(String string) {
name=string;
}
@Override
public void run() {
callMe();
}
synchronized private void callMe() {
System.out.println("Started");
for (int i = 1; i <= 5; i++) {
System.out.println(name+" = "+i);
}
}
public static void main(String[] args) {
MyThread a = new MyThread("A");
MyThread b = new MyThread("B");
a.start();
b.start();
}
}
When I execute this , output I get is -
Started
Started
B = 1
B = 2
A = 1
A = 2
B = 3
A = 3
B = 4
A = 4
B = 5
A = 5
I know that A and B are printed randomly as Thread Scheduler picks it up.
But my question is: why loop is NOT executed one after other? I have used synchronized keyword.
A:
Your synchronized method is effectively:
private void callMe() {
synchronized(this) {
System.out.println("Started");
for (int i = 1; i <= 5; i++) {
System.out.println(name+" = "+i);
}
}
}
Now you've created two different instances, so this will be different for each thread... so they're not synchronizing against each other. If you want to see two threads working with the same monitor, you could rewrite your code like this:
public final class DemoRunnable implements Runnable {
@Override
public synchronized void run() {
System.out.println("Started");
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " = " + i);
}
}
public static void main(String[] args) {
Runnable runnable = new DemoRunnable();
Thread a = new Thread(runnable, "A");
Thread b = new Thread(runnable, "B");
a.start();
b.start();
}
}
Then you'll get output like this:
Started
A = 1
A = 2
A = 3
A = 4
A = 5
Started
B = 1
B = 2
B = 3
B = 4
B = 5
(Although it could be the other way round, of course.)
We still have two threads, but they're calling a synchronized method on the same object (a DemoRunnable in this case) so one will have to wait for the other to complete.
A few points:
Implementing Runnable is generally preferred over extending Thread; it's more flexible
Synchronizing on a Thread object has its own issues, as the Thread class does it itself; try to avoid it
Personally I don't like synchronizing on this anyway - I would usually have a private final variable of type Object to represent a monitor that only my code knows about... that way I can easily see all the code that could synchronize on it, which makes it easier to reason about
A:
Synchronized works per Object. To synchronize across instances you need a shared object to synchronize on.
I.e.
private final static Object globalLock = new Object();
// Later
private void callMe() {
synchronized (globalLock) {
System.out.println("Started");
for (int i = 1; i <= 5; i++) {
System.out.println(name+" = "+i);
}
}
}
A:
Your Code is equal to this Code
private void callMe(){
synchronized(this){
System.out.println("Started");
for (int i = 1; i <= 5; i++) {
System.out.println(name+" = "+i);
}
}
}
You just synchronise to the current Object.
If you want to synchronise them to each other your need to synchronise to the class,
like this :
private void callMe(){
synchronized(MyThread.class){
System.out.println("Started");
for (int i = 1; i <= 5; i++) {
System.out.println(name+" = "+i);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting a page of results from IndexedDb using cursor
I'm trying to learn how to use IndexedDb and my next step is getting a page of results from a store. My strategy is to store the last key retrieved for the page in the service and use it to open the cursor using that key as the lower bound on the next request. Here is the function as I originally defined it:
service.getListPage = function(store, pageSize) {
pageSize = pageSize || 15;
var deferred = $q.defer();
//called on cursor open success event
var getPage = function (cursorEvent) {
var page = [];
var cursor = cursorEvent.target.result;
if (cursor) {
for (var i = 0; i < pageSize; i++) {
page.push(cursor.value);
cursor.continue();
}
lastKeyOnPage[store] = cursor.key;
deferred.resolve(page);
} else {
deferred.resolve([]);
}
}
var transaction = service.db.transaction([store], "readonly");
var objectStore = transaction.objectStore(store);
var cursor;
if (lastKeyOnPage.hasOwnProperty(store) && lastKeyOnPage[store]) {
cursor = objectStore.openCursor(IDBKeyRange.lowerBound(lastKeyOnPage[store]));
} else {
cursor = objectStore.openCursor();
}
cursor.onsuccess = getPage;
return deferred.promise;
}
If I tried to use this function with only one item in the store, I ran into two problems:
The continue function would throw an error (so I used a try/catch, resolving the array of values in the catch block)
The cursor would return the same value, pageSize times (so I tried checking if the primary key in the current loop iteration matched the last one)
This still isn't working, though. There are now two items in the store, and if I call this function, it gets the first item, and then throws an error saying the cursor is either iterating or past its end.
Am I missing something about how this is supposed to work? I would just use getAll, but this is for a Cordova application and that method is not available. How can I just grab a certain number of results?
A:
I figured it out. The specification doesn't make it totally obvious, but the onsuccess event handler is called after calling cursor.continue(), so there is no need for an explicit loop. The fixed method looks like this:
var pageFunction = function(store, pageSize, direction) {
pageSize = pageSize || defaultPageSize;
var deferred = $q.defer();
var counter = pageSize;
var page = [];
if (!keys[store]) {
keys[store] = {};
}
//query function
var getPage = function (cursorEvent) {
var cursor = cursorEvent.target.result;
if (cursor && (counter < 0 || counter--)) {
if (direction) {
if (counter == pageSize - 1) {
keys[store][direction == "prev" ? first : last] = cursor.key;
}
keys[store][direction == "prev" ? last : first] = cursor.key;
}
page.push(cursor.value);
cursor.continue();
}
}
var transaction = service.db.transaction([store], "readonly");
var objectStore = transaction.objectStore(store);
var rangeStart = null;
if (direction) {
var bound = direction == "prev" ? upperBound : lowerBound;
rangeStart = keys[store].first
? IDBKeyRange.bound(keys[store].first)
: null;
}
var cursor = objectStore.openCursor(rangeStart, direction);
cursor.onsuccess = getPage;
transaction.oncomplete = function () { deferred.resolve(q(page)); }
return deferred.promise;
}
var pageAvailability = function(bound) {
var deferred = $q.defer();
var transaction = service.db.transaction([store], "readonly");
var objectStore = transaction.objectStore(store);
var countRequest = objectStore.count();
cursor.onsuccess = function (response) {
deferred.resolve(response > 0);
}
return deferred.promise;
}
service.prevPage = function (store, pageSize) {
return pageFunction(store, pageSize, "prev");
}
service.hasPrev = function (store) {
return pageAvailability(IDBKeyRange.upperBound(keys[store].last));
}
service.hasNext = function() {
return pageAvailability(IDBKeyRange.lowerBound(keys[store].first));
}
service.nextPage = function(store, pageSize) {
return pageFunction(store, pageSize, "next");
}
service.thisPage = function(store, pageSize) {
return pageFunction(store, pageSize);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Как сделать заголовки QTableWidget редактируемыми?
Я хочу чтобы пользователь мог изменять заголовки прямо в программе. Думал сделать через QTableWidgetItem но это не сработало.
title=QTableWidgetItem()
title.setFlags(Qt.ItemIsEditable)
self.start.table.setHorizontalHeaderItem(1,title)
A:
QTableWidget::setHorizontalHeaderItem(int column, QTableWidgetItem *item)
Устанавливает горизонтальный элемент заголовка для столбца столбца в item.
QTableWidgetItem::setText(const QString &text)
Устанавливает item's text в указанный text.
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Dialog(QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.tableWidget = QTableWidget(2, 3)
self.tableWidget.setHorizontalHeaderLabels(["A", "B", "C"])
self.lineEdit_0 = QLineEdit()
self.lineEdit_1 = QLineEdit()
self.lineEdit_2 = QLineEdit()
lay = QGridLayout(self)
lay.addWidget(self.tableWidget, 0, 0, 1, 3)
lay.addWidget(self.lineEdit_0, 1, 0)
lay.addWidget(self.lineEdit_1, 1, 1)
lay.addWidget(self.lineEdit_2, 1, 2)
lay.addWidget(QPushButton("New Header 0", clicked=self.onClick), 2, 0)
lay.addWidget(QPushButton("New Header 1", clicked=self.onClick), 2, 1)
lay.addWidget(QPushButton("New Header 2", clicked=self.onClick), 2, 2)
def onClick(self):
sender = self.sender()
if sender.text() == "New Header 0":
title = QTableWidgetItem() # <---
title.setText(self.lineEdit_0.text()) # <---
self.tableWidget.setHorizontalHeaderItem(0, title) # <---
elif sender.text() == "New Header 1":
item = QTableWidgetItem()
item.setText(self.lineEdit_1.text())
self.tableWidget.setHorizontalHeaderItem(1, item)
elif sender.text() == "New Header 2":
item = QTableWidgetItem()
item.setText(self.lineEdit_2.text())
self.tableWidget.setHorizontalHeaderItem(2, item)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = Dialog()
w.resize(340, 200)
w.exec_()
Update
Я бы хотел чтобы заголовки редактировались как и ячейки:двойной щелчёк мышкой и пишешь прямо в заголовке.
Класс QHeaderView предоставляет строку заголовка или столбец заголовка для представлений элементов.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class HeaderView(QtWidgets.QHeaderView):
def __init__(self, parent):
super(HeaderView, self).__init__(QtCore.Qt.Horizontal, parent)
self.m_labels = []
self.sectionResized.connect(self.adjustPositions)
self.sectionCountChanged.connect(self.onSectionCountChanged)
self.parent().horizontalScrollBar().valueChanged.connect(self.adjustPositions)
@QtCore.pyqtSlot()
def onSectionCountChanged(self):
while self.m_labels:
label = self.m_labels.pop()
label.deleteLater()
for i in range(self.count()):
label = QtWidgets.QLineEdit(self)
label.setStyleSheet("QLineEdit { color: red; font-size: 12px; }")
self.m_labels.append(label)
self.update_data()
self.adjustPositions()
def setModel(self, model):
super(HeaderView, self).setModel(model)
if self.model() is not None:
self.model().headerDataChanged.connect(self.update_data)
def update_data(self):
option = QtWidgets.QStyleOptionHeader()
self.initStyleOption(option)
for i, label in enumerate(self.m_labels):
text = self.model().headerData(
i, self.orientation(), QtCore.Qt.DisplayRole
)
label.setText(str(text))
pal = label.palette()
bc = self.model().headerData(
i, self.orientation(), QtCore.Qt.BackgroundRole
)
if bc is None:
bc = option.palette.brush(QtGui.QPalette.Window)
pal.setBrush(QtGui.QPalette.Window, bc)
fc = self.model().headerData(
i, self.orientation(), QtCore.Qt.ForegroundRole
)
if fc is None:
fc = option.palette.brush(QtGui.QPalette.ButtonText)
pal.setBrush(QtGui.QPalette.ButtonText, fc)
label.setPalette(pal)
textAlignment = self.model().headerData(
i, self.orientation(), QtCore.Qt.TextAlignmentRole
)
if textAlignment is None:
textAlignment = self.defaultAlignment()
label.setAlignment(textAlignment)
def updateGeometries(self):
super(HeaderView, self).updateGeometries()
self.adjustPositions()
@QtCore.pyqtSlot()
def adjustPositions(self):
for index, label in enumerate(self.m_labels):
geom = QtCore.QRect(
self.sectionViewportPosition(index),
0,
self.sectionSize(index),
self.height(),
)
geom.adjust(2, 0, -2, 0)
label.setGeometry(geom)
class Dialog(QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.tableWidget = QTableWidget(2, 3)
header = HeaderView(self.tableWidget)
self.tableWidget.setHorizontalHeader(header)
header_labels = []
for i in range(self.tableWidget.columnCount()):
header_label = "Column-{}".format(i)
header_labels.append(header_label)
self.tableWidget.setHorizontalHeaderLabels(header_labels)
lay = QGridLayout(self)
lay.addWidget(self.tableWidget)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = Dialog()
w.resize(340, 150)
w.exec_()
| {
"pile_set_name": "StackExchange"
} |
Q:
About basic commands in bash (cp, cd,..)
I am trying to learn basic commands in the terminal. I have a couple of quick questions. I know that to make a file and place it in a specific folder, one needs to create the directory and then use touch to create an empty file and place it there by mv:
mkdir folder/sub
touch file.txt
mv file.txt folder/sub
Could we somehow chain these things together and use touch to create a file and place it in a specific directory in just one line?
and then if I am in a sub-directory, in order to get back from there (say: folder/sub) to my home, either of these three commands would work (cd, cd -, cd ..) I am not sure I get the differences among the three. I get that cd .. takes you back one step up but the other two seem to work exactly the same.
and let's say I have already a text file in my home directory named file.txt. If I write this in shell it overrides that existing file:
cp folder/sub/file.txt ~/
How would I go about this if I wanted to keep both files?
A:
You can pass a relative or absolute path in any folder to and command, including touch (although the folder must exist):
touch folder/sub.file.txt
cd - switches to the folder you were last in (like a "Back" button)
. means the current directory
.. means the parent directory
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between having and not having parenthesis in if statements
In the python, the if statement can have parentheses or not like this:
if True:
pass
if (True):
pass
Is there any difference at all, even a performance difference, between these?
A:
As the compiled byte codes show,
>>> from dis import dis
>>> dis(compile("if True: pass", "string", "exec"))
1 0 LOAD_NAME 0 (True)
3 POP_JUMP_IF_FALSE 9
6 JUMP_FORWARD 0 (to 9)
>> 9 LOAD_CONST 0 (None)
12 RETURN_VALUE
>>> dis(compile("if (True): pass", "string", "exec"))
1 0 LOAD_NAME 0 (True)
3 POP_JUMP_IF_FALSE 9
6 JUMP_FORWARD 0 (to 9)
>> 9 LOAD_CONST 0 (None)
12 RETURN_VALUE
there is no difference between them at all. There are two things which I can think of.
You may want to use parens when you want to logically group conditions. For example,
if 10/5 == 2 and 2*5 == 10:
pass
would look better as
if (10/5 == 2) and (2*5 == 10):
pass
You can make the conditions more like English sentences by avoiding parens wherever possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysql count left join strange result
Can someone help me to understand those results ? (For me all 3 should return 6455).
(Using RDS mysql-8.0.13)
SELECT COUNT(p.product_id) FROM product p LEFT JOIN product_attributes pa ON p.pdt_id = pa.pdt_id WHERE pa.code = 'season';
Results : 6332
SELECT COUNT(*) FROM product p;
Results : 6455
SELECT COUNT(p.product_id) FROM product p LEFT JOIN product_attributes pa ON p.pdt_id = pa.pdt_id AND pa.code = 'season';
Results : 6455
A:
Your first join uses the WHERE clause, this mean sit selected all the rows, including those with a null join and then filters out those WHERE the pa.code = season, i.e. the null joins.
The last one joins on both, but because it is a left join you still get the full table of results, and nothing is filtered because you remove the WHERE clause. If you were to use an INNER JOIN in the last query you should get the same result (6332).
This link might be useful What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a difference in performance whether I put the trailing comma in array, or not?
In Thinking in Java book 4th edition I read, that leaving the comma after the last object in list makes automatic generating such lists easier, but it is optional. On the other hand here, in Java SE Specifications I can read, that trailing comma is ignored. On StackOverflow questions I read that it makes code easier to maintain. But I would like to ask you if it makes any difference for the JVM work? I deduce that it's only a good practice, am I right? If there is no difference in performance, should I use it as default? Which version is used in practice more frequently?
Here is sample code to show the problem:
Integer[] arrFst = new Integer[]{new Integer(1), new Integer(2), };
Integer[] arrSnd = new Integer[]{new Integer(1), new Integer(2) };
Thank you for your answers.
A:
In Thinking in Java book 4th edition I read, that leaving the comma after the last object in list makes automatic generating such lists easier, but it is optional.
Correct.
On the other hand here, in Java SE Specifications I can read, that trailing comma is ignored.
Correct, but there's no 'on the other hand' about it. It's ignored. By the compiler. There is no conflict between the above two statements.
On StackOverflow questions I read that it makes code easier to maintain.
Correct again.
But I would like to ask you if it makes any difference for the JVM work?
No, because it's ignored by the compiler, so the JVM doesn't even get to see it.
I deduce that it's only a good practice, am I right?
It's an optional practice that is useful in certain situations.
If there is no difference in performance, should I use it as default?
No, why?
Which version is used in practice more frequently?
That isn't answerable without a complete survey of all the Java code in existence, or enough of it to constitute a statistically significant sample. And in any case you should do what is best for you, not what everybody does statistically speaking.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I output the Devel query log?
Is it possible to output the Devel generated query log in some way? By default, it prints to the bottom of the page which is fine until I need to send the results to someone else to review.
A:
The devel module has an option to log the query times into the database, and you can then run your own analysis on this and do whatever you like with it.
This is something to be careful about as it is a lot of data and can add up quickly. However, for more sophisticated/aggregate analysis, it's quite useful.
After enabling query logging, you can see some results at http://yoursite.com/devel/queries
A:
The solution I came up with was to view the source on the page and to copy the query log <div> out and paste it into an html file. I then used Firebug to take out to copy the relevant css and add it to the html file as well. What ended up with was one, reasonably formatted, .html file that I could send to whoever needed to look at the query log. Not a particularly elegant solution but it served my purposes.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to return DB (database/sql) type in golang?
I use Go with PostgreSQL using github.com/lib/pq.
I want to call this opendb() function in other functions but I'm having problem with the return value.
package database
import (
"fmt"
"database/sql"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "pgpassword"
dbname = "postgres"
)
func opendb() (*DB) {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s " +
"sslmode=disable", host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
return db
}
If you run this:
$ go run main.go
It will show this error:
error:
undefined: DB
A:
the return datatype should be *sql.DB
changing
func opendb() (*DB) {
to
func opendb() (*sql.DB) {
should work
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I Pass Selected items from one page to another page in asp.net mvc
In my index page, i have multiple checkboxes that can be selected:
@foreach (var item in Model) {
<tr>
<td class ="text-nowrap">
<input class="chkSelect" type="checkbox" name="Selected" value="@item.Id">
</td>
<td>
@Html.ValueFor(modelItem => item.trandate, "{0:dd/MM/yyyy}")
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id })
</td>
</tr>
}
I need to get the selected items and pass them to another form/page /action where i want to use the ids of the selected item to perform other actions.
How do i pass the selected items to the controller action of the other page ?
so , now i created public ActionResult SendSMS(string[] msisdn)
{
return View();
}
and
@using (Html.BeginForm("SendSMS", "Subscribers", FormMethod.Post))
{
<div class="form-group">
<a href="@Url.Action("SendSMS", "Subscriber", new { msisdn = Request["Selected"] })"> <span class="btn btn-primary"> <i class="fa fa-envelope"></i> Send SMS</span> </a>
</div>
}
So, will Request["Selected"] hold all the selected items? it appears null when debugging.
A:
I was able to get this done by simply using a submit button. and
and in the controller action SendSMS i have :
if (Request["Selected"] != null)
{
model.msisdn = string.Empty;
model.MessageId = string.Empty;
foreach (var selection in Request["Selected"].Split(','))
{
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
MVC Razor - If condition shows up in html render
In below code(the first Div) I need to Put if condition based on which different buttons will be visible. I did this but it results in below issue (see pic below). We can't put if conditions in DIV ? Please suggest a way to do this. Thanks!
<td style="text-align:center; vertical-align:middle">
<div class="editDelGLCode">
if(@Model.Tables["PM_GLCode"].Rows[0]["InfoRefID"].ToString().Trim().Length == 0)
{
<button type="button" class="btn OOrange" onclick="editGLCode(this);">
<i class="fas fa-plus-circle"></i> Add New
</button>
}
else
{
<a href="#" title="Edit" onclick="editGLCode(this);"><i class="fas fa-edit"></i></a>
}
</div>
<div class="saveCanGLCode" style="display:none">
<span id="UpdateOSaveGLCode"> <a href="#" title="Save" onclick="addOrUpdateOGlcode(this);"><i class="fas fa-save"></i></a></span>
<span> </span>
<span><a href="#" title="Cancel" onclick="cancelRowGLCode();"><i class="fas fa-times"></i></a></span>
</div>
<div class="hdnPM_GLCode" style="display:none;">
@if (Model.Tables["PM_GLCode"].Rows.Count > 0)
{ @Model.Tables["PM_GLCode"].Rows[0]["BSAInfoRefID"]}
</div>
</td>
A:
Change This line of Code from :
if(@Model.Tables["PM_GLCode"].Rows[0]["InfoRefID"].ToString().Trim().Length == 0)
To
@if(Model.Tables["PM_GLCode"].Rows[0]["InfoRefID"].ToString().Trim().Length == 0)
As @ has to be added for the code logic starts
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do I not get compiler warning about access uninitialized member variable in ctor?
Here is a simple test case that compiles without any warning. Looks like a common mistake but clang, gcc and visual studio doesn't emit warning in this case. Why?
class Image {
private:
int width, height;
int* array;
public:
Image(int _width, int _height);
void crashTest();
};
Image::Image(int _width, int _height)
{
array = new int[width * height];
// ^^^^^ ^^^^^^ this is wrong
// I expect a warning here e.g.: 'width is uninitialized here'
width = _width;
height = _height;
}
void Image::crashTest()
{
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
array[x + y * width] = 0;
}
}
int main()
{
const int ARRAY_SIZE = 1000;
Image image(ARRAY_SIZE, ARRAY_SIZE);
image.crashTest();
return 0;
}
e.g.:
g++ -Wall -Wextra -O2 -Wuninitialized test.cpp
clang++ -Wall -Wextra -O2 -Wuninitialized test.cpp
gives me no warning
A:
A follow-up to this old question: You can get the warning you are looking for with g++ by enabling warnings from "Effective C++" with -Weffc++. This will complain about member variables that are not explicitly initialised.
This is possibly too aggressive in that it will also complain about class members with default constructors that are not explicitly initialised.
I have not seen an equivalent option for Clang -- I agree a warning about classes with uninitialised primitive data members would be very useful.
A:
Short Answer
As pointed out in the comments, reading from an uninitialized variable is undefined behavior. Compilers are not obligated by the standard to provide a warning for this.
(In fact, as soon as your program expresses undefined behavior, the compiler is effectively released from any and all obligations...)
From section [defns.undefined] of the standard (emphasis added):
undefined behavior
behavior for which this International Standard imposes no requirements
[ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed. —end note ]
Long Answer
This can be a difficult situation for a compiler to detect (and if it does detect it, it's difficult to inform the user about it in some useful way).
Your code only exhibits undefined behavior because it's trying to read from uninitialized member variables width and height. The fact that they're member variables is one of the things that can make this situation tricky to diagnose.
With local variables, the static analysis involved in detecting this can be relatively straightforward (not all the time, mind you).
For example, it's very easy to see the problem here:
int foo()
{
int a;
int b = 0;
return a + b; // Danger! `a` hasn't been initialized!
}
How about in this scenario:
int foo(int& a)
{
int b = 1;
return a + b; // Hmm... I sure hope whoever gave me `a` remembered to initialize it first
}
void bar()
{
int value;
int result = foo(value); // Hmm... not sure if it matters that value hasn't been initialized yet
}
As soon as we start dealing with variables whose scope extends beyond a single block, it's very difficult to detect whether or not a variable has been initialized.
Now, relating this back to the problem at hand (your question): the variables width and height are not local to the constructor - they could have been initialized outside the constructor.
For example:
Image::Image(int _width, int _height)
{
Initialize();
array = new int[width * height]; // Maybe these were initialized in `Initialize`...
width = _width;
height = _height;
}
Image::Initialize()
{
width = 0;
height = 0;
}
Should the compiler emit a warning in this scenario?
After some cursory analysis we can conclusively say "no, it shouldn't warn", because we can see that the Initialize method does indeed initialize the member variables in question.
But what if Initialize delegates this to another method MoreInitialize()? And that method delegates it to another method YetEvenMoreInitialize? This begins to look like a problem that we can't reasonably expect the compiler to solve.
| {
"pile_set_name": "StackExchange"
} |
Q:
Encode a URL for proper characters
I have a URL that looks like below:
https://www.xyz.net/test%3Fkey%3Dvalue
How do I encode it to look like below:
https://www.xyz.net/test?key=value
I guess I need to use the URL Encoding techniques or?
A:
java.net.URLDecoder.decode(resourceURL, "UTF-8") is the answer!
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between association and dependency?
In a UML class diagram, what is the difference between an association relationship and a dependency relationship?
From what I know, an association is a stronger relationship than a dependency, but I'm not sure how it is stronger.
Any example would be more than welcome :)
A:
An association almost always implies that one object has the other object as a field/property/attribute (terminology differs).
A dependency typically (but not always) implies that an object accepts another object as a method parameter, instantiates, or uses another object. A dependency is very much implied by an association.
A:
What is the difference between dependency and association?:
In general, you use an association to represent something like a field
in a class. The link is always there, in that you can always ask an
order for its customer. It need not actually be a field, if you are
modeling from a more interface perspective, it can just indicate the
presence of a method that will return the order's customer.
To quote from the 3rd edition of UML Distilled (now just out) "a
dependency exists between two elements if changes to the definition of
one element (the supplier) may cause changes to the other (the
client)". This is a very vague and general relationship, which is why
the UML has a host of stereotypes for different forms of dependency.
In code terms, such things as naming a parameter type and creating an
object in a temporary variable imply a dependency.
...
A:
In OOP terms:
Association --> A has-a C object (as a member variable)
Dependency --> A references B (as a method parameter or return type)
public class A {
private C c;
public void myMethod(B b) {
b.callMethod();
}
}
There is also a more detailed answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Integer matrix visualization in Julia
How to convert a random integer matrix into an image with colored grids?
I tried to using convert(Image, rand(Int,3,3)) after viewing a tutorial for Juno-LT, but I got
julia> using Images
julia> convert(Image, rand(Int,3,3))
ERROR: UndefVarError: Image not defined
Stacktrace:
[1] top-level scope at none:0
A:
The tutorial you gave a link to is quite old. In Images.jl, images are simply arrays. There is no constructor with the name Image anymore.
using Images, ImageView
# this will show an image in which the highest value
# of the array is white and the lowest is black
imshow(rand(Int, 3, 3))
It is better to take a look at the official documentation of the packages of JuliaImages, specifically, the section Arrays, Numbers and Colors.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I compare Excel files? OleDbDataAdapter doesn't read string column in Excel tab?
Our Excel 2013 xlsx file has tab "DEPTS" and this tab has a column called "1F/3F". Each cell in this column can have one of these values: "5", "Ati_3", "4", "Btu_4", etc.
Before today, I would move the contents of this tab to a dataset with this straightforward snippet. The dataset viewer would display all rows and all columns:
string connectionString = string.Format(ExcelConnstring, FileName);
string deptsSql = string.Format("SELECT * FROM [{0}$]", "DEPTS");
DataSet deptsDataset = new DataSet();
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(deptsSql, con);
adapter.Fill(deptsDataset);
con.Close();
}
return deptsDataset;
Today, I try to upload today's file, which is the same exact format. When I look at the contents of the dataset, I notice that the cells in column "1F/3F" that are not numerical are empty. It's reading all 40 rows, but those particular cells whose values could be "Ati_3", "Btu_4" (ie. not numeric) are being read as empty. The numeric values are being read correctly.
How can I compare an older file with this file? The file seems to be correct, and I have no idea how to check if something was added to that particular column that would cause the error.
Thanks.
A:
The ADO.NET driver uses the data in each column (the first 10 rows or so) to determine its datatype, which is terrible but it is what it is. If you have a column which has numeric values in the first 10 or so rows, the driver treats that as a numeric column and will read any non-numeric values as null.
Cell formats in the excel document are not honored by the driver. If you want to ensure that the data is read as text, and you have control over the process that generates the excel document, you can force the column to be treated as text by inserting 10 or so dummy values (e.g. 'Ignore') and throw away those rows after you have read the contents.
By ensuring that the first 10 rows of a column contain text, the driver will correctly read the numeric and non-numeric values for that column (they will all be treated as text).
If you cannot control the creation of the file you are going to read you could switch to another technology to read the Excel document. Some alternatives include:
EPPlus (http://epplus.codeplex.com/) - safe to use on a server
Office Automation - not safe to use on a server
| {
"pile_set_name": "StackExchange"
} |
Q:
Google analytics events in behavior section not showing up
in my site i have google analytics tag coded it works in real-time but when i go to behavior nothing show up.. it says there is only one event, in the graph section but down in the report section there's nothing.
![sample][1]
A:
If you are using GA free, please be advised that the data will be visible in reports within 24-72 hrs. If you see the data in real-time reports, be assured it will show up in the reports in due time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pixels in photoshop vs pixels in CSS?
I notice that when I measure out something in Photoshop to "ensure pixel perfection" it's usually half of what's measured in Photoshop to go to CSS. So if I measure at 60px, in CSS it goes to 30px.
But only roughly so.. Is there a way to make sure it matches 100% so I don't have to guesstimate? And why does this happen?
A:
When you are measuring out those pixels in Photoshop, you have to make sure you know what size your resolution is. For the web, it uses 72 dpi resolution, check in Photoshop under "image size" to see what resolution your image is. Sometimes images are at 300 dpi which if you use that and then try to save on the web will make the image larger than it should be.
| {
"pile_set_name": "StackExchange"
} |
Q:
Выдает в прямом смысле код на странице, вместо его исполнения
Есть код:
jQuery('document').ready(function() {
$("button").click(function() {
if ($(".sent_1") == "right") {
$(".sent_1").animate({
color: 'red'
});
}
if ($(".sent_2") == "wrong") {
$(".sent_2").animate({
color: 'red'
});
}
if ($(".sent_3") == "wrong") {
$(".sent_3").animate({
color: 'red'
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="/jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="/textcolors.js"></script>
<meta charset="utf-8" http-equiv="ContentType" content="text/html">
<title>Выполните задания</title>
</head>
<body>
<form method="POST" action="textcolors.js">
<div class="exercise_sentences">
<label for='first' class="sent_1">first(+)</label>
<input type="text" name="fi">
<label for='second' class="sent_2">second(-)</label>
<input type="text" name="se">
<label for='third' class="sent_3">third(-)</label>
<input type="text" name="th">
<input class="button" type="submit" name="check" value="Проверить">
</div>
</form>
</body>
</html>
Когда нажимаю на кнопку, хочу, чтобы при правильном ответе текст горел зеленым, а при не правильном - красным. Когда нажимаю кнопку - выдает просто текст ровно тот же что в textcolors.js, вместо того, чтобы выполнить его. (Подключал jQuery путем копипаста в jquery-3.0.0.min.js соотв версии.) Мне хотя бы узнать - что не так?
A:
Вот пример рабочего кода. В action пишут не ссылку на код, который должен выполниться, а ссылку на "серверный" файл, которому будут переданы данные. Обычно это php файл.
В теге label в атрибуте for нужно указать ссылку на id поля ввода, т.е. они должны совпадать.
Чтобы узнать значение поля на jq нужно применять метод val().
JQ не будет анимировать нечисловые значения. Писать color: red некорректно.
jQuery('document').ready(function() {
$("input[type='button']").click(function(e) {
e.preventDefault();
if ($("input[name='first']").val() === "right") {
$(".sent_1").css("color", "red");
}
if ($("input[name='second']").val() === "wrong") {
$(".sent_2").css("color", "red");
}
if ($("input[name='third']").val() === "wrong") {
$(".sent_3").css("color", "red");
}
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta charset="utf-8" http-equiv="ContentType" content="text/html">
<title>Выполните задания</title>
</head>
<body>
<form>
<div class="exercise_sentences">
<label for='first' class="sent_1">first(+)</label>
<input type="text" id="first" name="first">
<label for='second' class="sent_2">second(-)</label>
<input type="text" id="second" name="second">
<label for='third' class="sent_3">third(-)</label>
<input type="text" id="third" name="third">
<input class="button" type="button" name="check" value="Проверить">
</div>
</form>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I show or download pdf files inside a Flutter_webview?
I want to open or download a PDF-File inside my webview. I tried to enableFilesURl inside the webview community version but it doesn´t work.
Best regards
Falk
A:
Future<File> createFileOfPdfUrl({String urlP = ''}) async {
final url = urlP;
String filename = '${DateTime.now().microsecondsSinceEpoch}';
var request = await HttpClient()?.getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
String dir = (await getApplicationDocumentsDirectory()).path;
File file = new File('$dir/$filename');
await file.writeAsBytes(bytes);
return file;
}
.
.
createFileOfPdfUrl(urlP: '${jsonRes['m']}').then((res) {
Navigator.push(context, MaterialPageRoute(builder: (context) => PDFScreen(res.path)));
});
.
.
.
class PDFScreen extends StatelessWidget {
String pathPDF = "";
PDFScreen(this.pathPDF);
@override
Widget build(BuildContext context) {
return PDFViewerScaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios),
),
centerTitle: true,
title: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
"PDF",
style: TextStyle(
fontSize: 16,
color: Theme.of(context).accentColor,
),
),
Text("Önizleme", style: TextStyle(color: Theme.of(context).accentTextTheme.subtitle.color, fontSize: 14)),
],
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.share),
onPressed: () {
Share.share('$pathPDF');
},
),
],
),
path: pathPDF);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to update the value in a VC when a tab is selected from a UITabbarController?
I have a tabbar controller. When the user clicks on one of the tab bar buttons, I need to update a value in the UIPageViewController that is in the target view controller.
I am trying to use a delegate to inform a UIPageViewController which tab bar button was clicked:
protocol PlanTypeDelegate {
func setIntro(thisFlow planType: UITabBarItem)
}
class NewTabBarController: UITabBarController {
var planTypeDelegate : PlanTypeDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// create and handle tab bar button actions
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
planTypeDelegate?.setIntro(thisFlow: item)
}
In my UIPageController I have the following:
class IntroPageController: UIPageViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let tabbar = self.parent as? NewTabBarController() else { return }
tabbar.delegate = self
}
}
extension IntroPageController : PlanTypeDelegate {
func setIntro(thisFlow planType: UITabBarItem) {
print("this item:\(planType)")
}
}
Instead I get this error message:
I am new to passing data between VCs so I have no idea how to go about handling this scenario.
EDIT
Same error after update
A:
You can Achieve it like this.. without Delegate ... write setIntro method in IntroPageController i hope it will solve your Issue
class NewTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
}
func tabBarController(_ tabBarController: UITabBarController,
shouldSelect viewController: UIViewController) -> Bool{
if let controller = viewController as? IntroPageController {
controller.setIntro(thisFlow: tabBarController.tabBarItem)
}
return true
}
You can also achieve it through Protocol for that write... All controllers who confirm PlanTypeDelegate can perform action against this method
func tabBarController(_ tabBarController: UITabBarController,
shouldSelect viewController: UIViewController) -> Bool{
if let navController = viewController as? UINavigationController {
if let myViewController = navController.topViewController , let homeController = myViewController as? PlanTypeDelegate {
homeController.setIntro(thisFlow: tabBarController.tabBarItem)
}
} else if let controller = viewController as? PlanTypeDelegate {
controller.setIntro(thisFlow: tabBarController.tabBarItem)
}
return true
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring Boot Kotlin API returns 404 response for all endpoints
I'm using Spring Boot with Kotlin . The rest controller returns 404 error for all endpoints. In the starting logs the endpoints in the controller are not present. Any endpoint returns the same 404 response.
These are the steps I have tried,
Tried clearing cache/target
Moved all classes into single directory
Tried adding ComponentScan annotation but it is not accepted.
I'm using cmd line to run the project
Same output seen when running java -jar $jarfile
Checked annotations Repository , Service , RestController
Controller:
package com.example.controller
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.RequestBody
import Cricketer
import CricketerRepository
import CricketerService
import org.springframework.web.bind.annotation.RequestMapping
@RestController
@RequestMapping("/api")
class CricketerController(private val cricketerService: CricketerService , private val cricketerRepository: CricketerRepository){
@GetMapping("/cricketers/{id}")
fun getCricketer(@PathVariable("id") id: Long):ResponseEntity<Cricketer> {
val cricketer = cricketerService.findById(id)
return ResponseEntity<Cricketer>(cricketer as Cricketer, HttpStatus.OK);
}
@GetMapping("/cricketers/")
fun getAllCricketers() :ResponseEntity<List<Cricketer>> {
var cricketersList: ArrayList<Cricketer> = cricketerService.getAllPlayers() as (ArrayList<Cricketer>)
return ResponseEntity<List<Cricketer>>(cricketersList, HttpStatus.OK)
}
@PostMapping("/cricketer/")
fun addCricketer(@RequestBody cricketer:Cricketer):ResponseEntity<Cricketer> {
val cCricketer : Cricketer = Cricketer(name = cricketer.name
, country = cricketer.country
, highestScore = cricketer.highestScore)
cricketerRepository.save(cCricketer)
return ResponseEntity<Cricketer>(cricketer , HttpStatus.OK)
}
@PutMapping("/cricketer/{id}")
fun updateCricketer(@PathVariable("id") id: Long, @RequestBody cricketer: Cricketer ):ResponseEntity<Cricketer> {
val cCricketer = Cricketer(name = cricketer.name
, country = cricketer.country
, highestScore = cricketer.highestScore)
cricketerRepository.save(cCricketer)
return ResponseEntity<Cricketer>(cricketer, HttpStatus.OK)
}
@DeleteMapping("/cricketer/{id}")
fun deleteCricketer(@PathVariable("id") id:Long ):ResponseEntity<String> {
val cCricketer :Cricketer = cricketerService.findById(id) as Cricketer
cricketerRepository.delete(cCricketer)
return ResponseEntity<String>("cricketer removed", HttpStatus.OK)
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>Spring-Kotlin-Rest-API</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring-Kotlin-Rest-API</name>
<description>Spring Boot Kotlin REST API Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<kotlin.version>1.2.41</kotlin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
<jvmTarget>1.8</jvmTarget>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
Startup logs
2018-05-21 22:31:19.490 INFO 3061 --- [ main] c.e.d.SpringKotlinRestApiApplicationKt : Starting SpringKotlinRestApiApplicationKt on nirmal-desktop with PID 3061 (/home/nirmal/code/workspace-sts-3.9.1.RELEASE/Spring-Kotlin-Rest-API/target/classes started by root in /home/nirmal/code/workspace-sts-3.9.1.RELEASE/Spring-Kotlin-Rest-API)
2018-05-21 22:31:19.512 INFO 3061 --- [ main] c.e.d.SpringKotlinRestApiApplicationKt : No active profile set, falling back to default profiles: default
2018-05-21 22:31:19.592 INFO 3061 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@5bab7c16: startup date [Mon May 21 22:31:19 IST 2018]; root of context hierarchy
2018-05-21 22:31:29.492 INFO 3061 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$28d3b505] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-05-21 22:31:33.847 INFO 3061 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-05-21 22:31:34.312 INFO 3061 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-05-21 22:31:34.313 INFO 3061 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-05-21 22:31:34.389 INFO 3061 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2018-05-21 22:31:36.190 INFO 3061 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-05-21 22:31:36.190 INFO 3061 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 16602 ms
2018-05-21 22:31:36.560 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-05-21 22:31:36.564 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-21 22:31:36.566 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-21 22:31:36.566 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-21 22:31:36.566 INFO 3061 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-21 22:31:37.743 INFO 3061 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-05-21 22:31:39.038 INFO 3061 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-05-21 22:31:39.222 INFO 3061 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-05-21 22:31:39.480 INFO 3061 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-05-21 22:31:40.064 INFO 3061 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.2.17.Final}
2018-05-21 22:31:40.066 INFO 3061 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-05-21 22:31:40.302 INFO 3061 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-05-21 22:31:42.180 INFO 3061 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2018-05-21 22:31:44.235 INFO 3061 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@7d95eb4a'
2018-05-21 22:31:44.237 INFO 3061 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-05-21 22:31:44.688 INFO 3061 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-21 22:31:46.829 INFO 3061 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@5bab7c16: startup date [Mon May 21 22:31:19 IST 2018]; root of context hierarchy
2018-05-21 22:31:46.894 WARN 3061 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2018-05-21 22:31:47.072 INFO 3061 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-21 22:31:47.073 INFO 3061 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-21 22:31:47.121 INFO 3061 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-21 22:31:47.122 INFO 3061 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-21 22:31:49.030 INFO 3061 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-05-21 22:31:49.033 INFO 3061 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-05-21 22:31:49.047 INFO 3061 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-05-21 22:31:50.682 INFO 3061 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-05-21 22:31:50.695 INFO 3061 --- [ main] c.e.d.SpringKotlinRestApiApplicationKt : Started SpringKotlinRestApiApplicationKt in 34.697 seconds (JVM running for 49.043)
A:
I guess your CricketerController is not in a subpackage relative to your main class. So you basically have two options:
Place your main class directly under the package com.example
Add the annotation at the bottom of this answer to your main class.
Using any of these two methods makes the controller class visible for Spring at startup and therefore should create your mappings.
@ComponentScan(basePackages = { "com.example.controller"} )
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing SVG file - decomposing transformation matrix
I need to parse SVG (just the simples things) and only thing left to do is to properly extract position and angle from the matrix transformation. I know this question has been asked many times and I believe I have went through many of the answers, documents etc. but still cannot handle it proporly. Here's the simplest example I managed to prepare:
I have created 1000x1000 document (all numbers in px) and put a rectangle of 100x100 size at 100,100 position. It has generated the following piece of SVG file (I have removed style attrib. and parent tags). There's no other transformation anywhere in the file:
<rect
width="100"
height="100"
x="100"
y="100" />
Then I have rotated the rectangle by 33deg (with the 'transform' inkscape tool). The SVG code looks this:
<rect
width="100"
height="100"
x="-5.8952699"
y="157.49644"
transform="matrix(0.83867057,-0.54463904,0.54463904,0.83867057,0,0)" />
Now, my goal is to extract the position and angle from the matrix, so basically I'd like to get back the following values: x:100,y:100,angle:33. In order to do it, I have assumed the following formulas:
sx=sqrt(a^2+b^2)
sy=sqrt(c^2+d^2)
t=atan(c/d) OR t=atan(-b/a)
t=acos(a) if MATRIX is PURE
x' = tx + sx*(COS(t)*x-SIN(t)*y)
y' = ty + sy*(SIN(t)*x+COS(t)*y)
the result is:
t = 0.575958787 (which is 33deg) - PERFECTLY FINE
however
x'=-90.72230563 and y'=128.8770646
and this is exactly what totally confuses me - why it's not 100,100 ?
Please help, I have went through tons of forums, SVG W3C documentation and still cannot make it right.
Thank you,
Veedoo
A:
Step 1: Combine everything into a single matrix. This might be avoided, but it makes the subsequent discussion more uniform, since you won't have to worry about more than a single transformation. To get this matrix, combine the specified position (which is an implicit translation) with the given transformation matrix:
$$M=\begin{pmatrix}
0.83867057 & 0.54463904 & 0 \\
-0.54463904 & 0.83867057 & 0 \\
0 & 0 & 1\end{pmatrix}
\cdot\begin{pmatrix}
1 & 0 & -5.8952699 \\
0 & 1 & 157.49644 \\
0 & 0 & 1\end{pmatrix}\\
=\begin{pmatrix}
0.83867057 & 0.54463904 & 80.8345205177 \\
-0.54463904 & 0.83867057 & 135.298423247 \\
0 & 0 & 1\end{pmatrix}$$
Step 2: Identify rotation (and possiby scaling). The upper left $4\times4$ block of $M$ has the form
$$\begin{pmatrix}
s\cdot\cos\varphi & -s\cdot\sin\varphi \\
s\cdot\sin\varphi & s\cdot\cos\varphi
\end{pmatrix}$$
where $\varphi$ is the angle of rotation and $s$ is the global scale factor. You can therefore compute
\begin{align*}
s &= \sqrt{0.83867057^2 + 0.54463904^2} \approx 1 \\
\tan\varphi &= \frac{-0.54463904}{0.83867057} \\
\varphi &= \operatorname{atan2}(-0.54463904, 0.83867057)
= -0.575958656219877 \approx -33°
\end{align*}
So your scaling is negligible (and due to rounding errors), while your rotation is by the $33°$ you mentioned, but in the opposite direction as you might have thought, due to different conventions as to which direction is positive.
Step 3: Find center. The position $(100, 100)$ in the original document denoted the upper left corner of the rectangle. But as a first step, you should have a look at the center. The dimension of the rectangle is still given as $100\times100$. So take the point $(50,50)$ and apply $M$ to it.
$$\begin{pmatrix}
0.83867057 & 0.54463904 & 80.8345205177 \\
-0.54463904 & 0.83867057 & 135.298423247 \\
0 & 0 & 1\end{pmatrix}\cdot\begin{pmatrix}50\\50\\1\end{pmatrix}
\approx\begin{pmatrix}150\\150\\1\end{pmatrix}$$
So you now know that the center of the rectangle is located at $(150,150)$. From this and the original size, you can deduce that the original top left corner must have been $(100,100)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving that if $(X,\tau)$ is infinite, then $\exists S \subset X: S \cong (\Bbb N,\tau_1)$
So, in an exercise I'm asked to prove the following:
Let $X$ be an infinite set. Then, prove that $(X,\tau)$ has a subspace homeomorphic to $(\Bbb N,\tau_1)$, where either $\tau_1$ is the trivial topology or $(\Bbb N ,\tau_1)$ is a $T_0$ - space.
So I'm having some trouble solving this because I'm not sure how to prove this kind of statements. For example: Should I assume that $\tau_1$ is trivial and then show that there exists a subspace, and then assume that $(\Bbb N,\tau_1)$ is $T_0$ and show that there also exists?
Or should I say: Let $S$ be a subspace of $(X,\tau)$ and show that it is homeomorphic to one of the two?
I don't know if I'm being able to explain myself well, but my problem is not with the concepts and the content of the proof is more with the structure of the proof. What structure should a proof for this have? I do not wish for a complete proof of this statement, I only want some help setting up the structure for the proof.
A:
We've all been there. It's confusing at first, yes.
You need to show that for every topological space, some condition holds. Then we need to take an arbitrary topological space, and show the condition holds. So let $X$ be an arbitrary topological space.
So what's the condition? If $X$ is infinite, then blah. Great, so if $X$ that we took is not infinite, there's nothing to check. So we can assume that it is infinite. Namely, we have an arbitrary infinite topological space.
Now what? Now we need to show that it has a subspace homeomorphic to $\Bbb N$ with the trivial topological, or to some $T_0$ topology on $\Bbb N$. So we have two options:
If $X$ has a subspace homeomorphic to the trivial topology on $\Bbb N$, we are done. So let's assume it doesn't have one, and show that the other option holds. Or,
If $X$ has a subspace homeomorphic to $\Bbb N$ with some $T_0$ topology, we are done. So let's assume there are none, and show that the other option holds.
Which one you choose is up to you, and it will usually depend on what you know, and how easy it is to prove each option.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prevent Spring from instantiating certain beans during unit tests
The production applicationContext.xml defines several beans, seen below (mostly JMS resources) that are only relevant while deployed in production. The unit tests have mock implementations that completely bypass any JMS.
<jee:jndi-lookup id="jmsConnectionFactory" jndi-name="java:/JmsXA" resource-ref="false" proxy-interface="javax.jms.ConnectionFactory"/>
<jee:jndi-lookup id="myQueue" jndi-name="java:jboss/exported/jms/queue/myQueue"/>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="jmsConnectionFactory" />
</bean>
<bean id="myMessageHandler" class="com.example.MyMessageHandler" />
<bean id="jndiDestinationResolver" class="org.springframework.jms.support.destination.JndiDestinationResolver"/>
With the above in the main applicationContext.xml, I get the following exception during the tests since there is no JNDI container available.
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154)
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
at org.springframework.jndi.support.SimpleJndiBeanFactory.getBean(SimpleJndiBeanFactory.java:113)
Is it possible to tell Spring not to attempt to load those beans (whose ids I know) in the test applicationContext.xml? Or have a "null bean" since I know they will never be used? This would be less work than mocking them like in How to test a mocked JNDI datasource with Spring? .
A:
What I suggest in general is the following. Break up your context files into multiple files. Generally isolate the beans that should not be used during testing in a separate context file. Have a single context file that imports all the bean definition files.
For your test, only load the files with the beans that you need for the test. If you have a bean A that you need for the test and depends on bean B, use Springockito's @ReplaceWithMock to mock B and inject it into the context.
In your case I would suggest moving your jndi-lookup beans into a separate context and mocking / replacing jmsConnectionFactory or jmsTemplate (I would lean towards replacing jmsTemplate).
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculate total miles traveled from vectors of lat / lon
I have a data frame with data about a driver and the route they followed. I'm trying to figure out the total mileage traveled. I'm using the geosphere package but can't figure out the correct way to apply it and get an answer in miles.
> head(df1)
id routeDateTime driverId lat lon
1 1 2012-11-12 02:08:41 123 76.57169 -110.8070
2 2 2012-11-12 02:09:41 123 76.44325 -110.7525
3 3 2012-11-12 02:10:41 123 76.90897 -110.8613
4 4 2012-11-12 03:18:41 123 76.11152 -110.2037
5 5 2012-11-12 03:19:41 123 76.29013 -110.3838
6 6 2012-11-12 03:20:41 123 76.15544 -110.4506
so far I've tried
spDists(cbind(df1$lon,df1$lat))
and several other functions but can't seem to get a reasonable answer.
Any suggestions?
> dput(df1)
structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40), routeDateTime = c("2012-11-12 02:08:41",
"2012-11-12 02:09:41", "2012-11-12 02:10:41", "2012-11-12 03:18:41",
"2012-11-12 03:19:41", "2012-11-12 03:20:41", "2012-11-12 03:21:41",
"2012-11-12 12:08:41", "2012-11-12 12:09:41", "2012-11-12 12:10:41",
"2012-11-12 02:08:41", "2012-11-12 02:09:41", "2012-11-12 02:10:41",
"2012-11-12 03:18:41", "2012-11-12 03:19:41", "2012-11-12 03:20:41",
"2012-11-12 03:21:41", "2012-11-12 12:08:41", "2012-11-12 12:09:41",
"2012-11-12 12:10:41", "2012-11-12 02:08:41", "2012-11-12 02:09:41",
"2012-11-12 02:10:41", "2012-11-12 03:18:41", "2012-11-12 03:19:41",
"2012-11-12 03:20:41", "2012-11-12 03:21:41", "2012-11-12 12:08:41",
"2012-11-12 12:09:41", "2012-11-12 12:10:41", "2012-11-12 02:08:41",
"2012-11-12 02:09:41", "2012-11-12 02:10:41", "2012-11-12 03:18:41",
"2012-11-12 03:19:41", "2012-11-12 03:20:41", "2012-11-12 03:21:41",
"2012-11-12 12:08:41", "2012-11-12 12:09:41", "2012-11-12 12:10:41"
), driverId = c(123, 123, 123, 123, 123, 123, 123, 123, 123,
123, 456, 456, 456, 456, 456, 456, 456, 456, 456, 456, 789, 789,
789, 789, 789, 789, 789, 789, 789, 789, 246, 246, 246, 246, 246,
246, 246, 246, 246, 246), lat = c(76.5716897079255, 76.4432530414779,
76.9089707506355, 76.1115217276383, 76.2901271982118, 76.155437662499,
76.4115052509587, 76.8397977722343, 76.3357809444424, 76.032417796785,
76.5716897079255, 76.4432530414779, 76.9089707506355, 76.1115217276383,
76.2901271982118, 76.155437662499, 76.4115052509587, 76.8397977722343,
76.3357809444424, 76.032417796785, 76.5716897079255, 76.4432530414779,
76.9089707506355, 76.1115217276383, 76.2901271982118, 76.155437662499,
76.4115052509587, 76.8397977722343, 76.3357809444424, 76.032417796785,
76.5716897079255, 76.4432530414779, 76.9089707506355, 76.1115217276383,
76.2901271982118, 76.155437662499, 76.4115052509587, 76.8397977722343,
76.3357809444424, 76.032417796785), lon = c(-110.80701574916,
-110.75247172825, -110.861284852726, -110.203674311982, -110.383751512505,
-110.450569844106, -110.22185564111, -110.556956546381, -110.24483308522,
-110.217355202651, -110.80701574916, -110.75247172825, -110.861284852726,
-110.203674311982, -110.383751512505, -110.450569844106, -110.22185564111,
-110.556956546381, -110.24483308522, -110.217355202651, -110.80701574916,
-110.75247172825, -110.861284852726, -110.203674311982, -110.383751512505,
-110.450569844106, -110.22185564111, -110.556956546381, -110.24483308522,
-110.217355202651, -110.80701574916, -110.75247172825, -110.861284852726,
-110.203674311982, -110.383751512505, -110.450569844106, -110.22185564111,
-110.556956546381, -110.24483308522, -110.217355202651)), .Names = c("id",
"routeDateTime", "driverId", "lat", "lon"), row.names = c(NA,
-40L), class = "data.frame")
A:
How about this?
## Setup
library(geosphere)
metersPerMile <- 1609.34
pts <- df1[c("lon", "lat")]
## Pass in two derived data.frames that are lagged by one point
segDists <- distVincentyEllipsoid(p1 = pts[-nrow(df),],
p2 = pts[-1,])
sum(segDists)/metersPerMile
# [1] 1013.919
(To use one of the faster distance calculation algorithms, just substitute distCosine, distVincentySphere, or distHaversine for distVincentyEllipsoid in the call above.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Usage of Memento in pseudorandom number generator
I would like to ask, how exactly is used memento in pseudorandom number generator? I have high level knowledge of pseudorandom number generator but I don't see there any memento (even I read it's there). Thank you for your answer so much :)
A:
I believe you are talking about design pattern memento. If so, then in my opinion memento is used as the inner state of random number generator. First you create random number generator with particular seed (that is its state) and then you use this seed during the next random number generation. So using a standard memento terminology:
originator is random number generator,
caretaker is a caller who retrieves numbers by using random number generator,
memento is a state of random number generator based on which the next random value is created
Standard rand() in C++ does not support retrieving its state so the only restore operation is simply to store the seed you are setting via srand() at the beginning and then us it to restore generator to initial state.
However, you can reimplement it so it supports state querying and then subsequent restore to any, not only initial, state. For way how to achieve that see this SO answer. Also it is mentioned in the same thread that new c++11 random number generators offer this functionality by default.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java: Control thread speed / change delay of threads
I need some help with threads in java.
I'm currently working on a project, what compiles a class at runtime and invokes it's main method. The class represents a guy in a territory, which is visible as a canvas to the user.
This main method invokes some other methods. Either methods the user typed into an editor or predefined methods from a super class.
The editor content could look like this:
main() {
System.out.println("test users class main");
takeAll();
takeAll();
}
public void takeAll() {
for (int i = 0; i < 2; i++)
move();
takeHoney();
takeHoney();
takeHoney();
for (int i = 0; i < 2; i++)
move();
}
The above code is what the user later enters into an editor inside the GUI, which will be compiled when he uses a certain button. He is supposed to learn imperative programming.
The methods main, move and takeHoney are defined in a superclass and takeAll is a method defined by the user at runtime.
My program adds the class prefix and compiles the users class.
The user should be able to start, pause, resume, and terminate the main method by clicking some buttons in the GUI.
When I just run the main method all methods finish too fast. The user will only see the result, but not the steps and won't be able to interact while it's runnning.
So far I created a new runnable and started a thread.
protagonistMainMethodRunnable = new Runnable() {
@Override
public void run() {
protagonist.main();
terminateWasPressed();
}
};
//.....
Thread thread = new Thread(protagonistMainMethodRunnable);
thread.run();
"protagonist" is an instance of the users class, which was compiled at runtime.
I'm not very good with threads and can't find an idea to create a delay after each method call.
Does someone have an idea to create a delay after each method call in the main or even after every method call?
EDIT: The idea from James_D was very helpful. Here is the class that works for my use case:
public class OperationQueue {
private Queue<Runnable> operationQueue = new LinkedList<Runnable>();
private Timeline timeline;
public OperationQueue(double delay) {
timeline = null;
setDelay(delay);
}
public void setDelay(double seconds) { //careful: seconds > 0
if (timeline != null)
timeline.stop();
System.out.println("Set keyframe duration to " + seconds + " seconds.");
timeline = new Timeline(new KeyFrame(Duration.seconds(seconds), e -> {
if (!operationQueue.isEmpty()) {
operationQueue.remove().run();
}
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
public Queue<Runnable> getOperationQueue() {
return operationQueue;
}
public void add(Runnable queueItem) {
this.operationQueue.add(queueItem);
}
public void clearQueue() {
this.operationQueue.clear();
}
}
I moved the timeline to a setter method. In that way you can change the delay at runtime (with a slider for example).
A:
This is just an outline of how I might approach this, as the question really is too broad.
You are really asking how you can perform an animation that the user defines in code. (It's an animation because you are displaying a collection of frames, where each frame is defined by performing an operation, and there is a time gap between the operations.)
Consider creating a queue of operations to perform:
private class UI {
private Queue<Runnable> operationQueue = new LinkedList<Runnable>();
public Queue<Runnable> getOperationQueue() {
return operationQueue();
}
// ...
}
Now you can run an animation via a Timeline that periodically checks the queue, and if there's something in it, executes that operation:
public UI () {
// set up ui, etc...
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), e-> {
if (! operationQueue.isEmpty()) {
operationQueue.remove().run();
}
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
Now make your predefined basic methods private, and define public methods that submit those private methods to the queue:
public class BaseClass {
private final UI ui = ... ;
private void doMove() {
// implementation here...
}
public void move() {
ui.getOperationQueue().add(this::doMove);
}
private void doTakeHoney() {
// implementation here...
}
public void takeHoney() {
ui.getOperationQueue().add(this::doTakeHoney);
}
}
Note there is actually no threading here at all. Everything is on the FX Application Thread; the timing is controlled by the Timeline.
| {
"pile_set_name": "StackExchange"
} |
Q:
Lubridate mdy function
I'm trying to convert the following and am not successful with one of the dates [1]. "4/2/10" becomes "0010-04-02".
Is there a way to correct this?
thanks,
Vivek
data <- data.frame(initialDiagnose = c("4/2/10","14.01.2009", "9/22/2005",
"4/21/2010", "28.01.2010", "09.01.2009", "3/28/2005",
"04.01.2005", "04.01.2005", "Created on 9/17/2010", "03 01 2010"))
mdy <- mdy(data$initialDiagnose)
dmy <- dmy(data$initialDiagnose)
mdy[is.na(mdy)] <- dmy[is.na(mdy)] # some dates are ambiguous, here we give
data$initialDiagnose <- mdy # mdy precedence over dmy
data
initialDiagnose
1 0010-04-02
2 2009-01-14
3 2005-09-22
4 2010-04-21
5 2010-01-28
6 2009-09-01
7 2005-03-28
8 2005-04-01
9 2005-04-01
10 2010-09-17
11 2010-03-01
A:
I think this is occurring because the mdy() function prefers to match the year with %Y (the actual year) over %y (2 digit abbreviation for the year, defaulting to 19XX or 20XX).
There is a workaround, though. I took a look at the help files for lubridate::parse_date_time (?parse_date_time), and near the bottom of the help file, there is an example for adding an argument that prefers matching with the %y format over the %Y format for the year. The relevant bit of code from the help file:
## ** how to use `select_formats` argument **
## By default %Y has precedence:
parse_date_time(c("27-09-13", "27-09-2013"), "dmy")
## [1] "13-09-27 UTC" "2013-09-27 UTC"
## to give priority to %y format, define your own select_format function:
my_select <- function(trained){
n_fmts <- nchar(gsub("[^%]", "", names(trained))) + grepl("%y", names(trained))*1.5
names(trained[ which.max(n_fmts) ])
}
parse_date_time(c("27-09-13", "27-09-2013"), "dmy", select_formats = my_select)
## '[1] "2013-09-27 UTC" "2013-09-27 UTC"
So, for your example, you can adapt this code and replace the mdy <- mdy(data$initialDiagnose) line with this:
# Define a select function that prefers %y over %Y. This is copied
# directly from the help files
my_select <- function(trained){
n_fmts <- nchar(gsub("[^%]", "", names(trained))) + grepl("%y", names(trained))*1.5
names(trained[ which.max(n_fmts) ])
}
# Parse as mdy dates
mdy <- parse_date_time(data$initialDiagnose, "mdy", select_formats = my_select)
# [1] "2010-04-02 UTC" NA "2005-09-22 UTC" "2010-04-21 UTC" NA
# [6] "2009-09-01 UTC" "2005-03-28 UTC" "2005-04-01 UTC" "2005-04-01 UTC" "2010-09-17 UTC"
#[11] "2010-03-01 UTC"
And running the remaining lines of code from your question, it gives me this data frame as the result:
initialDiagnose
1 2010-04-02
2 2009-01-14
3 2005-09-22
4 2010-04-21
5 2010-01-28
6 2009-09-01
7 2005-03-28
8 2005-04-01
9 2005-04-01
10 2010-09-17
11 2010-03-01
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing SVG color via CSS, SVG color wont change
Heres my code:
HTML:
<img src="../img/icon-play.svg" class="play-button-svg">
SASS:
.play-button-svg
padding-left: 10px
fill: $white
The icon keep its original color and does not change to white.
A:
by using SVG as image or background image you cant control with CSS. If you want '.play-button-svg' to work, you should place SVG code which will look like-
<svg ...>
<path .../>
</svg>
Then apply class-
<svg ...>
<path class="play-button-svg" .../>
</svg>
and now your CSS will work :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Как динамически изменять величину шага приращения в QDoubleSpinBoxDelegate?
В приложении C++ есть таблица QTableWidget, где некоторые колонки связаны с QDoubleSpinBoxDelegate, но величина шага приращения задаётся в той же строке другой колонки через QComboBoxDelegate. Спрашивается - как при редактировании ячейки в QDoubleSpinBoxDelegate задать значение шага.
Сам делегат:
#ifndef DOUBLESPINBOXDELEGATE_H
#define DOUBLESPINBOXDELEGATE_H
#include <QObject>
#include <QItemDelegate>
#include <QDoubleSpinBox>
class DoubleSpinBoxDelegate : public QItemDelegate
{
Q_OBJECT
double minVal;
double maxVal;
double oneStep;
QString suffix;
public:
DoubleSpinBoxDelegate(QObject *parent = nullptr);
DoubleSpinBoxDelegate(QObject *parent, double min, double max, double step = 0.0001, QString suffix = "");
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setEditorData(QWidget *editor, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setStepSize(double step);
};
#endif // DOUBLESPINBOXDELEGATE_H
Реализация:
#include "doublespinboxdelegate.h"
DoubleSpinBoxDelegate::DoubleSpinBoxDelegate(QObject *parent)
{
minVal = 1.5;
maxVal = 29.9999;
}
DoubleSpinBoxDelegate::DoubleSpinBoxDelegate(QObject *parent, double min, double max, double step, QString suffix)
{
if (parent)
{
minVal = min;
maxVal = max;
oneStep = step;
this->suffix = suffix;
}
}
QWidget *DoubleSpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QDoubleSpinBox *editor = new QDoubleSpinBox (parent);
editor->setSuffix(tr(" MHz"));
editor->setDecimals (6);
editor->setMinimum(minVal);
editor->setMaximum(maxVal);
editor->setSingleStep(oneStep);
return (QWidget *) editor;
}
void DoubleSpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
double value = index.model()->data(index, Qt::EditRole).toDouble();
QDoubleSpinBox *dSpinBox = static_cast<QDoubleSpinBox*>(editor);
dSpinBox->setValue(value);
}
void DoubleSpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QDoubleSpinBox *dSpinBox = static_cast<QDoubleSpinBox*>(editor);
dSpinBox->interpretText();
double value = dSpinBox->value();
model->setData(index, value, Qt::EditRole);
}
void DoubleSpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
Понятно, что в методе createEditor, надо задавать значение oneStep, но как его прочесть из другой колонки таблицы в этой же строке?
A:
Если у вас настройки редактора зависят от данных, то лучше их выполнять в setEditorData. Так по моему логичней. Как это сделать наиболее правильно зависит от проекта, ниже перечислю варианты:
void DoubleSpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
double value = index.data(Qt::EditRole).toDouble();
QDoubleSpinBox *spin = dynamic_cast<QDoubleSpinBox*>(editor);
spin->setValue(value);
// можно обратиться прямо к модели, самый простой и быстрый вариант
// но делегат будет работать только с одной моделью
MyModel * model = dynamic_cast<MyModel*>(index.model());
auto step1 = model->getMySpinBoxStep();
// можно напрямую запросить нужную ячейку, чуть лучший вариант
// так как делегат будет зависеть от структуры модели
double step2 = index.model()->data(step_index, Qt::EditRole).toDouble();
// можно задать для этого отдельную роль, это наиболее идеоматичный
// способ так как типы делегата и модели связаны только через код роли
double step3 = index.data(MyStepRole).toDouble();
spin->setSingleStep(step2);
}
Напомню, что коды собственных ролей данных должны быть больше чем значение Qt::UserRole.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the simplest way to capitalize the first word in a sentence for multiple sentences in python 3.7?
For my homework I have tried to get the first word of each sentence to capitalize.
This is for python 3.7.
def fix_cap():
if "." in initialInput:
sentsplit = initialInput.split(". ")
capsent = [x.capitalize() for x in sentsplit]
joinsent = ". ".join(capsent)
print("Number of words capitalized: " + str(len(sentsplit)))
print("Edited text: " + joinsent)
elif "!" in initialInput:
sentsplit = initialInput.split("! ")
capsent = [x.capitalize() for x in sentsplit]
joinsent = "! ".join(capsent)
print("Number of words capitalized: " + str(len(sentsplit)))
print("Edited text: " + joinsent)
elif "?" in initialInput:
sentsplit = initialInput.split("? ")
capsent = [x.capitalize() for x in sentsplit]
joinsent = "? ".join(capsent)
print("Number of words capitalized: " + str(len(sentsplit)))
print("Edited text: " + joinsent)
else:
print(initialInput.capitalize())
This will work if only one type of punctuation is used, but I would like it to work with multiple types in a paragraph.
A:
Correctly splitting a text into sentences is hard. For how to do this correctly also for cases like e.g. abbreviations, names with titles etc., please refer to other questions on this site, e.g. this one. This is only a very simple version, based on your conditions, which, I assume, will suffice for your task.
As you noticed, your code only works for one type of punctuation, because of the if/elif/else construct. But you do not need that at all! If e.g. there is no ? in the text, then split("? ") will just return the text as a whole (wrapped in a list). You could just remove the conditions, or iterate a list of possible sentence-ending punctuation. However, note that capitalize will not just upper-case the first letter, but also lower-case all the rest, e.g. names, acronyms, or words previously capitalized for a different type of punctuation. Instead, you could just upper the first char and keep the rest.
text = "text with. multiple types? of sentences! more stuff."
for sep in (". ", "? ", "! "):
text = sep.join(s[0].upper() + s[1:] for s in text.split(sep))
print(text)
# Text with. Multiple types? Of sentences! More stuff.
You could also use a regular expression to split by all sentence separators at once. This way, you might even be ablt to use capitalize, although it will still lower-case names and acronyms.
import re
>>> ''.join(s.capitalize() for s in re.split(r"([\?\!\.] )", text))
'Text with. Multiple types? Of sentences! More stuff.'
Or using re.sub with a look-behind (note the first char is still lower-case):
>>> re.sub(r"(?<=[\?\!\.] ).", lambda m: m.group().upper(), text)
'text with. Multiple types? Of sentences! More stuff.'
However, unless you know what those are doing, I'd suggest going with the first loop-based version.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to log on the remote that Ansible was run?
I would like to log on the remote host each time an ansible-generated script was run. Ideally, I would like to see the full ansible command that was run. At a minimum it should log the time and which playbook was run.
I would like a history on each host when changes were made with Ansible.
Is there a reasonable way to do this?
A:
My problem was that logging on the remote host was disabled. The documentation states that the default is logging enabled. So it must have been disabled in the example config we started from.
I had to change no_target_syslog to false in ./config/ansible.cfg.
# TODO Deprecated option ?
# no_target_syslog = True
no_target_syslog = False
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to block git pulls/fetches?
in our project we have a jenkins job running from a remote master branch. Developers often rebase from this remote master to fetch the latests changes into their local copies.
What we want is to avoid this rebasing when the jenkins is broken (red or yellow ball). Instructions are "rebase only if jenkins is green" but... people are lazy :-)
So, can we do something in the jenkins job so that it blocks the git repo when the execution fails?
Best regards!
A:
It seems you are not verifying your commits before merging into your git repository instead verifying them after merged into git in frequent intervals of time.
I think there is no way we can disable git pull other than removing ssh-keys of all users from git repository, which is not feasible.
We can have a post build step in Jenkins which can manipulate authorized_keys file in Git to block access to git repo. ( I am not sure if it works)
We had a same scenario where each build+verification takes around 2 hours and we can't really enforce this test for each commit. But we were able to manage this situation.
If you are using gerrit:
Instead of using Jenkins Gerrit-trigger plugin, we can have our own script which will poll entire gerrit for changes which have all approvals and ready to merge and run your verification. Once verification succeeds all changes in that job will be merged(Submitted in Gerrit) automatically. With this we can avoid bad commits being merged.
If you are not using gerrit:
We can have two separate branches
Development branch ( where all developers push their changes)
Integration branch (from where developers can pull their changes)
All developers will push their changes to development branch and in frequent intervals we can verify development branch and push changes to integration branch only if verification succeeds.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert HashMap to Object containing list attributes
Is possible to convert this HashMap to the corresponding Object? Maybe using Jackson Object Mapper, Gson, or even Mapstruct. The trick here is how to map List attributes, that in my INPUT has a number as suffix in the attribute name:
Map<String, String> map = new HashMap<String, String>() {{
put("fooName", "foo name");
put("bars1.barName", "bar at position 0 name");
put("bars1.barValue", "bar at position 0 value");
put("bars2.barName", "bar at position 1 name");
put("bars2.barValue", "bar at position 1 value");
}};
public class Foo {
String fooName;
List<Bar> bars;
// getters/setters
}
public class Bar {
String barName;
String barValue;
// getters/setters
}
PS: this input comes from an external API call and I can't modify the source.
A:
You may use @JsonAnySetter annotation along with a map of Bar instances:
public class Foo {
String fooName;
private Map<Integer, Bar> map = new TreeMap<>();
// getters/setters
public String getFooName() {
return fooName;
}
public void setFooName(String fooName) {
this.fooName = fooName;
}
public List<Bar> getBars() {
return map.values().stream().collect(Collectors.toList());
}
@JsonAnySetter
public void bars(String key, String value) {
String[] ids = key.split("\\.");
if (ids[0].startsWith("bars")) {
Integer barKey = Integer.parseInt(ids[0].substring("bars".length())) - 1;
String field = ids[1];
Bar bar = map.computeIfAbsent(barKey, k -> new Bar());
if ("barName".equals(field)) {
bar.setBarName(value);
} else if ("barValue".equals(field)) {
bar.setBarValue(value);
}
map.put(barKey, bar);
} // else handle other properties
}
}
Test:
ObjectMapper m = new ObjectMapper();
Map<String, String> map = new HashMap<String, String>() {{
put("fooName", "foo name");
put("bars1.barName", "bar at position 0 name");
put("bars1.barValue", "bar at position 0 value");
put("bars2.barName", "bar at position 1 name");
put("bars2.barValue", "bar at position 1 value");
}};
String json = m.writerWithDefaultPrettyPrinter().writeValueAsString(map);
Foo foo = m.readValue(json, Foo.class);
System.out.println("reserialized = " + m.writerWithDefaultPrettyPrinter().writeValueAsString(foo));
output:
reserialized = {
"fooName" : "foo name",
"bars" : [ {
"barName" : "bar at position 0 name",
"barValue" : "bar at position 0 value"
}, {
"barName" : "bar at position 1 name",
"barValue" : "bar at position 1 value"
} ]
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Preload Image Without BuildContext
Is there a way to load images in Flutter in a function without access to a BuildContext?
Flutter can preload images with precacheImage() which requires a BuildContext and is inconvenient to use.
I would like to load images in the initState() method of a StatefulWidget which precacheImage() does not support.
There is an open issue about preloading images that suggests loading images without a BuildContext is not currently supported.
https://github.com/flutter/flutter/issues/26127
A:
I know two workarounds, first one is initstate "delayed" like so :
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var image;
@override
void initState() {
super.initState();
Future.delayed(Duration.zero).then((_) {
//Your code here
});
}
@override
Widget build(BuildContext context) {
return Container();
}
}
Second way is to use didChangeDependencies like so :
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var image;
bool init = true;
@override
void didChangeDependencies() {
if (init) {
init = false;
//your code here
}
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Container();
}
}
init boolean is to prevent didChangeDependecies from running same code so many time as it reruns alot
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove that $e^x > 1 + (1 + x)\log(1 + x), x > 0$ using power series expansion.
Prove that $e^x > 1 + (1 + x)\log(1 + x), x > 0$ using power series expansion.
I am a bit puzzled by this statement because the power series for $\log(1+x)$ only converges iff $|x|<1$. Is the problem sound? Should it be $1>x>0$?
A:
We can make an estimate for $1+(1+x)\log(1+x)$ that does not rely on the power series for $\log(1+x)$, and instead use the power series for $e^x$, which is valid for $x\ge0$.
Since $\frac1{1+t}\le1$ on $[0,x]$,
$$
\begin{align}
\log(1+x)
&=\int_0^x\frac{\mathrm{d}t}{1+t}\tag1\\
&\le x\tag2
\end{align}
$$
Furthermore,
$$
\begin{align}
(1+x)\log(1+x)-x
&=x\cdot\frac1x\int_0^x\log(1+t)\,\mathrm{d}t\tag3\\
&\le x\log\left(1+\frac1x\int_0^xt\,\mathrm{d}t\right)\tag4\\[3pt]
&=x\log(1+x/2)\tag5\\[3pt]
&\le\frac{x^2}2\tag6
\end{align}
$$
Explanation:
$(4)$: since $\log(1+t)$ is concave, apply Jensen's Inequality
$(6)$: apply $(2)$
Therefore, by comparing to the Taylor series for $e^x$,
$$
\begin{align}
1+(1+x)\log(1+x)
&\le1+x+\frac{x^2}2\tag7\\
&\le e^x\tag8
\end{align}
$$
Explanation:
$(7)$: apply $(6)$
$(8)$: $e^x=1+x+\frac{x^2}2+\text{positive terms}$
| {
"pile_set_name": "StackExchange"
} |
Q:
Implementations of an Adder in VHDL comparison
Can someone explain me why this implementation works
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.numeric_std.all;
entity Adder is
port(A: in std_logic_vector(3 downto 0);
B: in std_logic_vector(3 downto 0);
SUM: out std_logic_vector(3 downto 0);
CO: out std_logic);
end;
architecture DescriptionAdders of Adder is
signal temp: std_logic_vector(4 downto 0);
signal temp1: std_logic_vector(4 downto 0);
signal temp2: std_logic_vector(4 downto 0);
begin
temp1 <= '0' & A;
temp2 <= '0' & B;
temp <= std_logic_vector(unsigned(temp1) + unsigned(temp2));
SUM <= temp(3 downto 0);
CO <= temp(4);
end;
while this doesn't (the SUM is XX when it starts running, then it is always one step behind the real result, but the temps update well).
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.numeric_std.all;
entity Adder is
port(A: in std_logic_vector(3 downto 0);
B: in std_logic_vector(3 downto 0);
SUM: out std_logic_vector(3 downto 0);
CO: out std_logic);
end;
architecture DescriptionAdders of Adder is
signal temp: std_logic_vector(4 downto 0);
signal temp1: std_logic_vector(4 downto 0);
signal temp2: std_logic_vector(4 downto 0);
begin
process(A, B) is
begin
temp1 <= '0' & A;
temp2 <= '0' & B;
temp <= std_logic_vector(unsigned(temp1) + unsigned(temp2));
end process;
SUM <= temp(3 downto 0);
CO <= temp(4);
end;
Sorry if the question is too easy, I'm a begginer.
A:
This question seems to be based about a common misconception of how VHDL simulation works.
process(A, B)
means the process will be triggered at an event of A or B. What happens in the process are assignments to additional objects
temp1 <= '0' & A;
temp2 <= '0' & B;
temp <= std_logic_vector(unsigned(temp1) + unsigned(temp2));
This means three events will be scheduled, one to each of temp1, temp2 and temp. But the way VHDL works, the actual assignments will not occur until the next delta cycle. Which occurs after the process is evaluated. So even though the lines for assignment to temp1 and temp2 are located before the assignemnt to temp, their values have not been changed yet.
Considering values of temp1 and temp2 change after the process is finished, the assignment to temp is missed. Unless you re-enter the process, by adding the objects to the sensitivity list. E.g.
process(A, B, temp1, temp2) is
begin
temp1 <= '0' & A;
temp2 <= '0' & B;
temp <= std_logic_vector(unsigned(temp1) + unsigned(temp2));
end process;
An alternative solution would be to use variables, which can change inside of the process. But please note that variables can cause difficulties in logic synthesis if not properly used. This example will work:
process(A, B) is
variable temp1, temp2 : std_logic_vector(4 downto 0);
begin
temp1 := '0' & A;
temp2 := '0' & B;
temp <= std_logic_vector(unsigned(temp1) + unsigned(temp2));
end process;
But the question is: why do you need temp1 and temp2 at all. Just write
process(A, B) is
begin
temp <= std_logic_vector(unsigned('0' & A) + unsigned('0' & B));
end process;
Or a bit more flexible
process(A, B) is
begin
temp <= std_logic_vector(
resize(unsigned(A), temp'length) +
resize(unsigned(B), temp'length));
end process;
Or even using the integer type (limited to 32 bits!)
process(A, B) is
begin
temp <= std_logic_vector(to_unsigned(
to_integer(unsigned(A)) + to_integer(unsigned(B))
, temp'length));
end process;
| {
"pile_set_name": "StackExchange"
} |
Q:
Matrix with Functions as Entries
What do we call a matrix with functions as entries?
$$\textbf{f(x)}=\begin{bmatrix}
f_{11}(x) & f_{12}(x) \\
f_{21}(x) & f_{22}(x)
\end{bmatrix} $$
A:
Recall that you denote by $M_{2\times 2}(\mathbb{C})$ the set of matrices with entries in the complex numbers.
You can define matrices over other sets and depending on the structure of those sets these matrix algebras may or may not be interesting to you.
It is not clear what type of functions the $f_{ij}$ are here but because you might want to add and multiply the entries (why?), they will usually form a ring (briefly a set with addition and multiplication). So perhaps your functions come from the ring of continuous functions on the real line. You might denote this set by $\mathcal{C}(\mathbb{R})$.
Then your matrix above would be an element of the set of matrices over $\mathcal{C}(\mathbb{R})$ which we would denote by $M_{2\times 2}(\mathcal{C}(\mathbb{R}))$ and we could write
$$\mathbf{f}=\left(\begin{array}{cc}f_{11} & f_{12}\\ f_{21} & f_{22}\end{array}\right).$$
Your object above then seems to do more. It seems to take as an input $x\in\mathbb{R}$ and output a 2$\times$2 matrix:
$$\mathbf{f}:x\mapsto \left(\begin{array}{cc}f_{11}(x) & f_{12}(x)\\ f_{21}(x) & f_{22}(x)\end{array}\right),$$
so you have a function
$$\mathbf{f}:\mathbb{R}\rightarrow M_{2\times 2}(\mathbb{R}).$$
EDIT: i.e. what copperhat said.
Now you might begin to ask what kind of properties does this map have?
| {
"pile_set_name": "StackExchange"
} |
Q:
Applying Bag of words
Hey I am working with bag of words and I am trying to implement so suppose I have the corpus below but I don't want to use print( vectorizer.fit_transform(corpus).todense() ) as a vocabulary instead I have one create which goes like
{u'all': 0, u'sunshine': 1, u'some': 2, u'down': 3, u'reason': 4}
How can I use this vocabulary to generate the matrix?
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'All my cats in a row',
'When my cat sits down, she looks like a Furby toy!',
'The cat from outer space',
'Sunshine loves to sit like this for some reason.'
]
vectorizer = CountVectorizer()
print( vectorizer.fit_transform(corpus).todense() )
print( vectorizer.vocabulary_ )
A:
Instantiate your CountVectorizer using your custom vocabulary and then transform your corpus.
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'All my cats in a row',
'When my cat sits down, she looks like a Furby toy!',
'The cat from outer space',
'Sunshine loves to sit like this for some reason.'
]
vocabulary = {u'all': 0, u'sunshine': 1, u'some': 2, u'down': 3, u'reason': 4}
vectorizer = CountVectorizer(vocabulary=vocabulary)
print( vectorizer.transform(corpus).todense() )
[[1 0 0 0 0]
[0 0 0 1 0]
[0 0 0 0 0]
[0 1 1 0 1]]
print( vectorizer.vocabulary_ )
{'all': 0, 'sunshine': 1, 'some': 2, 'down': 3, 'reason': 4}
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem Filtering android app based on screen resolution
I want my app to be shown in the Market, only for devices with large screen. i.e WVGA800 (480x800, 480x850).
Example: Nexus One.
I have done following changes in the Manifest file.
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="false" android:smallScreens="false" android:resizeable="true"></supports-screens>
After uploading, when i try to search in Market using Nexus one, the app is not showing up. I have also tried with other devices having different screen types.
Any help on this will be great.
Thanks
A:
Are you sure the nexus one is a largescreen type phone? I don't think so. If its 480x800 but with "high density", then it's a 'normal' sized screen.
See here: http://developer.android.com/resources/dashboard/screens.html
If this images is correct, there have been very little or no 'large screen' devices on the market in august 2010 e.g. That doesn't proof anything, but i doubt the nexus would be unfindable in this graph ;): http://developer.android.com/guide/practices/screens_support.html
| {
"pile_set_name": "StackExchange"
} |
Q:
ember.js best way to add header and footer across all pages
I know this questions already been asked for several times. But I am having difficulties with it. I am creating an application with ember.js. I have about, contact, faq pages in my application. I want to show header and footer in all pages but the content will be changed based on page.so far I have:
Application Header
Application Footer
Application Home Page Contents
But I would like to have like this. basically the header and footer will be same for all pages but contents will change:
Application Header
Application Home Page Contents
Application Footer
Below is my code: app.js
App = Ember.Application.create();
App.Router.map(function() {
this.resource("about");
this.resource("contact");
this.resource("faq");
});
index.html
<script type="text/x-handlebars">
<h2>Application Header</h2>
<h2>Application Footer</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<div id="contents">
<h2> Application Home Page Contents</h2>
</div>
</script>
<script type="text/x-handlebars" data-template-name="about">
<h2>Application About Page</h2>
</script>
<script type="text/x-handlebars" data-template-name="contact">
<h2>Application contact page</h2>
</script>
<script type="text/x-handlebars" data-template-name="faq">
<h2>Application FAQ page</h2>
</script>
Thanks in advance.example code will appreciated.
A:
I use the main application route for this so my application template is:
<script type="text/x-handlebars" data-template-name="application">
{{partial "header"}}
{{outlet}}
{{partial "footer"}}
</script>
You could also replace the partials with views or render helper depending on if you need to change the controller or have access to the view directly in your script.
| {
"pile_set_name": "StackExchange"
} |
Q:
Batch to delete empty directories (and state which directories aren't empty?)
I'm using:
for /f "tokens=*" %%d in ('dir /ad/b/s ^| sort /R') do rd "%%d"
pause
which returns:
The directory is not empty.
for any nonempty directories. Is there any way for it to list specifically which directories aren't empty instead of a vague statement? I know it's not much effort to manually check the directories, but this is part of a larger script that I'm trying to make more user-friendly.
A:
rd returns an ERRORLEVEL you can use, just change:
rd "%%d"
To this:
rd "%%d" || (echo Not empty: %%d)
To remove error message from rd too just redirect stderr to nul:
rd "%%d" 2>nul || (echo Not empty: %%d)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do some C/C++ headers have "sys/" in front of them?
Some C/C++ headers like <sys/ioctl.h> have a "sys/" prefix in front of them.
(There are also some with a "net/" prefix.)
Why is this?
A:
Practically, this shows those file are under a sub-folder named "sys" in one of the standard list of system directories (e.g compiler default search path, or folder given as a parameter during the build).
The reason they are in a sub-folder is to indicate they are not a part of the c or c++ standard libraries, but rather a specific extension, usually provided by the operating system you are working in.
Note that this is only a matter of conventions, and not part of the specified behavior by C or C++. Usually to really understand those kind of header you will look at further documentation provided by the operating system you are working under.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bash script with graphical menus
I have been writing simple bash scripts for a while now, and I was wondering how I could implement simple menus and, if possible, use menus with color.
In the past, I have written simple C applications that use ncurses and would like to (if possible) have menus in my bash script where the user can use the up/down arrows to select items in a list, and go back/forth through a series of yes/no/cancel prompts.
I am familiar with setting up colored text in bash, so there's a start (eg: bash using colors), so the only requirement left at this point is to see if bash has these capabilities. I would prefer to avoid having to code an application in C/C++ for this, as I would like to be able to edit it on the fly.
A:
there is a package called dialog, is this relevant to your requirement?
A:
I haven't used this myself, but have you checked out bashsimplecurses? From the documentation, it looks like a possible solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to audit all the software installed on a PC
one of my customers is going to be audited by a Microsoft partner to check if all the installed software is legal.
So far, so good with the software I installed: all the Windows XP machines have their correspondent licenses, all the other applications I installed are freeware (Open Office, 7zip, etc).
But my customer asks me for a pre-auditing revision, to check if any of his employees installed any kind of software or -worse- are using a "portable" version of a copyrighted
software with no license.
Is there any freeware tool that can help me with the auditing? I checked
WinAudit, which seems good to audit the installed software, but it has no support to scan for registry keys or .EXE names / CRC checksums of possible offending programs.
TIA,
Pablo
A:
When it comes to auditing I think Belarc is probably the best out there.
The Belarc Advisor builds a detailed profile of your installed software and hardware, missing Microsoft hotfixes, anti-virus status, CIS (Center for Internet Security) benchmarks, and displays the results in your Web browser.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I check if a library (dll) is available in C#?
How do I check if a library (dll) is available at runtime before I call it?
A:
The AppDomain.AssemblyLoad and AppDomain.AssemblyResolve events occur on load and load failure, respectively. If you handle these events you can determine which assemblies loaded and which failed.
A:
You can use System.IO.File.Exists to check for the file if you know where it's located.
You can use System.Reflection.Assembly.LoadFrom to load it.
You'll need to use reflection to call methods in the dll if you use this form of late binding.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not able to add Background Image on Position Absolute div
Can you please take a look at this demo and let me know why I am not able to add image to the #img-box
html, body {
height:100%;
width:100%;
}
#wrapper {
position: relative;
height: 100%;
width: 100%;
}
#img-box {
position: absolute;
background-image: url("http://www.bluearthrenewables.com/wp-content/uploads/2014/12/7_Intake-Construction_CullitonCreek.jpg");
top:0;
left:0;
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
}
A:
Because #img-box has not any width & heights associated with it. try to define
html, body {
height:100%;
width:100%;
}
#wrapper {
position: relative;
height: 100%;
width: 100%;
}
#img-box {
position: absolute;
background-image: url("http://www.clker.com/cliparts/2/0/f/b/13873752061098664878happy_smiley-th.png");
height: 100%;
width: 100%;
top:0;
left:0;
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
}
<div id="wrapper">
<div id="img-box"></div>
<div id="tets"></div>
<div id="tes3"></div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Minimum Page Frames
What determines the minimum number of page frames that must be allocated to a running process in a virtual memory environment.
I found the the answer to the above question is instruction set architecture but couldn't understand reason behind it.
please explain.
EDIT :
The question is on the following link http://www.geeksforgeeks.org/archives/4036 (see question 3), i'm not able to understand the logic behind the answer.
A:
yes ISA does play a role.
Imagine this hypothetical condition if the ISA supports an instruction(like mov in x86) which can take an operand after 3 levels of indirection( recall x86's indirect addressing mode). Lets call this system A.
On another system you can have max of 2 levels of indirection call it B.
On A and B if we give 4 as the minimum number of frames see what happens.
B runs fine not A here's the reason:
when an instruction which has 3 level of indirection in its operand is loaded into the cpu for execution, remember we only have 4 frames for this process,assume this scenario
frame 1 will be for the instruction itself.
frame 2 will be for the 1st level of indirection the operand is in another page
frame 3 will be for the 2nd level of indirection maybe this was not in the address range of previously allocated frame.
frame 4 the same happens with the next level of indirection.
Now recall pipeline , only after the operand fetch is done we can go to the next execution stage, but we don't have the final operand we only have the address of where it in the frame 4 , now you get a page fault, so you remove one of the previously allocated frame to process and restart the instruction which caused the fault , but again the same thing happens.
The system B doesn't have this problem.
As far as i recall this is the way ISA plays a role in deciding minimum number of frames for a process.
Refer galvin i think the book covers this in virtual memory section.
But this is in theory , I don't know how the process is in a real system like linux.
Cheers :)
Edit:- As given in the link you pointed the instruction may cross page boundary
| {
"pile_set_name": "StackExchange"
} |
Q:
Drupal 7 theme "Busy" customization
I am a starter of Drupal 7.
I like the "Busy" theme a lot, especially this one in its screenshot of demos.
Yet, after I installed this theme, it seemed pretty far from what it looks like in the screenshot above. I tried to customize it but so far, I did not make much progress.
I see a lot of people saying this theme is good. The usage statistic shows a lot of websites are using this theme. I do like its neat layout, but as a starter, I really need some advice on how to work with this theme. How to make it look like the screenshot?
Any advice is appreciated.
Thanks,
Milo
A:
What exactly are you having trouble with?
I don't know your level of experience with Drupal so I'm just going to give you a couple ideas.
If you go to (yourSiteName)/admin/structure/block/demo/busy it will show a demo of where you can place blocks on the page to make your site look more like the picture.
(yourSiteName)/admin/appearance/settings/busy will take you to the settings screen where you can change colors and toggle features on and off.
(yourSiteName)/admin/structure/block will take you to the blocks page where you can change the layout of each block and also configure individual blocks.
I hope this helps, if you can give a more detailed question, you'll probably get a better answer
| {
"pile_set_name": "StackExchange"
} |
Q:
"logical subject" of verbals
Native speakers, could you please define "logical subject" of verbals (infinitive, gerund, participle)? I am Chinese and some of my grammar books define "logical subject" as the agent of the action, while some define it as the agent or patient of the action.
A:
I don't like him using swear words.
In the above sentence the verb like has an object that is a gerund phrase
"him using swear words".
The gerund phrase contains a full sentence "He uses swear words".
So some authors use the formulation "gerund construction with an own logical subject".
Of course, "him" is no subject in the sentence. Only if you transform the gerund phrase back to an independent sentence "him" becomes the subject "he". This is why "him" is called "logical subject of the gerund phrase".
This is the use of the term as I know it from my grammars. I never came across another use of the term. But it may well be that in some grammars the term is used in a different way, especially in Chinese grammars of English.
| {
"pile_set_name": "StackExchange"
} |
Q:
Accidently ran "chown www-data:www-data / -R" as root
I just ran this a few seconds ago. I managed to do Ctrl - C as soon as I realized what I started doing.
So far the only directory it's started going through is /bin.
I'm afraid to do anything else. So far I realized I can't use su as my normal user anymore.
Luckily I still have another root terminal open. What do I do?
A:
Redhat user:
chown 0:0 /bin/rpm && rpm -qa | xargs rpm --setugids
Debian/Ubuntu user:
chown 0:0 /bin/* /usr/bin/*
chown daemon:daemon /usr/bin/at
chown 0:utmp /usr/bin/screen
chmod 02755 /usr/bin/screen
chmod u+s /bin/fusermount /bin/mount /bin/su /bin/mount
chmod u+s /usr/bin/sudo /usr/bin/passwd
screen
While screen is running do this at least twice:
dpkg --get-selections | awk '{ if ($2 == "install") print $1}' \
| xargs apt-get install --reinstall --
Pay very close attention to the output because if it complains about something having the wrong permissions, you should fix it on another screen window.
Crash course in screen:
Control+A - command key
Control+A a - emit a control+A
Control+A n - next "screen"
Control+A c - create "screen"
Solaris user:
You're fucked.
pkgchk -R / -f -a
will reset all the permissions, but setuid-ness will still be broken. Use a backup, or another solaris machine to look for setuid/setgid scripts and files and fix them up manually.
THE IMPORTANT THING ABOUT BACKUPS
Is that you can recover them, not that you take them.
Other people have given you advice to take backups, but I want to add that you should be testing them. If you're using a unixish system, there is no reason whatsoever that you can't dump the files onto another machine periodically and make sure everything works.
A:
Most everything in /bin/ should be owned by root:root, so if you run the following you can fix the ownership on those files:
chown root:root -R /bin/
You may also want to make sure the setuid bit is properly set on /bin/su, which you can fix with the following:
chmod 4755 /bin/su
A:
Be aware that the set-uid flags on any affected binaries may have been removed, too; this is a security feature of chown. Check with some other system which binaries have the set-uid or set-gid flags and be sure to set them on your binaries as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to write kubernetes deployment to get the latest image built using GCP cloudbuild
I am trying to do the CI/CD with GCP cloudbuild.
I have a k8s cluster ready in GCP. check the deployment manifest bellow.
I have a cloudbuild.yaml ready to build new image and push it to registry and command to change the deployment image. check the cloudbuild yaml bellow.
Previously, I used to push the image using the TAG latest for the docker image and use the same tag in deployment but it didn't pull the latest image so Now I have changed it to use the TAG $COMMIT_SHA. Now, I am not able to figure out the way to pass the new image with TAG based on commit_sha to the deployment.
nginx-deployment.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: mynginx
spec:
replicas: 3
minReadySeconds: 50
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- image: gcr.io/foods-io/cloudbuildtest-image:latest
name: nginx
ports:
- containerPort: 80
cloudbuild.yaml
steps:
#step1
- name: 'gcr.io/cloud-builders/docker'
args: [ 'build', '-t', 'gcr.io/$PROJECT_ID/cloudbuildtest-image:$COMMIT_SHA', '.' ]
#step 2
- name: 'gcr.io/cloud-builders/docker'
args: ['push', 'gcr.io/$PROJECT_ID/cloudbuildtest-image:$COMMIT_SHA']
#STEP-3
- name: 'gcr.io/cloud-builders/kubectl'
args: ['set', 'image', 'deployment/mynginx', 'nginx=gcr.io/foods-io/cloudbuildtest-image:$COMMIT_SHA']
env:
- 'CLOUDSDK_COMPUTE_ZONE=us-central1-a'
- 'CLOUDSDK_CONTAINER_CLUSTER=cloudbuild-test'
images:
- 'gcr.io/$PROJECT_ID/cloudbuildtest-image'
Note: I repeat previously I was using the latest tag to the image and
as is the same in deployment I expected to pull the new image with my
3rd steps in cloudbuild but that didn't so I made the above changes in
TAG but now wondering how do I make changes to deployment manifest. Is
using the helm only solution here?
A:
You need a step to replace the tag in your deployment.yaml, one way to do it is to use an environment variable and use envsubst to replace it.
Change deployment.yaml:
- image: gcr.io/foods-io/cloudbuildtest-image:$COMMIT_SHA
Use some bash script to replace the variable (using the ubuntu step for example):
envsubst '$COMMIT_SHA' < deployment.yaml > nginx-deployment.yaml
Alternative using sed:
sed -e 's/$COMMIT_SHA/'"$COMMIT_SHA"'/g' deployment.yaml > /workspace/nginx-deployment.yaml
| {
"pile_set_name": "StackExchange"
} |
Q:
R: Removing vector entries from a list of vectors after comparison using operator
I'm trying to remove elements smaller than a given number from the vectors contained in a list. I manage to find exactly which elements in the vector meet my criteria, but somehow I'm failing to select them.
myList <- list(1:7,4:7,5:10)
lapply(myList, function(x)`>`(x ,5))
...
Rmagic
...
desiredoutput <- list(6:7,6:7,6:10)
I'm sure it's something to do with `[` but I can't figure it out and searching for this problem is a nightmare.
A:
We need to extract the elements based on the logical index (x>=6)
lapply(myList, function(x) x[x>= 6])
| {
"pile_set_name": "StackExchange"
} |
Q:
What build orders work for the Training Day Achievment?
What are the various build order's I can give that will allow me to complete this achievement?
Train 10 Marines during the first 320 seconds of a single Melee game
A:
6 Supply Depot
6 Barracks
6 SCV
7 SCV
8 Barracks (first barracks is still being built use another SCV to do this)
Retask SCV's to mineral collection when they're done building
When the first barracks is finished start building marines in it (6-7 I think)
When the second barracks is finished build more marines out of it (3-4)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to grep for unicode characters?
How do you search a file using grep for a string of unicode characters?
I'm trying to count the number of occurrences of the string "\xfe\n\xfe". I can find this with Python by doing:
open(filename).read().count('\xfe\n\xfe')
This finds a few thousand matches.
However, since this loads the entire file into memory, this will crash if I try to search a file larger than my system's memory.
So I'm trying to do the equivalent with grep via:
grep -P -c "\xfe\n\xfe" filename
It consumes almost 0 memory, which is great, but even though I run this on the same file, it finds 0 matches. What's wrong with my syntax?
A:
You don't need to read the entire file into memory. You can iterate on the file and count the occurrence of that string across lines taking a pair of lines at every instant:
count = 0
with open(filename) as f:
prev_line = next(f)
for line in f:
if prev_line.endswith('\xfe\n') and line.startswith('\xfe'):
count += 1
prev_line = line
| {
"pile_set_name": "StackExchange"
} |
Q:
populating a bootstrap 3 modal window on fullcalendar event click
Trying to leverage fullcalendar.io to populate a series of events. I've got my events working and the callback function when an event is clicked functioning as well.
What I want to do is open a bootstrap modal that will populate it's content area with an ajax call to my php backend. This will allow me to display the event details in that modal window.
Below is my latest attempts at making this work:
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div id="modal-body" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- This file should primarily consist of HTML with a little bit of PHP. -->
<div id='calendar'>
</div>
<script>
jQuery(document).ready(function () {
// set up the modal to be an ajax pull.
jQuery("#myModal").on("show.bs.modal", function(e) {
var link = jQuery(e.relatedTarget);
jQuery(this).find(".modal-body").load(link.attr("href"));
});
// set up the calendar
jQuery('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
height: 650,
editable: false,
eventLimit: true, // allow "more" link when too many events
eventSources: [
{
url :'<?php echo esc_url( admin_url('admin-post.php') ); ?>',
color: 'yellow',
textColor: 'black',
type: 'POST',
data: {
action: 'fun_events_feed'
}
}
],
// toggle the display of the modal window when an event is clicked.
eventClick: function(calEvent, jsEvent, view) {
jQuery.get( '/fun-intra/event-data.php', null, function(data){
jQuery('#modal-body').html(data);
jQuery('#myModal').modal('toggle');
});
},
});
});
</script>
when trying to open the modal window with an event click, the console spits out this error:
(index):183 Uncaught TypeError: jQuery(...).modal is not a function
I suspect I have a scoping issue, is there a way to pass in the jquery selected object so that I can toggle the display of the modal AFTER it has loaded within the .get callback? Once I have this working then I can easily add in the required parameters of the eventId so that my backend can fetch the correct event.
A:
Managed to find the answer last night after much google searching.
<script>
jQuery(document).ready(function () {
// set up the calendar
jQuery('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
height: 650,
editable: false,
eventLimit: true, // allow "more" link when too many events
eventSources: [
{
url :'<?php echo esc_url( admin_url('admin-post.php') ); ?>',
color: 'yellow',
textColor: 'black',
type: 'POST',
data: {
action: 'fengate_events_feed'
}
}
],
// toggle the display of the modal window when an event is clicked.
eventClick: function(calEvent, jsEvent, view) {
console.log(calEvent);
jQuery("#modal-body").load('<?php echo esc_url( admin_url('admin-post.php') ); ?>?action=event_modal&id=' + calEvent.id);
jQuery("#myModal").modal('toggle');
},
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Python urllib2 parse html problem
I am using mechanize to parse html of website, but with this website i got strange result.
from mechanize import Browser
br = Browser()
r = br.open("http://www.heavenplaza.com")
result = r.read()
result is something which i can not understand. you can see here: http://paste2.org/p/1556077
Anyone can have some method to get that website HTML? with mechanize or urllib.
Thanks
A:
import urllib2, StringIO, gzip
f = urllib2.urlopen("http://www.heavenplaza.com")
data = StringIO.StringIO(f.read())
gzipper = gzip.GzipFile(fileobj=data)
print gzipper.read()
| {
"pile_set_name": "StackExchange"
} |
Q:
scala is inferring Nothing though defining with explicit types
In the following code I'm getting error
Error:(48, 11) type mismatch;
found : (Int, Map[Int,Option[List[Int]]])
required: (Int, Nothing)
f
def tuplesWithRestrictions1(): (Int, Map[Int, Option[List[Int]]]) = {
val df = new DecimalFormat("#")
df.setMaximumFractionDigits(0)
val result = ((0 until 1000) foldLeft ((0, Map.empty(Int, Some(List.empty[Int]))))) {
(r: (Int, Map[Int, Option[List[Int]]]), x: Int) => {
val str = df.format(x).toCharArray
if (str.contains('7')) {
import scala.math._
val v = floor(log(x)) - 1
val v1 = (pow(10, v)).toInt
val m = (r._2).get(v1) {
case None => r._2 + (v1 -> List(x))
case Some(xs: List[Int]) => r._2 updated(x, xs :+ x)
}
val f = (r._1 + 1, m)
f
} else r
}
}
result
}
Why the compiler is inferring Nothing though I'm explicitly specifying that result is of (Int, Map[Int, Option[List[Int]]]) type ? and How to fix this issue.
A:
Your val m = (r._2).get(v1) returns Option[Option[List[Int]]]. I think, you should do pattern matching inside pattern matching to get results you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Subscribers not able listen to startup events when library is being instantiated
I want to allow users to subscribe to events in my codes lifecycle so i've included a pubsub mechanism which is made available to the user as soon as the library has been instantiated. It works well for the most part. The code looks like something this:
var library = function() {
//library code here
//Publish some sort of initialisation event
ev.publish('init');
//return an object that includes the ev pubsub functionality
};
then I imagined a user might be able to interact with it like so:
var test = new library();
//the ev object is returned from the instantiation of the library
test.ev.subscribe('init',function() {});
This works for the most part - the subscribe function can hook in to all post initialisation publishes.
The Problem lies with when the library is instantiated and various initialisation events are fired. There's no way for a user can interact with the publish events that are fired during initialisation because by the time the user is given an opportunity to subscribe to anything those startup events have already been fired.
How can I refactor this code to allow the event system to be captured in full?
A:
There are several approach to achieve this kind of thing. Based on your architecture, requirements, preference you can do either of the following:
Approach 1 :
You can accept a callback function as a init function and there you can handle it.
var library = function(initCallback) {
ev.subscribe('init', initCallback);
//library code here
//Publish some sort of initialisation event
ev.publish('init');
//return an object that includes the ev pubsub functionality
};
Then you can call like
var test = new library(function() {});
Approach 2 :
Separate the init function from instantiate. This architecture used most. You can expose selected method only as public.
var library = function() {
//library code here
//Publish some sort of initialisation event
function init() {
ev.publish('init');
}
//return an object that includes the ev pubsub functionality
return {
init : init,
ev : ev,
// .... expose other function/properties
};
};
Then you can use this like:
var test = new library();
//the ev object is returned from the instantiation of the library
test.ev.subscribe('init',function() {});
//Call the actual initialization
test.init();
Approach 3:
As you stated you do not want to follow neither of above approaches, then there may be only one way to achieve what you want, by moving the event handler from your object. As you haven't gave your event handler code, I am giving an example implementation with jquery event handler.
var library = function() {
//library code here
//Publish some sort of initialisation event
var self = this;
$(window).trigger( "init.library", [ self ] );
//return an object that includes the ev pubsub functionality
};
hen you can use this like:
$(window).on( "init.library", function( event, obj ) {
//Do whatever you want with "obj"
});
var test = new library();
If you do not want to use the last approach, then best of luck :). And if you find any other interesting solution, please post it for others. Actually another thing you can do, if your purpose is to just call the init function, after instantiate of the object(not while instantiating) then you can change ev.publish('init'); line as
setTimeout(function() {
ev.publish('init');
},1);
Then your code will also work!!
Happy coding!!
| {
"pile_set_name": "StackExchange"
} |
Q:
convert float to hours and minutes in pandas/numpy
I have several columns in a pd.DataFrame in which decimal separates hours and minutes (e.g., 3.15 = 3 hours, 15 minutes). Is there a quick way to convert this so that the data are recognized as h.m ? The pandas Time Series documentation doesn't seem to apply to my case. I don't have or want to attach any dates.
I tried:
# create df
hour_min = pd.DataFrame({'a': [4.5, 2.3, 3.17],
'b': [2.12, 1.13, 9.13],
'c': [8.23, 9.14, 7.45]})
# convert to hours
hour_min.astype('timedelta64[h]')
which gives
a b c
0 04:00:00 02:00:00 08:00:00
1 02:00:00 01:00:00 09:00:00
2 03:00:00 09:00:00 07:00:00
but I want
a b c
0 04:50 02:12 08:23
1 02:30 01:13 09:14
2 03:17 09:13 07:45
I also need the following type of result from adding/subtracting column values 1.32 + 1.32 = 3.04
A:
I'm pretty sure there should be a more efficient solution, but since no one answered yet, here is a hacky workaround:
import pandas as pd
hour_min = pd.DataFrame({'a': [4.5, 2.3, 3.17],
'b': [2.12, 1.13, 9.13],
'c': [8.23, 9.14, 7.45]})
def convert(number):
hour = ('%.2f' % number).split(sep='.')[0]
minute = ('%.2f' % number).split(sep='.')[1]
return pd.to_datetime(hour+":"+minute, format='%H:%M')
Then you just need to use applymap():
>>> hour_min = hour_min.applymap(convert)
>>> hour_min
a b c
0 1900-01-01 04:50:00 1900-01-01 02:12:00 1900-01-01 08:23:00
1 1900-01-01 02:30:00 1900-01-01 01:13:00 1900-01-01 09:14:00
2 1900-01-01 03:17:00 1900-01-01 09:13:00 1900-01-01 07:45:00
You can show the time only with:
>>> for i in hour_min:
hour_min[i] = hour_min[i].dt.time
>>> hour_min
a b c
0 04:50:00 02:12:00 08:23:00
1 02:30:00 01:13:00 09:14:00
2 03:17:00 09:13:00 07:45:00
A:
You're going to want to use pd.to_timedelta in a function and applymap it to get the math you want. Looks something like this:
import pandas as pd
import math
def to_t_delt(number):
return pd.to_timedelta(f'{math.floor(number)}hours {(number - math.floor(number)) * 100}min')
hour_min = pd.DataFrame({'a': [4.5, 2.3, 3.17],
'b': [2.12, 1.13, 9.13],
'c': [8.23, 9.14, 7.45]})
hour_min = hour_min.applymap(to_t_delt)
print(hour_min)
print()
print(hour_min['a'] + hour_min['b'])
and yields this result:
a b c
0 04:50:00 02:12:00 08:23:00
1 02:30:00 01:13:00 09:14:00
2 03:17:00 09:13:00 07:45:00
0 07:02:00
1 03:43:00
2 12:30:00
dtype: timedelta64[ns]
| {
"pile_set_name": "StackExchange"
} |
Q:
Running Supervisor on Heroku
I was wondering if anyone knows how to run Supervisor on Heroku to manage queue workers? I've managed to get Supervisor running locally for my Laravel app, but have no idea how to create more worker processes to go through the job queue quicker.
I asked Heroku's support on this and they said it should work, but they don't have any documentation for this, nor do I think they would want to help figure this out for me. Currently the only way to get more workers on a queue (I'm using SQS) is to create more processes through the Procfile which you have to pay for additional dynos, or scale up if you're on the performance dynos.
Seems kinda inefficient for me as my current worker process only uses up < 60MB working through the queue, and the memory limit of the hobby dynos are 512MB. It's a waste to spin up more dynos when the existing dynos are underutilized.
I've googled for hours but haven't been able to find a solution to this.
Is this even possible in the first place? Thanks.
A:
Ok I think I've managed to figure out the solution. I've posted it on my blog - http://www.dannytalk.com/running-supervisor-with-laravel-workers-on-heroku/.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ajax request is not working it seems
i have following ajax code... it seems to not working...
$('form').submit(function () {
var email = $('#useremail').val();
var name = $('#username').val();
$.ajax({
url: '/Landing2/mail.php',
type: 'POST',
data: {
email: email,
name: name
},
success: function (data) {
alert(data);
},
});
});
my dir sturcutre is
htdocs
Landing2
index.php (From where i am making request")
mail.php
anything wrong in this?
A:
Your requested url should be this:
url: 'mail.php',
this will work for you.
A:
There are a few issues with this, your properties you are passing to your Ajax call are incomplete. Either add a final property (i.e. error: function() {}) or Remove the final , from the end of your properties.
Also if the request location is in the same directory as the current location, you can just specify the file name (i.e. url: 'mail.php')
Example code :
$('form').submit(function () {
var email = $('#useremail').val();
var name = $('#username').val();
$.ajax({
url: 'mail.php',
type: 'POST',
data: {
'email': email,
'name': name
},
success: function (data) {
alert(data);
}
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Profiling Java WebApps
While trying to profile our WebApp with JVisualVM I have the problem that a lot of the interesting stuff is hidden behind the methods of our ApplicationServer.
I would love to have a tool that would allow me to profile the complete webapp inside of the server, but without profiling the server itself or any other webapps that might be running on the same server. Basically I think the server itself should be in a good position to provide something like that, but I never heard of such a feature in any server. Is anyone aware of such a functionality?
I would like to add that I already do profile my web app with JVisualVM...
A:
Profiling a web application without profiling the server is not really feasible, since profilers always look at the entire JVM.
You could define entry points to automatically start and stop profiling, but that is not really necessary: Just set your method call recording filters to the package of your web application and you will only see method calls in the classes that you are interested in, without the surrounding stack frames of the container.
In JProfiler, this is done by opening the session settings and defining a single inclusive filter:
Disclaimer: My company develops JProfiler.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can you supress hive column names printing to CLI?
I have so many columns in my hive table that it is causing my text editor to crash upon the completion of my jobs. I am hoping there is a
set hive.exec.showheaders=false
I have looked through the hive JIRA but can't fine a way to change any type of setting.
A:
set the property below to false.
hive> set hive.cli.print.header=false;
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I add a photo to a form without InfoPath?
I on a 2013 site. I would like to add a photo to a form that was created within SP without using InfoPath. Is this possible? here is an example.
This was created using InfoPath. Any information on how to do this without InfoPath would be much appreciated. Thanks!
A:
Use a CEWP at the top of your page. Store the Image in an image library so SharePoint can get it. Then, use HTML in the CEWP to make your header with the image. Should work just fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Set CORS header in ASP.NET HTTP response
I'm trying to set headers for my HTTP response to include CORS header Access-Control-Allow-Origin in order for the response to be easily read by my Anguler.js web app.
To do that, I'm doing the following:
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace tecboxapi777.Controllers
{
public class WorkersController : ApiController
{
// GET: api/Worker
[Route("api/Workers")]
[HttpGet]
public HttpResponseMessage Get()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
response.Headers.NAME_OF_THE_HEADER = "Access-Control-Allow-Origin";
}
}
}
As you can see, I am unable to find the correct name for the CORS header. I've searched online but all I find is to use something similar to Access-Contro-Allow-Origin = "*" which doesn't even compile.
My question is: How do I properly set my CORS headers so that my Angular.JS webapp is able to read my response?
Currently Firefox's developer mode console returns the following message in whenever I try to do a GET request to my API:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://192.168.0.6:45455/api/Workers. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)
Just for the sake of completeness, the Angular.JS code that does the GET request is the following:
posts: Observable<any>;
getPosts(){
this.posts = this.http.get(this.ROOT_URL + '/api/Workers');
console.log(this.posts);
}
EDIT: I accepted Sotiris Koukios-Panopoulos's answer because it's what I did to solve my problem and also it requires no installation of packages. Nevertheless, Manish's answer is the better answer and its the one you should follow if you care about whats considered standard.
It surprises me how everything, even adding headers to a response, requires a package in .NET...
A:
You have two ways to do this.
Enable this using a response header just like you initially tried:
Response.Headers.Add("Access-Control-Allow-Origin", "*");
Configure it globally and use it selectively in your Controllers/Actions.
For this, you can use the guide in the official docs which can explain it more thoroughly than I ever could
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery trigger - 'change' function
I have a radio button set called "pick_up_point" and I have a change handler to detect the radio button that is checked. In the change handler I call a function "clearFields()" which basically clears out the input fields.
function clearFields()
{
$("#Enquiry_start_point").val("");
$("#Enquiry_start_town").val("");
$("#Enquiry_start_postcode").val("");
}
$("input[name='pick_up_point']").change(function()
{
if($("input[name='pick_up_point']:checked").val() == "pick_up_airport")
{
$("#pick_up_airport_div").slideDown();
$("#start_point_div").hide();
clearFields();
}
});
I also have a trigger which will retain the view if the form is redisplayed due to a validation error.
$('input[name=\'pick_up_point\']').trigger('change');
Now when I post the form the trigger is run and it calls the change handler, which of course runs the clearFields() function. So how can I get around this? I don't want the fields being cleared when the form is re-displayed.
A:
Try using a custom event handler, like so:
$("input[name='pick_up_point']").change(function()
{
$(this).trigger("displayForm");
clearForm();
});
$("input[name='pick_up_point']").bind("displayForm", function() {
if($("input[name='pick_up_point']:checked").val() == "pick_up_airport")
{
$("#pick_up_airport_div").slideDown();
$("#start_point_div").hide();
}
});
So instead of triggering the change event, trigger the custom displayForm handler, like this:
$('input[name=\'pick_up_point\']').trigger('displayForm');
And now, when change is triggered, it works as expected, but for the special case of displaying the form without clearing the input fields, you can simply trigger your new custom event handler.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why $L^{r}(X)\cap L^{t}(X)\subset L^{s}(X)$ for $1<r<s<t$?
I am working on this homework problem, and I am totally stuck:
Let $(X,\mu)$ be a measure space, and let $1 \leq r < s < t < \infty$. Prove that there exist constants $\alpha,\beta>0$ so that
$$
\|f\|_s \;\leq\; \|f\|_r^\alpha\,\|f\|_t^\beta
$$
for any measurable function $f\colon X\to\mathbb{R}$. Use this to show that
$$
L^r(X) \cap L^t(X) \,\subset\, L^s(X).
$$
I know this is supposed not to be difficult. But I cannot solve it.
A:
Hint: Write $\frac{1}{s} = \frac{\alpha}{r} + \frac{\beta}{t}$ and apply Hölder's inequality.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to call sizeForItemAtIndexPath method after screen rotates
I have made my collection view cells to be calculated programmatically and I'm using sizeForItemAtIndexPath method to set the cell's sizes.
But When the screen rotates ,I need to recalculate the sizes and set them for cells. So,How can I call that function again after screen rotates?
By the way, I know didRotateFromInterfaceOrientation method and the only problem I got is that I don't know how should I call set the cell's sizes again.
Thanks
A:
Another way using newer UIViewController methods
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context)
{
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context)
{
[self.collectionView.collectionViewLayout invalidateLayout];
}];
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
OR two values in shell script?
I have a variable that may or may not be empty. If it's not empty, I want that value. If it is empty, I want the value of some other command. Example:
my_function ()
{
name_override="$1"
user_name=${name_override} || $(git config "user.name")
}
I'm not sure if the code above will work. But basically I want to run git config and store that result in user_name if the name_override variable is unset (and thus $1 would not have been provided).
How can I do this correctly?
A:
The bash idiom for accomplishing this is
user_name=${1:-$(git config "user.name")}
where :- says to use the value of $1 if it is set and non-null, else use the following string.
| {
"pile_set_name": "StackExchange"
} |
Q:
$P(A' ∩ B) = P(B) − P(A)$ when $A \subset B$
$A \subset B$. I need to prove that $P(A' ∩ B) = P(B) − P(A)$. I know that I have to use the partition theorem. I have that $P(A' ∩ B) + P(A ∩ B) = P(B)$. But that is all I have. I do not know how to get the $P(A)$. Can someone help me out.
A:
Hint: Use the fact that
\begin{align}
B&=A~\cup~(B\setminus A)\\&=A~\cup~(B~\cap~A').
\end{align}
This union is a disjoint union.
| {
"pile_set_name": "StackExchange"
} |
Q:
Infinispan NotSerializableException when spinning up WAR in Wildfly 16
I am trying to run my application on 2 Wildfly 16 nodes running in Standalone mode using the standalone-full-ha.xml configuration. When the 2nd node starts up, the first attempts to distribute/balance the default web cache to the new node.
When it does this, I see the following error message in the log on the first node, and the 2nd node fails to start:
13:45:48,487 ERROR [org.infinispan.remoting.rpc.RpcManagerImpl] (transport-thread--p18-t8) ISPN000073: Unexpected error while replicating: org.infinispan.commons.marshall.NotSerializableException: org.wildfly.transaction.client.ContextTransactionManager
Caused by: an exception which occurred:
in field com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.transactionManager
in object com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorRequired@73962bdb
in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.instance
in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
in field java.util.Collections$SynchronizedCollection.c
in object java.util.Collections$SynchronizedList@333ebcd4
in field org.jboss.weld.contexts.CreationalContextImpl.dependentInstances
in object org.jboss.weld.contexts.CreationalContextImpl@4dc7055b
in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.creationalContext
in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37
in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37
13:45:50,718 ERROR [org.infinispan.statetransfer.OutboundTransferTask] (transport-thread--p18-t8) Failed to send entries to node node2: org.wildfly.transaction.client.ContextTransactionManager: org.infinispan.commons.marshall.NotSerializableException: org.wildfly.transaction.client.ContextTransactionManager
Caused by: an exception which occurred:
in field com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.transactionManager
in object com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorRequired@73962bdb
in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.instance
in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
in field java.util.Collections$SynchronizedCollection.c
in object java.util.Collections$SynchronizedList@333ebcd4
in field org.jboss.weld.contexts.CreationalContextImpl.dependentInstances
in object org.jboss.weld.contexts.CreationalContextImpl@4dc7055b
in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.creationalContext
in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37
in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37
Some other things to note:
It fails when starting up one of my WARs that is distributed inside an EAR, but not the other 2 WARs that are also deployed in the EAR
My web.xml is marked as <distributable/> for all 3 WARs
My other caches seem to replicate just fine
I can't seem to figure out where the ContextTransactionManager is being used, or why it my be serialized to a session cache. I'm assuming it might be in my code somewhere, but I can't figure out where to even start looking. Any help would be appreciated!
Update (05/28/2019): Here are a couple screenshots from the management console showing 2 sessions that get created at startup (we use JSP in our web app, and we have a startup service that runs to pre-compile all of the JSP files):
A:
Update: This ended up being a really simple and somewhat stupid problem in the first place. We had marked a method in the LoggedInUser class with the @javax.transaction.Transactional annotation, which was not necessary in the first place, but was causing the serialization issue.
Just wanted to post an update in case anyone else ran across something similar.
| {
"pile_set_name": "StackExchange"
} |
Q:
Total memory consumption of the system
Is it correct to assume that the total memory consumption (virtual + physical) of a system is sum of "Memory Usage" and "VM Size" columns shown by the task manager in windows?
A:
Read these posts by Mark Russinovich:
http://blogs.technet.com/markrussinovich/archive/2008/07/21/3092070.aspx
http://blogs.technet.com/markrussinovich/archive/2008/11/17/3155406.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it mis-use to use "bandwith" to describe the speed of a network?
I often heard people talking about a network's speed in terms of "bandwith", and I read from < Computer Networks: A Systems Approach > the following definiton:
The bandwidth of a network is given by
the number of bits that can be
transmitted over the network in a
certain period of time.
AFAIK, the word "bandwith" is used to describe the the width of frequency that can be passed on some kind of medium. And the above definition describe something more like a throughput. So is it mis-use?
I have been thinking about this question for some time. I don't know where to post it. So forgive me if it is off topic.
Thanks.
Update - 1 - 9:56 AM 1/13/2011
I recall that, if a signal's cycle is smaller in time domain, its frequency belt will be wider in frequency domain, so IF the bit rate (digital bandwidth) is big, the signal's cycle should be quite small, and thus the analog bandwidth it required will be quite wide, but medium has its physical limit, the medium has the widest frequency it allows to pass, so it has the biggest bit rate it allows to transmit. From this point of view, I think the mis-use of bandwidth in digital world is acceptable.
A:
The word bandwidth has more than one definition:
Bandwidth has several related meanings:
Bandwidth (computing) or digital bandwidth: a rate of data transfer, throughput or bit rate, measured in bits per second (bps), by analogy to signal processing bandwidth
Bandwidth (signal processing) or analog bandwidth, frequency bandwidth or radio bandwidth: a measure of the width of a range of frequencies, measured in hertz
...
With both definitions having more bandwidth means that you can send more data.
In computer networking and other digital fields, the term bandwidth often refers to a data rate measured in bits per second, for example network throughput, sometimes denoted network bandwidth, data bandwidth or digital bandwidth. The reason is that according to Hartley's law, the digital data rate limit (or channel capacity) of a physical communication link is proportional to its bandwidth in hertz, sometimes denoted radio frequency (RF) bandwidth, signal bandwidth, frequency bandwidth, spectral bandwidth or analog bandwidth. For bandwidth as a computing term, less ambiguous terms are bit rate, throughput, maximum throughput, goodput or channel capacity.
(Source)
| {
"pile_set_name": "StackExchange"
} |
Q:
Advice on framework design
i'm currently constructing some kind of mini-framework for a project, and come up with this solution. I have tried many of them, but this seems to me very convinient (code is shortened for simplicity):
# Basically it's just a Registry pattern
class Repository {
private static $objects = array();
public function loadObject($alias, $object) {
self :: $objects[$alias] = $object;
return true;
}
public function __get($name) {
if ($this->objectExists($name)) {
return self::$objects[$name];
} else {
return false;
}
}
}
class Database extends Repository {
/* database class */
}
class Session extends Repository {
public function some_func($key, $value) {
/* i can access database object using $this in any class that extends Repository */
$this -> database -> exec (/* sql */);
}
}
/* =================== */
# Load core objects
$R = new Repository :: getInstance();
$R -> loadObject ('config', new Config());
$R -> loadObject ('database', new Database());
$R -> loadObject ('session', new Session());
/* =================== */
Can you see any problems or drawbacks with this approach? For me i see maybe i little more memory consumption, because each next class holds more and more objects from Repository.
Before i had a design where each class was independent, but anyway all of them require database, session, config etc, no i had to declare them in any class.
Just wanted to note that i'm planning this design only for core objects, not for specific classes.
A:
Don't extend Repository:
A database is not a repository, a repository has a database
Your database/session/config aren't related and shouldn't be. Liskov substitution principle:
[...] if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program (e.g., correctness).
Edit: trying to answer follow-up questions in this reply.
This technique is called dependency injection. A session example:
class Session {
// notice the clean API since no methods are carried along from a possibly huge base class
public function __construct(ISessionStorage $storage) {
$this->_storage = $storage;
}
public function set($key, $value) {
$this->_storage->set($key, $value);
}
}
interface ISessionStorage {
public function set($key, $value);
}
class DatabaseSessionStorage implements ISessionStorage {
public function __construct(Db $db) {
$this->_db = $db
}
public function set($key, $value) {
$this->_db->query("insert....");
}
}
class CookieSessionStorage implements ISessionStorage {
public function set($key, $value) {
$_SESSION[$key] = $value;
}
}
// example where it's easy to track down which object went where (no strings used to identify objects)
$session = new Session(new DatabaseSessionStorage(new Db()));
$session->set('user', 12512);
// or, if you'd prefer the factory pattern. Note that this would require some modification to Session
$session = Session::factory('database');
$session->set('user', 12512);
Sure you could store connection settings hardcoded in a config-file. This only means the other files need to get hold of that config class without going through their parents. For example:
class Database {
// The same pattern could be used as with the sessions to provide multiple database backends (mysql, mssql etc) through this "public" Database class
public function __construct(Config $config) {
$this->_config = $config;
$this->_connect();
}
private function _connect() {
$this->_config->getDatabaseCredentials();
// do something, for example mysql_connect() and mysql_select_db()
}
}
If you'd prefer to keep config information out of php-files (for easier editing/reading), see the Zend_Config-classes for examples of accessing different storage devices including the more common ones: ini, php array, xml. (I'm only mentioning Zend_Config since I've used it and am satisfied, parse_ini_file would do as well.)
A good & hopefully easy read: Fabience Potencier - What is dependency injection?
Edit #2:
Also see the slide: Matthew Weier O'Phinney - Architecting your models
A:
"because each next class holds more and more objects from Repository" - I don't exactly understand what you meant by that, I think as the objects are static there's only one copy.
I think you can use a little bit different approach to avoid drawback, by combining singleton pattern.
class Repository
{
private static $instance;
private $objects = array();
private static getInstance()
{
if (!Repository::$instance)
!Repository::$instance = new Repository();
return !Repository::$instance();
}
public static function loadObject($alias, $object)
{
Repository::getInstance()->objects[$alias] = $object;
return true;
}
public static function get($name)
{
$repository = Repository::getInstance();
if (isset($repository->objects[$name]
return $repository->objects[$name];
else
return false;
}
You will then use this in your child classes:
Repository::get('config');
and in bootstrap
Repository::loadObject('config', new Config());
Repository::loadObject('database', new Database());
etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does ASP.NET Core return a 404 at the end of the Middleware Pipeline?
I wanted to find out how ASP.NET Core determines we have reached the end of the middleware pipeline and starts sending the response back. This is the code that handles it (from the GitHub repository):
public RequestDelegate Build()
{
RequestDelegate app = context =>
{
/*
Some code omitted for clarity
*/
context.Response.StatusCode = 404;
return Task.CompletedTask;
};
foreach (var component in _components.Reverse())
{
app = component(app);
}
return app;
}
My question is this: What does the line context.Response.StatusCode = 404; do? Why is it even there? Shouldn't it be a 200 ("OK")? Where is the code that changes this default value so that we don't get a "404 Not Found" error on every request?
A:
What does the line context.Response.StatusCode = 404; do? Why is it even there?
This call ends up being run as the last component within the middleware pipeline. If the incoming request makes it all the way to the end of the pipeline that you configured, this code will run. It's there to ensure that a 404 is returned when a request isn't handled by your application.
Shouldn't it be a 200 ("OK")?
No, a HTTP 200 OK response isn't appropriate for this. That indicates that the request was handled successfully, but in fact it wasn't handled at all, because logic for processing this particular request was not found (HTTP 404 NotFound).
Where is the code that changes this default value so that we don't get a "404 Not Found" error on every request?
The middleware pipeline supports the concept of short-circuiting (see the docs). Briefly, this means a middleware component decides whether or not to execute the next middleware component in the pipeline. Imagine the following, simplified pipeline setup:
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
In this pipeline, both the static-files and the endpoints middleware may short-circuit the pipeline. If the static-files middleware is able to process the request, it usually sets the status-code to HTTP 200 and returns the file. If the endpoints middleware finds a matching controller/action, it could do one of many things, but usually it will set a success status code such as HTTP 200.
Only if neither the static-files middleware nor the endpoints middleware manages to handle the request, the line called out (context.Response.StatusCode = 404;) will run as a sort of fallback.
| {
"pile_set_name": "StackExchange"
} |
Q:
Values not being transfered from JS to php
I have a JS script of:
function addTasteingNote(userID,beerID)
{
//get values
var note = $('#note1').val();
var ajaxSettings = {
type: "POST",
url: "a.php",
data: "u="+userID+"&b="+beerID+"&n="+note,
success: function(data){
} ,
error: function(xhr, status, error) { alert("error: " + error); }
};
$.ajax(ajaxSettings);
return false;
}
and the php script to add to the db is:
<?php
error_log("starting code");
require_once('connect.inc.php');
$u = $_GET['uID'];
$b = $_GET['bID'];
$n = $_GET['n'];
//do some checks etc
$db = new myConnectDB();
error_log("Successfully created DB");
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ($u, '$b', '$n')";
error_log($query3);
$result = $db->query($query3);
?>
The problem is that the error log shows nothing being put into the query:
[01-Nov-2013 23:40:29] Successfully created DB
[01-Nov-2013 23:40:29] INSERT INTO x (userID,beerID,note) VALUES (, '', '')
I have put alerts in the success of the ajax call, so I know that values are being passed through...
A:
You need to give data like
var ajaxSettings = {
type: "POST",
url: "a.php",
data: {u:userID,b:beerID,n:note},
success: function(data){
}
data wont be and Query string,And since you are posting the values through ajax you need to get them via POST only like
$u = $_POST['u'];
$b = $_POST['b'];
$n = $_POST['n'];
And your query should be like
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ('".$u."', '".$b."', '".$n."')";
And Better to use escape strings with your POST variables to prevent from SQL injection.
| {
"pile_set_name": "StackExchange"
} |
Q:
Covariance of normally distributed random variables
If $ X \sim N(0,1) $ and given $ X = x $ then $ Y \sim N(x,1) $
I want to find the $ Cov(X,Y) $ using the relationship stated above.
My attempt:
$ Cov(X,Y) = E[XY] - E[X]E[Y] \\
E[X] = 0\\
Cov(X,Y) = E[XY] \\
E[XY] = E[E[XY|X=x]]$
I am not sure how to proceed from there..
Do I integrate the joint distribution?
A:
$$E[XY] = E[XE[Y|X]]
$$
Now as $E[Y|X] = X$:
$$
= E[X^2] = 1
$$
and
$$
E[X]E[Y] = 0
$$
you get $cov(X,Y) = 1$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I only make one wudu because of cream?
I have a skin problem (on my face) and I am required to put a very expensive cream on my face once a day and cannot wash it off. The cream has to be on my face all the time. When I wake up for fajr prayer I do wudu (then put the cream) and then I have to try and not go to the bathroom the whole day until after isha prayer so I don't break the wudu. It's very difficult because I eat and drink less and have to only pray with one wudu only. I don't know what to do or if what i'm doing is ok.
What should I do?
A:
i don't know about what you can do to do not try not go to the bathroom the whole day
but about your question (or if what i'm doing is ok.)
yes what you do is ok
Renewing wudu is suna , not a duty
and prophet Mohamed did what you do in tabok foray (غزوة تبوك) he pray all the prayer with one wudu when shaba ask hem he said that 'because i want you to know this possible "
but Renewing wudu in every pray is better the god say (يا ايها الذين ءامنوا اذا قمتم الي الصلاة فأغسلوا وجوهكم وايديكم الي المرافق وامسحوا برؤسكم وارجلكم الي الكعبين )
the god say if we want to pray we have to do wudu but because what prophet mohammed do in Tabok's foray we say that Renewing wudu is not a duty every pray but is better
link for the fatwa in arabic https://www.islamweb.net/ar/fatwa/281650/%D8%A7%D8%B3%D8%AA%D8%AD%D8%A8%D8%A7%D8%A8-%D8%A7%D9%84%D9%88%D8%B6%D9%88%D8%A1-%D8%B9%D9%86%D8%AF-%D9%83%D9%84-%D8%B5%D9%84%D8%A7%D8%A9
link for fatwa in english
https://islamqa.info/en/answers/239934/is-it-mustahabb-to-do-wudoo-before-every-naafil-prayer
| {
"pile_set_name": "StackExchange"
} |
Q:
Ansible WHEN with variable interpolation
From what I was able o find online, Ansible doesn't support varibale intrepolation very well when it comes to jinja templates.
However I'm sure that someone more advanced in Ansible has found a workaround for my problem below.
I would like to "interpolate" a variable to WHEN statment.
i.e. when: Disabled in (smart_link_status.results[item[0]].stdout)
This is my play:
- name: "Get Smart Link status"
shell: "{{ssh_command}} show network {{network_name}}_{{item}} | grep 'Smart Link'"
register: "smart_link_status"
with_items:
- "{{uplink_id}}"
- name: "enable SmartLink for the network"
shell: "{{ssh_command}} set network {{network_name}}_{{item[1]}} SmartLink={{smart_link}}"
when: Disabled in (smart_link_status.results[item[0]].stdout)
with_indexed_items:
- "{{uplink_id}}"
How can I achieve this? Seem's that I can do it easly with normal modules i.e. debug but not with the WHEN statement.
This works fine:
- debug:
msg: "{{ls_bin.results[item[0]].stdout}}"
with_indexed_items:
- "{{bob}}"
Any help or pointers will be appreciated.
A:
The here were two issues:
One of the as correctly pointed by @Konstantin Suvorov was that I did not use the quotation.
The other problem was that I was running the ansible-playbook with --start-at-task and thus skipping the step where smart_link_status was created.
| {
"pile_set_name": "StackExchange"
} |
Q:
ARCore + Location Services
I am wondering is there any options for combining existing ARCore early stage with Google Location in order to place AR objects over lat/lng in the real world? I know this one is possible with ARKit but haven't found any information on such via ARCore.
Any ideas? Thanks in advance.
A:
A option that's recently emerged would be: https://www.appoly.co.uk/arcore-location/
It allows you to render objects at a GPS location. Currently it offers two example renderers - an annotation, or a 2D image - however you can implement your own custom ones based on the example code which shows 3D models.
It's worth noting that this is based around Android SDK and not Unity etc.
A:
I think that this is not 0/1 type question :)
First of all ARCore is SDK only for mapping the surrounding. It has no computer vision and/or location capabilities.
Your request is possible but you must combine two elements. First you need to work with location (GPS) and calculate that selected location lat/lng is in your view. This quite simple, you can find a lot of tutorials about that.
Than when you will be sure where this point is ( you can also calculate the bearing that will help here) you can use ARCore to pin the 3D model to the world. Probably you will have to make some kind of transformation to change the real world coordinates to your screen
Making the answer simpler: ARCore itself is not able to that, but combining different tools will allow you to achieve this goal
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I create a security group if none is specified in a parameter in a cloudformation script?
I have a parameter for security group:
"Parameters" : {
"SecurityGroup" : {
"Description" : "Name of an existing EC2 Security Group ",
"Type" : "String",
"Default" : "default",
"MinLength": "1",
"MaxLength": "64",
"AllowedPattern" : "[-_ a-zA-Z0-9]*",
"ConstraintDescription" : "can contain only alphanumeric characters, spaces, dashes and underscores."
},
},
But rather than use the default, if no parameter is specified I'd like to create one. Is this possible?
A:
These were likely added after this question was asked, but for anyone that comes across this now, this can be done with Conditions in CloudFormation.
So if we start with your Parameters declaration
"Parameters" : {
"SecurityGroup" : {
"Description" : "Name of an existing EC2 Security Group ",
"Type" : "String",
"Default" : "default",
"MinLength": "1",
"MaxLength": "64",
"AllowedPattern" : "[-_ a-zA-Z0-9]*",
"ConstraintDescription" : "can contain only alphanumeric characters, spaces, dashes and underscores."
},
},
We could add a Conditions declaration, with a condition ShouldCreateSecurityGroup
"Conditions" : {
"ShouldCreateSecurityGroup" : {"Fn::Equals" : [{"Ref" : "SecurityGroup"}, "default"]}
},
This condition can now be used to tell CloudFormation whether to create a security group:
"Resources": {
"NewSecurityGroup": {
"Type" : "AWS::EC2::SecurityGroup",
"Condition" : "ShouldCreateSecurityGroup"
"Properties" : {
"SecurityGroupEgress" : [ Security Group Rule, ... ],
"SecurityGroupIngress" : [ Security Group Rule, ... ],
}
}
}
Then when you go to reference the value in this, you can use the Fn::If Conditional function to say whether you want to use the value from the SecurityGroup parameter or the NewSecurityGroup Resource. For example, for passing the value into the SecurityGroups parameter of an EC2 instance, we could use {"Fn::If} like:
"Server": {
{
"Type" : "AWS::EC2::Instance",
"Properties" : {
...
"SecurityGroups" : [ {"Fn::If": ["ShouldCreateSecurityGroup", {"Ref": "NewSecurityGroup"}, {"Ref": "SecurityGroup"}]} ],
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to (properly) map Active Directory attributes to outgoing claims?
So I'm trying to figure out how to map employee numbers from active directory as claims in my claims-aware app. We need some kind of key-value in our app so that accounts don't get orphaned when people change their names (marriage etc.).
What's the proper way to map these attributes as claims? Below I've done it in what seems to be the obvious way to do it, but on login, we're getting 'an error occurred' and an entirely useless error message, which I will attach at the bottom.
A:
For anyone with the same problem, just use the settings in the question (they have been edited to reflect some changes I made). These will work to add an employee number to an outgoing claim in ADFS 3.0.
| {
"pile_set_name": "StackExchange"
} |
Q:
Class is not abstract and does not override abstract method keyReleased(KeyEvent) in KeyListener
I am trying to make a small game where you have to dodge rectangles as an oval and I encountered this problem.
Dodge is not abstract and does not override abstract method keyReleased(KeyEvent) in KeyListener
I have scoured the internet to try to find an answer but I cannot find a fix to it.
package dodge;
import java.awt.event.KeyListener;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.Graphics;
public class Dodge extends JPanel implements KeyListener {
private int x = 5, y = 5;
public Dodge(){
setSize(new Dimension(500, 400));
setPreferredSize(new Dimension(500, 400));
//setBackground(Color.BLACK);
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE);
g.fillOval(x, y, 20, 20);
repaint();
}
public static void main(String[] args) {
Dodge game = new Dodge();
JFrame frame = new JFrame();
frame.setTitle("Dodge the Rectangles");
frame.add(game);
frame.pack();
frame.setResizable(false);
frame.setSize(new Dimension(500, 400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
A:
As already pointed out, you need to write or inherit every method that is required by any interface you implement. As a convenience implementing interfaces, an interface may have associated with it a class that provides default implementations for some or all of its methods.
In the case of KeyListener, the convenience class is java.awt.event.KeyAdapter. It provides empty methods. If you extend it, you only need to directly implement the method you want.
To find the convenience class for an interface, scan its "All Known Implementing Classes" list.
| {
"pile_set_name": "StackExchange"
} |
Q:
CPU Architecture
Is there a distinct hardware advantage between CPU's? My specific requirement will be for C++ coding and high end numerical analysis. I am building a new desktop system and considering the advantages of AMD vs Intel. Since graphics are of little concern, I'm having difficulty making that determination via google.
Specifically, I'm trying to determine which of the following CPUs I should go with:
AMD Opteron 6378
AMD FX-9590
Intel Xeon E5-2620 v4
Intel Core i7-5820K
I will be compiling software and using matlab and mathematica to do HPC.
A:
This somewhat depends on the compiler, linker, and interpreter. If you are using a framework that is optimized for a certain CPU then you most likely want to go for that CPU architecture.
At the assembly level, they both use the same instruction set and there isn't a distinct advantage. With C++, if you use something like Visual Studio, I found a site that performed benchmarks on Windows 8 - VS 2012 - Firefox compile. Here are the results: benchmarks. Although this shouldn't be a definitive stamp of success for Intel since it is somewhat dated, for other benchmarks you can find on that site, Intel does win in almost all cases with the i7 architecture. So although you don't really care about graphics, other applications you may run on your machine may have noticeable differences in performance in comparison.
EDIT: I've noticed the question has been updated. Because of your specific requirements choices, I would definitely go with Intel. Now, between the two if you are going to utilize multi-core processing, then the Intel Xeon E5-2620 v4 will be optimal. Looking at this link: Core i7 vs Xeon you can see that in terms of multi-core processing Xeon performs better in benchmarks.
One last thing, if price is a factor at all the Core i7-5820K can be considered over the Xeon. Just looking at a quick price check on Google between the two, the Core i7 is cheaper.
| {
"pile_set_name": "StackExchange"
} |
Q:
Domain redirection and suspension
I have a site developed in ASP.NET and hosted on a windows server using shared windows hosting account at godaddy.
I developed a replica of my website in php and hosted my php site on a free hosting service (php, linux, mysql) and its working fine. This is on a shared subdomain. Example (mysite.freehostprovider.com)
Now I want to continue using the free hosting service. So I would like my site to be redirected from www.mysite.com to mysite.freehostprovider.com
Since I have not paid for Windows hosting. They have stopped hosting for my site. But my domain is valid till 2010. What do I need to do to see my website go live @ www.mysite.com
My free hosting provider supports redirection. I tried but wasn't successful.
Any help will be appreciated.
Thanks
A:
You need to enable forwarding or redirection from your domain registrar. If it is GoDaddy you are using then check out the "Forwarding a Domain" portion of this support article (page 4): http://help.godaddy.com/article/2227
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is it correct to conceptualize LIGO's mirrors as "test masses?"
In the LIGO paper on the first detection of gravitational waves, they have a diagram of one of the interferometers in which they label the mirrors with the conceptual label of "test masses." The collaboration has a page with some photos of the mirrors, where they mention that the masses are 40 kg, although obviously the actual mass would be irrelevant.
What is a good conceptual explanation of why it is valid to think of the experiment in terms of these four test masses, pretending that they're floating in space? After some helpful discussion in comments with Sean E. Lake, several possibilities occur to me:
Even if the mirrors were anchored to the ground rather than suspended loosely, the ground is in some sense so elastic that it wouldn't matter that the ground exists. To matter, the ground would have to be so stiff that signals would propagate in it at speeds on the order of $c$. Actually, signals propagate in it at the speed of seismological waves, which are many orders of magnitude lower. Suspension rather than rigid anchoring is required because of noise from ground vibration.
If the mirrors were anchored to the ground, then the detected signal would be zero, even in the absence of noise from ground vibration.
Logically, if the metric in general relativity is to mean anything, then it must relate to rigid measuring rods. The ground underlying one arm of the detector is a measuring rod.
A:
As part of the vibration isolation process, they're suspended (see also), not rigidly coupled to the ground. So, they are connected, but the response to ground vibrations is going to be very frequency dependent, and in the relevant frequency range and amplitude range, they're just hanging there in space.
"To matter, the ground would have to be so stiff that signals would propagate in it at speeds on the order of c." I don't think so. What your describing is a a system with a resonant response and quality factor (width of resonant response). So the limiting factor is how it responds to the relevant frequency and if the quality factor is high enough for the response to build to observable before the signal ends.
| {
"pile_set_name": "StackExchange"
} |
Q:
Current recommendation for enabling session in Azure Websites for Session variables and TempData?
I have a MVC3, ASP.NET 4.5 web application deployed on Azure Websites, using SQL Azure.
Currently I am using some "inproc" Session variables which I need to remove since I am going to start using multi website instances. I could just store the Session variable values in the SQL Azure DB, but I am also using TempData, which also uses Session state, "under the bonnet". Due to TempData use, I do need to implement an "out of proc" session solution.
I have seen some recommendation for using AppFabric caching, but I am unsure whether this is still current, and whether it is correct for Azure websites.
Also my development setup is on a Windows 7 machine with SQL Server 2008 R2. So a solution should be transferable with minimum pain.
There is also a "thread agility" issue with session variables, and a open source solution has been created using REDIS caching, but I have no experience of this, or REDIS. See: GitHub site
So thoughts I have are:
1) Angieslist/AL-redis custom provider, see: GITHUB link . Not entirely sure that this can be used in a Azure Websites application.
2) Appfabric. Not sure if this is relevant or current for Azure Websites.
3) SQL Azure session provider.
4) Azure Table storage.
5) Use a custome TempData provider to persist via cookies ie https://www.nuget.org/packages/BrockAllen.CookieTempData.dll/1.2.2, and then remove other session variables.
I would be very grateful for advice on a good Azure Websites session implementation mechanism which is simple. My data is pretty simple. I think I have one object which I quess I will need to serialize, probably via Json.NET
A:
If you have more than one instance of an Azure Web Site, sticky sessions are enabled by default by the load balancer. This means that a user will be directed to the same instance (server) and that you'll be able to use session state in your app.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding a permutation to satisfy given condition
In $S_n$ with n=10, find a permutation $a$ such that $axa^{-1} = y$ if $x=(1,2)(3,4)$ and $y=(5,6)(3,1)$
I don't know how to start doing this. I read something like I need to get, for this case, $$(a(1),a(2)) \qquad \mbox{ and} \qquad (a(3),a(4))$$ but I am not sure where will I get their equivalents. Also, will those be my permutation $a$? Please help. I have problems very similar to this.
A:
we need a permutation $a$ such that $axa^{-1}=a(1,2)a^{-1}\cdot a(3,4)a^{-1}$ equals to $(5,6)(3,1)$. this can be done if : $a(1,2)a^{-1}=(a(1),a(2))=(5,6) $ and $a(3,4)a^{-1}=(a(3),a(4))=(3,1) $ so I think that you can continue from here , not that the remaining integers can be fixed or just complete the permutation
| {
"pile_set_name": "StackExchange"
} |
Q:
How can we make an event to trigger when something published from specific Publication?
How can we make an event to trigger when component published from a specific Publication?
A:
The event handlers (triggers) are system-wise, so you will have to control the publication scope from within the event itself. I would check it at the very beginning, see the example below:
[TcmExtension("YourEventSystem")]
public class YourEvent: TcmExtension
{
public YourEvent()
{
Subscribe();
}
public void Subscribe()
{
EventSystem.Subscribe<RepositoryLocalObject, CheckInEventArgs>(HandlerForInitiated, EventPhases.Initiated);
}
private void HandlerForInitiated(RepositoryLocalObject subject, CheckInEventArgs args, EventPhases phase)
{
//Check for publication id match here
if (subject.OwningRepository.Id != "your_publication_uri")
{
return;
}
//Your logic here...
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending 2 streams to FFmpeg from nodejs
I am trying to send 2 ReadableStreams to FFmpeg from nodejs. I have tried using fluent-ffmpeg library to do this, but it only supports sending one stream for processing. Check here
My problem is:
I have 2 incoming mono audio streams, I want to send them to ffmpeg to create a stereo stream, which I will then send to google's speech to text service, to generate a transcription.
I am successfully receiving both the mono streams to the nodejs server.
How to utilize FFmpeg to merge them in realtime is still unclear, I could spawn a FFmpeg child process, but I'm not sure how to give 2 ReadableStreams as inputs and get the output as another stream? FFmpeg supports multiple input streams.
I can merge the 2 mono streams if they are in two separate files with this code.
const { spawn } = childProcess;
const ffmpeg = spawn('ffmpeg', [
'-i', this.phoneAudioFile,
'-i', this.micAudioFile,
'-filter_complex', '[0:a][1:a]amerge=inputs=2[a]',
'-map', '[a]',
this.outputLosslessFile,
]);
How can I acheive the same using 2 streams instead of 2 files?
EDIT
The incoming streams both have PCM audio data.
This entire process runs on a linux Ubuntu server.
The final output must be a wav file.
A:
Assuming your source audio streams are regular PCM audio (such as what is most commonly found in WAV files), I would merge the streams internally in your application, and output a single stream to FFmpeg.
This can be done as simply as alternating which stream you read from, effectively interleaving the samples.
If your samples are 16-bit, then each sample is two bytes. So, your stream will look like this:
[LL][RR][LL][RR][LL][RR]
(where each LL is 2 bytes of a single sample for the left channel, and the same for RR)
If you're going to pipe this into FFmpeg, you'll need to set up the appropriate parameters for RAW PCM. Or, you can generate a WAV file header in your application as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why when I send a GET request using XMLHttpRequest, I get two readyState 1?
<div id="myDiv"></div>
<script>
var xmlhttp = new XMLHttpRequest();
document.getElementById("myDiv").innerHTML += xmlhttp.readyState + "<br/>";
xmlhttp.onreadystatechange = function() {
document.getElementById("myDiv").innerHTML += xmlhttp.readyState + "<br/>";
}
xmlhttp.open("GET", "example.com", true);
xmlhttp.send();
</script>
I get this in display:
0
1
1
2
3
4
Why there are two 1s?
My browser is firefox 17.0.
A:
Ready states are well defined for XML HTTP object: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#Properties.
But sequences of ready states seem to be different for every browser, so you can't rely on particular sequence of states in your code.
FF 19: 0, 1, 1, 2, 3, 4
Chrome 24: 0, 1, 2, 3, 4
Opera 12.12: 0, 1, 2, 3, 4
Safari 5.1: 0, 1, 2, 3, 4
IE 9: 0, 1, 1, 2, 3, 4
You can test your browser here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Retaining textbox value in jquery
In the following code every time button is clicked the alter shows the value of the variable counter=20 which is the value of null text box.
Kindly guide regarding this.
var username = $("#<%= uname.ClientID %>").val();
var pwd = $("#<%= pwd.ClientID %>").val();
var counter = (function () {
var counter1 = 0;
return function () {
if (username == "DEF" && pwd == "5678") {
counter1 = 6;
}
else if (username == "" && pwd == "") {
counter1 = 20;
}
else {
counter1 = -1;
}
return counter1;
};
return false;
})();
$("#<%= Login.ClientID %>").click(function makecounter1() {
counter();
if (counter() != -1) {
alert(counter());
}
else {
alert("Wrong Credentials");
}
return false;
});
Why counter doesn't show other value.
A:
The values are set when the page is loaded and is not getting refreshed.
move the code
var username = $("#<%= uname.ClientID %>").val();
var pwd = $("#<%= pwd.ClientID %>").val();
into the function counter and it should work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where is Create Unit Test in VS 2017?
I understand that this question has been asked before on SO and it appears that this feature was removed from VS at some point. But I am looking at a Microsoft tutorial right now and that says there should be a Create Unit Test function in VS 2017.
I'm trying to test ASP.NET Core MVC controllers. I have followed the steps for creating a test project. But I still can't see any such option when I right click a namespace/class/method.
EDIT: I'm using Visual Studio 2017 Community Edition
A:
The answer below relates to .NET Core/Standard only. If you're missing the Create Unit Tests option for a full .NET Framework project see here.
Current status: It's now working for .NET Core!
I now have the Create Unit Tests context menu in my Core 3 solution running on Visual Studio Professional 2019 Version 16.3.0 Preview 3.0. Not sure exactly when it reappeared as I've been updating regularly with each new preview version.
History
See the updates below for more history and details.
Original answer June 2017
This GitHub entry from Microsoft's Jayarani Garg, confirmed it is only available for projects targeting the full .NET framework:
Jayarani Garg [MSFT] · Feb 27 2017 at 06:09 AM Hi,
Thank you for your feedback. "Create Unit Test" is currently not
supported for .Net Core projects.
That's by design rather than a bug according to this Visual Studio Team comment on that same Visual Studio Developer Community page:
Visual Studio Team ♦♦ · Mar 10 2017 at 01:06 PM
Thank you for your feedback! The Visual Studio team has determined that this issue
is not a bug. However, we will consider this feedback and have created
https://github.com/Microsoft/vstest/issues/592 to track this. Please
feel free to vote for the issue.
The github issue referred to above on the Microsoft VS Test repo Create Unit Test Context Menu Missing (.net core projects) is slightly confusing. It's asking for this feature to be added for .NET Core projects too but then a Microsoft employees talk about having a fix for an issue. I believe that employee is referring to the old bug where the context menu option wasn't working for full .NET framework projects either as discussed in this question which is also mentioned in that thread. As far as I can see that thread is not saying they've added the menu option for .NET Core projects.
I've also just checked on a copy of Visual Studio Professional 2017, version 15.2 (26430.6) and I do have the Create Unit Tests option for a project that targets the full .NET framework (this one targets .NET Framework 4.5.1):
But I don't have it for a project that targets .NETCoreApp 1.1:
Update June 2018
Microsoft have taken notice of the upvotes for the feature request and are planning to introduce the context menu option for .NET Core projects in release 15.8:
Manish Jayaswal [MSFT] replying to Daniel Tibi · Apr 06 2018 at 10:30 PM
Getting this functionality added to .NET Core projects requires some
significant changes in the new project system - which drives the .NET
Core projects. This work is getting tracked in project system GitHub
repo in this issue
(https://github.com/dotnet/project-system/issues/3425) . This issue is
expected to be resolved in 15.8 release timeframe so unfortunately,
create unit test functionality for .NET Core projects would not be
available in the upcoming 15.7 release. We fully understand that this
is a key feature and would do our best to make it available as early
as possible.
Update July 2018
The Create unit test method stubs with the Create Unit Tests command page has been updated now to reflect that this doesn't work for .NET Core.
Update August 2018
As pointed out by @gartenriese below, the GitHub issue 3425 Microsoft described as tracking this work was moved to the 15.9 milestone on 02 August 2018.
Update January 2019
The unit testing feature seems to be reliant on, or blocked by, another part of the development. That part is now slated for VS 16.1, i.e VS 2019, and is also further down the priority list than EF Core 3.0 (which is one of the main features of VS 16) according to this GitHub post by Microsoft's David Kean.
May 2019 update
The Create Unit Tests context menu option isn't supported (yet) for projects that target .NET Core and .NET Standard.
The documentation was updated to reflect this in July 2018 and now states:
The Create Unit Tests menu command:
Is available in the Community, Professional, and Enterprise Editions of Visual Studio 2015 and later.
Supports only C# code that targets the .NET Framework.
Is extensible, and supports emitting tests in MSTest, MSTest V2, NUnit, xUnit format.
Is not yet available in .NET Core projects.
This feature was slated for release in Version 15.9 of Visual Studio, but now appears to have been pushed back to Version 16.1.
I've tested this in a .NET Core 2.2 project in Visual Studio Professional 2019 RC (version 16.0.0) and I can confirm it's still not working there - as expected as per the above answer.
I've also just tested Visual Studio Professional 2019 Preview (version 16.1.0 Preview 2.0) and it's not available there either, so it doesn't look like Microsoft have got to this yet.
| {
"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.