text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How do I set the QComboBox width to fit the largest item? I have a QComboBox that I fill with QString using:
comboBox->addItem(someString);
When I start my GUI application the width of the QComboBox is always 70, even if the smallest item is much larger. How can I dynamically set the width of a QComboBox, for instance, to the largest QString within the comboBox?
Edit:
After some further testing I found the following solution:
// get the minimum width that fits the largest item.
int width = ui->sieveSizeComboBox->minimumSizeHint().width();
// set the ComboBoxe to that width.
ui->sieveSizeComboBox->setMinimumWidth(width);
A: According to the docs the default SizeAdjustPolicy is AdjustToContentsOnFirstShow so perhaps you are showing it and then populating it?
Either populate it first before showing it or try setting the policy to QComboBox::AdjustToContents.
Edit:
BTW I'm assuming that you have the QComboBox in a suitable layout, eg. QHBoxLayout, so that the size hint/policy is actually being used.
A: I was searching for a solution to only change the size of the dropdown menu of the combobox to fit the largest text without changing the size of the combobox itself.
Your suggestion (@Linoliumz) did help me find the solution. Here it is :
Suppose you have a combobox called cb:
C++:
width = cb->minimumSizeHint().width()
cb->view().setMinimumWidth(width)
PyQT :
width = cb.minimumSizeHint().width()
cb.view().setMinimumWidth(width)
A: Qt (4.6) online documentation has this to say about QComboBox:
enum SizeAdjustPolicy { AdjustToContents, AdjustToContentsOnFirstShow, AdjustToMinimumContentsLength, AdjustToMinimumContentsLengthWithIcon }
I would suggest
*
*ensuring the SizeAdjustPolicy is actually being used
*setting the enum to AdjustToContents. As you mention a .ui file I suggest doing that in Designer. Normally there shouldn't be anything fancy in your constructor at all concerning things you do in Designer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3151798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Watson Speech to text could not resolve host I'm trying to use the ibm watson speech to text service. Using Curl and the appropriate credentials i'm getting an error and don't understand why. I'm new to this so i need some help
I'm using this command-lines to get the text out of an audio file:
curl -u username:password -X POST \ --header "Content-Type: audio/flac" \ --header "Transfer-Encoding: chunked" \ --data-binary @/tmp/0001.flac \ "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true"
and i'm getting this error:
curl: (6) Could not resolve host: --header
curl: (6) Could not resolve host: Content-Type
curl: (6) Could not resolve host: --header
curl: (6) Could not resolve host: Transfer-Encoding
curl: (6) Could not resolve host: --data-binary
curl: (6) Could not resolve host:
curl: (1) Protocol https not supported or disabled in libcurl
does anybody know what i'm doing wrong?
A: Remove the / from the curl command, we use them in the API Reference to better display the curl commands but they don't work in Windows.
curl -u username:password -X POST
--header "Content-Type: audio/flac"
--header "Transfer-Encoding: chunked"
--data-binary @/tmp/0001.flac
"https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true"
The command will work in unix based system like Ubuntu or Mac.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35104090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: convert string hours:minutes:sec.milisec to seconds An absolute time is given in stored in this format:
time = "000:03:07.447"
How can this string be converted to seconds in an elegant way?
Update:
As suggested by Harper89
3600*#1 + 60*#2 + #3 & @@ ToExpression[StringSplit["000:00:04.424", ":"]]
Szabolcs suggested to use AbsoluteTime
From Mathematica help: AbsoluteTime gives the total number of seconds since the beginning of January 1, 1900, in your time zone.
AbsoluteTime[{"000:03:07.447", {"Hour", ":", "Minute", ":", "Second",
".", "Millisecond"}}]
- AbsoluteTime[{"000:00:00.000", {"Hour", ":", "Minute", ":", "Second",
".", "Millisecond"}}]
This works both
A: Parse the string to form an array between each of the : using something like split()
*
*For the first set multiply by the number of seconds in an hour
*For the second set multiply by the number of seconds in a minute
*For the third set add the number to the total
In other words
totalseconds = array(0)*3600 + array(1)*60 + array(2)
Or in vb.net Code
Dim time As String = "000:3:7"
Dim a() As String
a = longstring.Split(":")
Dim TotalSeconds as Integer = (a(0) * 86400) + (a(1) * 3600) + a(2))
Trace.WriteLine(TotalSeconds.toString)
From the Tag definition of mathmatica
Not to be confused with mathematics (math).
OOPs..
A: Just as harper89 described, in Mathematica:
FromDigits[ToExpression /@ StringSplit[time, ":"], 60]
A: Try the following:
AbsoluteTime[{"000:03:07.447",
{"Hour", ":", "Minute", ":", "Second", ".", "Millisecond"}}]
(* ==> 187.447 *)
The key was giving an explicit date format (see the docs of DateList[])
This solution works in Mathematica 8. It appears that in version 7 (and possibly also in version 6) one needs to correct the result, like this:
AbsoluteTime[{"000:03:07.447",
{"Hour", ":", "Minute", ":", "Second", ".", "Millisecond"}}] -
AbsoluteTime[{"0", {"Hour"}}]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9278771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to check ReactDOM.render method to be called with a react component argument? Code here:
index.tsx:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export function Loading(props) {
return <div {...props}>loading...</div>;
}
export class MyComponent extends Component {
static show() {
const container = document.createElement('div');
container.classList.add('loading-container');
document.body.appendChild(container);
ReactDOM.render(<Loading className="loading" />, container);
}
render() {
return <div>my component</div>;
}
}
index.test.tsx:
import React from 'react';
import { Loading, MyComponent } from './';
import ReactDOM from 'react-dom';
describe('MyComponent', () => {
it('should pass', () => {
const renderSpy = jest.spyOn(ReactDOM, 'render');
MyComponent.show();
const loadingContainer = document.body.querySelector('.loading-container');
// 1. failed
// expect(renderSpy).toBeCalledWith(expect.any(Loading), loadingContainer);
// 2. TS type error
// expect(renderSpy).toBeCalledWith(Loading, loadingContainer);
// 3. TS type error
// expect(renderSpy).toBeCalledWith(<Loading />, loadingContainer);
});
});
I have tried three ways to assert that renderSpy to be called with the Loading component. But none of them work.
How can I solve it?
A: I think it's you're just missing the className="loading" in <Loading />:
import { Loading, MyComponent } from "./index";
import ReactDOM from "react-dom";
describe("MyComponent", () => {
it("spying on ReactDOM", () => {
const spy = jest.spyOn(ReactDOM, "render");
MyComponent.show();
expect(spy).toHaveBeenCalledWith(
<Loading className="loading" />,
document.body.querySelector(".loading-container")
);
});
});
Alternatively, you can mock ReactDOM instead of spying on it:
import { Loading, MyComponent } from "./index";
import ReactDOM from "react-dom";
jest.mock("react-dom", () => ({
__esModule: true,
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
Events: [],
},
createPortal: jest.fn(),
findDOMNode: jest.fn(),
flushSync: jest.fn(),
hydrate: jest.fn(),
render: jest.fn(),
unmountComponentAtNode: jest.fn(),
unstable_batchedUpdates: jest.fn(),
unstable_createPortal: jest.fn(),
unstable_renderSubtreeIntoContainer: jest.fn(),
version: "17.0.1",
}));
describe("MyComponent", () => {
it("mocking ReactDOM", () => {
MyComponent.show();
expect(ReactDOM.render).toHaveBeenCalledWith(
<Loading className="loading" />,
document.body.querySelector(".loading-container")
);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66594037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the max datetime for particular date among multiple dates, data example is as below Table has this value:
Heading 1
Heading 2
xyz
01-APR-2022 12.11.21.000000000 AM
xyz
01-APR-2022 12.11.29.000000000 AM
xyz
01-APR-2022 12.12.21.000000000 AM
xyz
02-APR-2022 12.09.21.000000000 AM
xyz
02-APR-2022 12.11.21.000000000 AM
xyz
02-APR-2022 12.22.21.000000000 AM
need below output:
Heading 1
Heading 2
xyz
01-APR-2022 12.12.21.000000000 AM
xyz
02-APR-2022 12.22.21.000000000 AM
A: informatica only solution -
*
*Create an exp transformation with three ports.
in_out_Heading1
in_out_Heading2
out_date_trunc=TRUNC(in_out_Heading2)
*Next, use an agg transformation with below ports.
in_out_Heading1 --group by port
in_Heading2
in_date_trunc --group by port
out_Heading2=MAX(in_Heading2)
And then connect out_Heading2 and in_out_Heading1 to your final target.
A: You can group by extracted date value, so need a conversion such as the one below
SELECT heading1, MAX(heading2)
FROM t
GROUP BY heading1, TRUNC(heading2)
the above SELECT statement is based on the Oracle database, you can replace TRUNC(heading2) depending on your current DBMS. The data type of heading2 is presumed to be TIMESTAMP
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72160581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I'm getting Error in typeof(x) : object 'ParcelArea.m2.' not found I am getting this strange error {I'm getting Error in typeof(x) : object 'ParcelArea.m2.' not found } even though I see the variable name in my dataframe.
> names(Cadastral)
[1] "CadastralZoneNameAB" "CadastralZoneCode" "ParcelCadastralNumber"
[4] "Urban_Rural" "ParcelArea.m2." "LandType"
[7] "ParcelLocalityName" "ParcelCadastralObjectName" "ParcelAddressText"
[10] "CultureNumber" "ParcelsCurrentUse" "CultureArea.m2."
[13] "ParcelTypeOfUse" "IsNatural" "Name"
[16] "FirstName" "FatherName" "IDCode"
[19] "IDType" "MunicipalityName" "HouseNumber"
[22] "PersonAddressDescription" "SharedQuotaPercentage" "SharedQuotaNumerator"
[25] "SharedQuotaDenominator"
LOOK at the variable 5 "ParcelArea.m2."
Code I'm using is:
> Cadastral%>% group_by(CadastralZoneNameAB,ParcelTypeOfUse)%>%
+ + summarise(ParcelArea.m2.=sum(ParcelArea.m2.))
Error in typeof(x) : object 'ParcelArea.m2.' not found
It is worth mentioning that, yesterday this same code worked at this particular dataset. Why I'm getting this error today is frustrated?
See the yesterdays code and the output:
> Cadastral%>% group_by(CadastralZoneNameAB,ParcelTypeOfUse)%>%
+ summarise(ParcelArea.m2=sum(ParcelArea.m2.))
# A tibble: 3 x 3
# Groups: CadastralZoneNameAB [?]
CadastralZoneNameAB ParcelTypeOfUse ParcelArea.m2
<fctr> <fctr> <int>
1 HAJVALI Bujqësore 608
2 MATIÇAN Bujqësore 400
3 PRISHTINË Tokë Ndërtimore 895
TODAY same code, same dataset different output :(
> Cadastral%>% group_by(CadastralZoneNameAB,ParcelTypeOfUse)%>%
+ + summarise(ParcelArea.m2=sum(ParcelArea.m2.))
Error in typeof(x) : object 'ParcelArea.m2.' not found
Could you please help me define this problem.
Thank you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51517179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Collision detection with rotated sprites, how to get correct bounding Rect? I am currently creating an android game and implemented collision detection a while back. I am simply drawing a Rect around sprites using their position, width and height and seeing if they intersect other Rects. However, my sprites now rotate depending on their trajectory, but I cannot find how to rotate the Rect so the bound is correct. Any suggestions?
Thanks
Andy
A: Rect objects are usually axis-aligned, and so they only need 4 values: top, left, bottom, right.
If you want to rotate your rectangle, you'll need to convert it to eight values representing the co-ordinate of each vertex.
You can easily calculate the centre value by averaging all the x- and y-values.
Then it's just basic maths. Here's something from StackOverflow:
Rotating a point about another point (2D)
Your eight values, or four corners are (assuming counter-clockwise from the top right):
v0 : (right, top)
v1 : (left, top)
v2 : (left, bottom)
v3 : (right, bottom)
Create your own rectangle object to cope with this, and compute intersections etc.
Note that I've talked about how to rotate the rectangle's vertices. If you still want a bounding box, this is normally still considered to be axis-aligned, so you could take the max and min of the rotated vertices and construct a new (larger) rectangle. That might not be what you want though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14468793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to paginate listview in jQuery-Mobile? I will like to display a long list in jQuery-Mobile, but I will like to split the list into multiple pages with previous - next buttons similar to gmail applications. The number of items per page will depend on the page height and will be different.
Even the answer on how to decide number of elements based on screen height will help solve the problem as creations of buttons and pages though not easy, is possible.
Thank you in anticipation.
A: I assume you want the pagination to work for the user, so it should be done server-side. Paginating the content that was already downloaded doesn't make much sense (unless you only care for a feeling)
*
*Before showing the list - get the optimum length for a single page
*Put it (with a bit of js) in the URL as a parameter
*Paginate with this setting like in the old times
To determine the number:
Make the button that lets user go to the list a 1 element listview.
Get the window height, substract height of heder and footer, divide by the 1 element height and put as a parameter to the link.
done
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6766842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: problem converting calendar to java.util.Date I need to create a java.util.Date object with an Australian timezone. this object is required for tag libraries used in downstream components (so I'm stuck with Date).
Here's what I have attempted:
TimeZone timeZone = TimeZone.getTimeZone("Australia/Sydney");
GregorianCalendar defaultDate = new GregorianCalendar(timeZone);
Date date = defaultDate.getTime();
However, "date" always returns the current local time (in my case, ET). What am I doing wrong here? Is it even possible to set a Date object with a different timezone?
Update:
Thanks for the responses! This works if I want to output the formatted date as a string, but not if I want to return a date object. Ex:
Date d = new Date();
DateFormat df = new SimpleDateFormat();
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
String formattedDate = df.format(d); // returns Sydney date/time
Date myDate = df.parse(formattedDate); // returns local time(ET)
I think I'm going to end up reworking our date taglib.
A:
Is it even possible to set a Date object with a different timezone?
No, it's not possible. As its javadoc describes, all the java.util.Date contains is just the epoch time which is always the amount of seconds relative to 1 january 1970 UTC/GMT. The Date doesn't contain other information. To format it using a timezone, use SimpleDateFormat#setTimeZone()
A: getTime is an Unix time in seconds, it doesn't have the timezone, i.e. it's bound to UTC. You need to convert that time to the time zone you want e.b. by using DateFormat.
import java.util.*;
import java.text.*;
public class TzPrb {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
System.out.println(df.format(d));
df.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println(df.format(d));
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4129906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Old Session id not available app.py file having flask application. test_app.py file having code related request module to invoke flask app url with id values.
Both app.py and test_app.py i am ruing in two different command prompt.
when request is sending 2nd time with id="10122" from the test_app.py the old session id is None. Why it is None? already my first request set a id in the session and second time i am accessing the old(first) request id.
for my second request with id = "10122" old session id should be 10121.
1.current output:
Old session id: None
New session id: 10121
2.Expected Output:
Old session id: 10121
New session id: 10122
(base) H:\Python\DevPractice\day4>python app.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
********started********
Old session id: None
New session id: 10121
************end**********
127.0.0.1 - - [21/Sep/2019 14:28:27] "POST / HTTP/1.1" 200 -
********started********
Old session id: None
New session id: 10122
************end**********
127.0.0.1 - - [21/Sep/2019 14:28:27] "POST / HTTP/1.1" 200 -
invoking from the test_app.py
(base) H:\Python\DevPractice\day4>python test_app.py
results
results
*
*app.py file
from flask import Flask, make_response, redirect, session, url_for, request
SECRET_KEY = 'develop'
app = Flask(__name__)
app.config.from_object(__name__)
@app.route('/', methods=['POST'])
def index():
print("********started********")
old_id = session.get('id', None)
print("Old session id:", old_id )
if request.method == 'POST':
session['id'] = request.form['id']
#session['hello'] = 'world!'
new_id = session.get('id', None)
print("New session id:", new_id )
print("************end**********")
return "results"
if __name__ == '__main__':
app.run()
*test_app.py file
import requests
list_id = ["10121", "10122"]
for i in list_id:
payload = {'id': i}
r = requests.post("http://127.0.0.1:5000/", data=payload)
print(r.text)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58040155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: django css setup not working I followed some tips from related questions in here, and tried the documentation but failed so far to get css file working.
Note that css (obviously) works perfectly fine if I place it within the template, but I can't import it from static folder.
So in my app folder, I created a static folder, within which I created another folder called static: app->static->style.css
When I run collectstatic, it gets style.css, and places it in: projectfolder->static->style.css
All of this is working fine.
My static settings were set automatically, I changed it based on some answers I read in related questions, but still didn't work:
MEDIA_ROOT = u'/home/user/projectfolder/media'
MEDIA_URL = '/media/'
STATIC_ROOT = u'/home/user/projectfolder/static'
STATIC_URL = '/static/'
In my template, I have:
{% load staticfiles %}
....
<head>
<link rel="stylesheet" href="{{ STATIC_URL }}style.css" />
....
Clearly I'm missing something, when I reload the website, no css is shown. In my css I have clearly set the body background to test it, but it doesn't change.
Extra info:
- Debug is set to true
- Using the latest Django version .10
Any help or direction would be appreciated,
thanks in advance.
A: When you view the page's source code from what path is it trying to load your style?
Try this - <link rel="stylesheet" href="{% static "style.css" %}" />
Also I would change MEDIA_ROOT and STATIC_ROOT to MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and STATIC_ROOT = os.path.join(BASE_DIR, 'static'). This way both paths are being built by the system and it's harder to mess up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39168010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: sqlite3 "OperationalError: near "(": syntax error" python simply put i am trying to make a sql database table and input data into it. I have it working in a simpler way, but when I put it into my script it results in this error. I'm hoping its something simple I missed. Any help/advice would be greatly appreciated.
conn = sqlite3.connect('Data1.db')
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE Data_Output6
(date text, output6MV real)''')
Averages_norm = []
for i, x in enumerate(Averages):
Averages_norm.append(x*output_factor)
c.execute("INSERT INTO Data_Output6 VALUES (%r,%r)" %(xdates[i],Averages_norm[-1]))
conn.commit()
results in the error:
57 for i, x in enumerate(Averages):
58 Averages_norm.append(x*output_factor)
---> 59 c.execute("INSERT INTO Data_Output6 VALUES (%r,%r)"%(xdates[i],Averages_norm[-1]))
60 conn.commit()
61
OperationalError: near "(": syntax error
A: Simply put, let the DB API do that formatting:
c.execute("INSERT INTO Data_Output6 VALUES (?, ?)", (xdates[i], Averages_norm[-1]))
And refer to the documentation https://docs.python.org/2/library/sqlite3.html where is mentioned:
Instead, use the DB-API’s parameter substitution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30257826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to read large xlsm files using apache POI I am trying to read a large xlsm file for which i am getting heap space error,i am using XSSFWorkbook for the large file but still i am getting this .And also i have set the VM argumets -Xmx1024m to eclipse.Here is my code
public class TestSJXLSX {
public static void main(String[] args) throws Throwable {
OPCPackage pkg = OPCPackage.open(new File("D:\\resources\\1712_Reporting.xlsm"));
XSSFWorkbook wb_template;
wb_template = new XSSFWorkbook(
pkg
);
System.out.println("package loaded");
SXSSFWorkbook wb = new SXSSFWorkbook(wb_template); wb.dispose();
wb.setCompressTempFiles(true);
SXSSFSheet sh = (SXSSFSheet) wb.createSheet();
sh.setRandomAccessWindowSize(100);// keep 100 rows in memory, exceeding rows will be flushed to disk
for(int rownum = 4; rownum < 5000; rownum++){
Row row = sh.createRow(rownum);
for(int cellnum = 0; cellnum < 10; cellnum++){
Cell cell = row.createCell(cellnum);
String address = new CellReference(cell).formatAsString();
cell.setCellValue(address);
}
}
FileOutputStream out = new FileOutputStream(new File("D:\\new_file.xlsm"));
wb.write(out);
out.close(); }
}
A: SXSSFWorkbook is for streaming-writing, not reading. Did you try with XSSFWorkbook instead? This will still require quite some memory so might still go OOM with 1024m, depending on the size of the workbook.
Another approach is a streamed reading approach, see e.g. https://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api for some description of this approach. There will be some features that are not supported there, though, so it might or might not be applicable for your use case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48764425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to reassign the values to a textbox after navigating to the backpage in Windows8 metro apps I have created two Pages Page1.xaml and Page2.xaml in windows8 metro apps.
I have created one textbox and Hyperlink in Page1.xaml. Clicking that Hyperlink button after entering some text in textbox in Page1.xaml. Then its navigating to the Page2.xaml. In Page2.xaml I am going to show the text which was entered in the Page1.xaml textbox.
Here after coming to the Page2.xaml I am clicking the back button for going to previous page Page1.xaml. Here I want to show the text in the textbox which I have entered earlier.
But I am getting error when clicking the back button.
Could you please provide me the solution for displaying the text in TextBox of Page1.xaml
Thanks in advance
A: One way to make code available across different script scopes is to use a WinJS namespace.
For example, in page1.js, you would have:
(function(){
function setText(){
var mytext = "";
WinJS.Namespace.define("page1", {
text: mytext
});
}
})();
in page2.js, you'd put the text in that namespace:
(function(){
page1.text = "page 2 text!";
})();
Back in page 1, you can retrieve that value later on:
(function(){
function setText(){
var mytext = "";
WinJS.Namespace.define("page1", {
text: mytext
});
}
function getText() {
document.querySelector("#myTextField").value = page1.text;
}
})();
I'd suggest being a bit more formal about what you put in namespaces, but that's one way to do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11189908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Socket.io like PHP Implementation I am working on a little personal project on Ionic2 framework, and one part of my application requires a chat to be implemented. So I went and read about Socket.IO and it's implementations and it is really awesome. But the drawback for my project is that the frontend will not be able to host NodeJS, so I had to quit the idea of using Socket.io.
is there any alternative/Solution to make the PHPserver maintain a bidirectional connection for the chat? My guessing was to use GET/POST between the Ionic App and the server but that will be heavy on both client and server since it has to check on every short amount of time (less than a second to give the real-time like behavior).
Thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41705473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Slow debugging with VS2015 and Trend Micro anti-virus in our corporation we are using Trend Micro Anti-Virus.
I noticed that when debugging, the "Manages the Trend Micro unauthorized change prevention" process hogs up to 50% CPU usage every time VS is hanged while debugging, and drops down to 0.x% when VS is freed.
We have tried excluding the source code folder from real-time scan but to no avail.
Are there any other ways to fix this? Thank you.
P.S: I know this might not be a SO typical question but as a programmer i cant afford wasting 5 minutes for each mouse-over.
A: Our IT department spoke with Trend technical support and they were able to fix this issue by excluding several folders (source code, VS installation path and others) from the real-time scan.
A: I found a blog post about this: http://blog.aabech.no/archive/debugging-happily-alongside-trend-micro/
Pretty much it is saying that you can use the Trend Micro Performance Tuning Tool to inspect the slowness of your debugging.
For me an the author of the blog post it was the msvsmon.exe which is used for remote debugging and was causing a lot of events which slowed down the whole thing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40717049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can a static class be resolved by the Unity Framework? I wold like the unity framework to resolve a static class "MyStaticObject" specified in my config file. As my class is static, I am getting an error "The type StaticObject does not have an accessible constructor."
My config file looks as below:
<unity>
<typeAliases>
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
<typeAlias alias="StaticObject" type="MyStaticAssembly.MyStaticObject, MyStaticAssembly, Version=1.0.0.0" />
<typeAlias alias="staticobject" type="MyStaticAssembly.MyStaticObject, MyStaticAssembly" />
</typeAliases>
<containers>
<container>
<types>
<type type="StaticObject" mapTo="staticobject" name="My Static Object">
<lifetime type="singleton"/>
</type>
</types>
</container>
</containers>
</unity>
I would highly appreciate any help.
A: Unity (or any IoC container framework) is basically a super-factory, creating objects and handing them to you. How is it supposed to create an instance of a static class?
Refactor your design to use a non-static class. If necessary create a class that wraps the static class and delegates to it.
EDIT: If you specifically want the container to call an existing static factory method, you can use StaticFactoryExtension.
EDIT: Unless you need to swap out implementations after deployment, I'd recommend avoiding XML configuration and writing fluent configuration code (calling container.RegisterType, etc.) in a single place in your application instead. You can still use separate configuration code in your unit tests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2562285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to capture a stringified text "2,000.00" in bytes without the "," and convert it to float64? My goal is to capture a stringified text "2,000.00" in []byte without the , and convert it to float64. The problem is the regex captures Group MUTASI with the ,
The code
package main
import (
"bytes"
"fmt"
"regexp"
)
func main() {
mutasis := [][]byte{[]byte("28,000.00 DB"), []byte("5,000,000.00")}
re := regexp.MustCompile(`(?m)^(?P<MUTASI>[\d,.]+)(?: (?P<TIPE>DB|CR))*$`)
matches := re.FindAllSubmatch(bytes.Join(mutasis, []byte("\n")), -1)
for _, match := range matches {
fmt.Println(string(match[1]))
}
}
What I've did:
*
*use ^(\d+(?:[,\d|.\d]+)*)$ but apparently, ?: is overriden by the brackets ( ).
A: Try this
func toFloat(data []byte) (float, error) {
return strconv.ParseFloat(strings.ReplaceAll(string(data), ",", ""), 64)
}
Split your original byte array by space, then pass it to this function. It will return either the float you need or error
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73558835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to run Openstack-Swift java api? I try to run Openstack-Swift java sdk sample.
I have swift and keystone project to use swift only.
I found this project : https://github.com/woorea/openstack-java-sdk
But, I don't know how to run this project in Window Eclipse.
Should I build all project(nova, etc..) in maven?
Do you know how to run this project or website that post run-way in regular sequence?
A: @stream
I have not tried Woorea but i know a lot many developers are using Jclouds, the link http://developer.rackspace.com/#home-sdks has well documented guide with example how to use the Java SDK.
Hope it helps.
A: looks like you can build SWIFT independently (part of woorea peoject)
as it states in the readme file here:
(com.woorea swift-client 3.0.0-SNAPSHOT)
https://github.com/woorea/openstack-java-sdk
the Maven artifact ID should be:
openstack-java-sdk
Here is a nice toturial that can be of hand:
https://github.com/woorea/openstack-java-sdk/wiki/Swift-Tutorial
it has the example for the java api for using SWIFT,
for example, this code snippet (more details in the link):
Properties properties = System.getProperties();
properties.put("verbose", "true");
properties.put("auth.credentials", "passwordCredentials");
properties.put("auth.username", "demo");
properties.put("auth.password", "secret0");
properties.put("auth.tenantName", "demo");
properties.put("identity.endpoint.publicURL","http://192.168.1.43:5000/v2.0");
OpenStackClient openstack = OpenStackClient.authenticate(properties);
AccountResource account = openstack.getStorageEndpoint();
account.container("hellocontainer").put();
account.container("hellocontainer").object("dir1").put();
account.container("hellocontainer").object("test1")
.put(new File("pom.xml"), new SwiftStorageObjectProperties() {{
setContentType("application/xml");
getCustomProperties().putAll(new HashMap<String, String>() {{
put("customkey.1", "customvalue.1");
}});
}});
List<SwiftStorageObject> objects = account.container("hellocontainer").get();
*
*just keep in mind that when using openstack's API you will most likely need to authenticate (get tokens etc..) so that you will need the Keystone lib as well
www.programcreek.com/java-api-examples/index.php?api=com.woorea.openstack.keystone.Keystone
hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19784740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to prevent the user data from being inserted in DB every time the page reloads? I have this function where I check if user can join a channel and then I insert this data to DB. The problem is it gets inserted every time I reload the page. How to prevent this from happening?
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
$time = now();
if (auth()->check()) {
UserInfo::storeUser();
return [
'id' => $user->id,
'ip' => $ip,
'name' => $user->name,
'joined' => $time
];
}
});
A: Basically, you need any mode of determining that you have already stored the information of this user.
DB, session, or even the auth()->user() object(this one depends on the use case) can store this data.
Take an example of session:
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
$time = now();
if (auth()->check() && !session()->has('user_id')){
UserInfo::storeUser();
session()->put('user_id',$user->id);
return [
'id' => $user->id,
'ip' => $ip,
'name' => $user->name,
'joined' => $time
];
}
});
and on logout:
session()->forget('user_id')
Bear in mind, this is a basic example without much context.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58129046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Identify a set of strings and remove them from a column I'm trying to loop through a column and remove any characters from the start of the row, that falls under my predefined set of strings.
Reproducible Example
df <- data.frame(serial = 1:3, name = c("Javier", "Kenneth", "Kasey"))
serial name
1 1 Javier
2 2 Kenneth
3 3 Kasey
Condition Vector
Removes these strings from the front of name only!
vec <- c("Ja", "Ka")
Intended Output
serial name
1 1 vier
2 2 Kenneth
3 3 sey
A: We could create a pattern by pasting vec into one vector and remove their occurrence using sub.
df$name <- sub(paste0("^", vec, collapse = "|"), "", df$name)
df
# serial name
#1 1 vier
#2 2 Kenneth
#3 3 sey
In stringr we can also use str_remove
stringr::str_remove(df$name, paste0("^", vec, collapse = "|"))
#[1] "vier" "Kenneth" "sey"
A: Since we're using fixed length vec strings in this example, it might even be more efficient to use substr replacements. This will only really pay off in the case when df and/or vec is large though, and comes at the price of some flexibility.
df$name <- as.character(df$name)
sel <- substr(df$name, 1, 2) %in% vec
df$name[sel] <- substr(df$name, 3, nchar(df$name))[sel]
# serial name
#1 1 vier
#2 2 Kenneth
#3 3 sey
A: We can also do this with substring
library(stringr)
library(dplyr)
df$name <- substring(df$name, replace_na(str_locate(df$name,
paste(vec, collapse="|"))[,2] + 1, 1))
df$name
#[1] "vier" "Kenneth" "sey"
Or with str_replace
str_replace(df$name, paste0("^", vec, collapse="|"), "")
#[1] "vier" "Kenneth" "sey"
Or using gsubfn
library(gsubfn)
gsubfn("^.{2}", setNames(rep(list(""), length(vec)), vec), as.character(df$name))
#[1] "vier" "Kenneth" "sey"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55803099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access GH ACTIONS_STEP_DEBUG from an SSH command / environment variable As far as I understood, the "secret" ACTIONS_STEP_DEBUG is set to true when you relaunch a workflow in "debug mode" on Github Actions for a repository.
Now I'd like to hook onto this like a switch to print additional information from python commands that are executed in my actions/steps.
Is it possible to turn ACTIONS_STEP_DEBUG into an environment variable or how could I access it from within a step (like bash or even in python)?
A: So found I can use the secrets, to set an env, however only for workflows, not for the action, for some reason.
env:
IS_STEP_DEBUG: ${{ secrets.ACTIONS_STEP_DEBUG }}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72963161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: monitor kuberntes cluster which created using kops with prometheus running on different vpc I created a kubernetes cluster on aws using kops so it created the certificates on its own.
so next is to add kubernetes api server in prometheus configuration.
I used the below prometheus configuration.
- role: node
api_server: 'https://example.com'
basic_auth:
username: 'username'
password: 'password'
tls_config:
ca_file: '/opt/prometheus-2.1.0.linux-amd64/ca.crt'
server_name: kubernetes
It's adding the targets in prometheus but prometheus unable to scrap the targets with the below error.
Get https://x.x.x.x:10250/metrics: x509: cannot validate certificate for x.x.x.x because it doesn't contain any IP SANs
eventhough i added server_name: kubernetes in the above configuration.
I took kubernetes from the certficate.
openssl x509 -text -noout -in ca.crt
It has below contents.
Subject: CN=kubernetes
A: Try with this. for setting up kubernetes cluster using ansible.
This will provision AWS ec2 and will setup cluster. This role includes lots of addons which is sufficient for development cluster
[1]: https://github.com/khann-adill/kubernetes-ansible
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48584896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to center a string in a batch file I'm making a batch game, and i want the player write the name of your character, and that name appears on the screen inside a text box. Like this:
@echo off
color 0a
setlocal Enabledelayedexpansion
mode 80,30
set /p nickname=Enter your nickname:
pause
cls
echo.
echo +------------------+
echo ¦ %nickname% ¦
echo +------------------+
pause
but as the nickname can be any, when the nickname number of letters is different from 10 (number of letters of variable %nickname%) the right bar of the text box is pushed or pulled. So when the batch starts looks like this:
Enter your nickname: Rob
Press any key to continue...
+------------------+
¦ Rob ¦
+------------------+
Press any key to continue...
(i use the nickname Rob for example, can be any name)
So how i fix it?? There is something to do with the "|" character does not change your position?
A: @ECHO Off
SETLOCAL
set /p nickname=Enter your nickname:
echo.
echo +------------------+
SET "nick=%nickname%"
:loop1
IF DEFINED nick IF "%nick:~17,1%" neq "" GOTO shownick
SET "nick=%nick% "
IF "%nick:~17,1%" neq "" GOTO shownick
SET "nick= %nick%"
GOTO loop1
:shownick
echo ^|%nick%^|
echo +------------------+
GOTO :EOF
Copy the name to another variable (nick)
If nick is not empty, then if its 18th character exists, go to shownick
otherwise, append a space to the end of nick
test again for 18th character, if not exist, prepend a space to nick and continue until character 18 exists.
Note that the syntax %nick:~17,1% means the1` character starting at "character 18" where the string starts at "character 0"
A: A slightly different variant of what Magoo came up with:
@echo off
color 0a
setlocal Enabledelayedexpansion
mode 80,30
set /p "nickname=Enter your nickname: "
ECHO %nickname%>x&FOR %%? IN (x) DO SET /A strlength=%%~z? - 2&del x
set "spaces="
for /l %%a in (%strlength%, 1, 13) do set "spaces=!spaces! "
pause
cls
echo.
echo +------------------+
echo ^| %nickname%%spaces%^|
echo +------------------+
pause
A: Append a bunch of spaces and then strip out as many characters as you want for your fixed field width. I just left the exclamation mark there as a visual indicator for your debugging:
set "n=%n% !"
set n=%n:~0,10%
Here's an example usage incorporated into your script. I'm storing in a separate variable since the original value is being modified and you might need it later and also because if the name entered is longer than ten characters then it's going to be truncated. The naming scheme is sort of inspired by COBOL although it might prove to become tedious to incorporate the length into the variables name.
@echo off
set /p nickname=Enter your nickname:
set "zz10=%nickname% "
set zz10=%zz10:~0,10%
echo +------------------+
echo + %zz10% +
echo +------------------+
Since the word "nickname" plus two percent characters is ten characters wide I'm guessing that might be why you specified a maximum width of ten. While that does make it a little easier to lay out the banner obviously there's no requirement for that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34729834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Validation Summary for Collections EDIT: upgraded this question to MVC 2.0
With asp.net MVC 2.0 is there an existing method of creating Validation Summary that makes sense for models containing collections? If not I can create my own validation summary
Example Model:
public class GroupDetailsViewModel
{
public string GroupName { get; set; }
public int NumberOfPeople { get; set; }
public List<Person> People{ get; set; }
}
public class Person
{
[Required(ErrorMessage = "Please enter your Email Address")]
[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid Email Address")]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "Please enter your Phone Number")]
public string Phone { get; set; }
[Required(ErrorMessage = "Please enter your First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter your Last Name")]
public string LastName { get; set; }
}
The existing summary <%=Html.ValidationSummary %> if nothing is entered looks like this.
The following error(s) must be corrected before proceeding to the next step
* Please enter your Email Address
* Please enter your Phone Number
* Please enter your First Name
* Please enter your Last Name
* Please enter your Email Address
* Please enter your Phone Number
* Please enter your First Name
* Please enter your Last Name
The design calls for headings to be inserted like this:
The following error(s) must be corrected before proceeding to the next step
Person 1
* Please enter your Email Address
* Please enter your Phone Number
* Please enter your First Name
* Please enter your Last Name
Person 2
* Please enter your Email Address
* Please enter your Phone Number
* Please enter your First Name
* Please enter your Last Name
Answer Based on Pharcyde's answer.
public static MvcHtmlString NestedValidationSummary(this HtmlHelper helper)
{
if (helper.ViewData.ModelState.IsValid)
return MvcHtmlString.Empty;
// create datastructure to group error messages under a given key (blank key is for general errors)
var errors = new Dictionary<string,List<string>>();
foreach (KeyValuePair<string, ModelState> keyPair in helper.ViewData.ModelState)
{
foreach (ModelError error in keyPair.Value.Errors)
{
//determine the 'key' for the group in which this error belongs
var key = keyPair.Key.Split(']')[0];
if (key.Contains("People["))
key = "Person " + key.Split('[')[1];
else
key = string.Empty;
if(!errors.ContainsKey(key))
errors.Add(key,new List<string>());
//now add message using error.ErrorMessage property
errors[key].Add(error.ErrorMessage);
}
}
// generate the HTML
var ul = new TagBuilder("ul");
foreach (KeyValuePair<string, List<string>> errorPair in errors.OrderBy(p=>p.Key))
{
var li = new TagBuilder("li");
if(!string.IsNullOrEmpty(errorPair.Key))
li.InnerHtml += string.Format("<p class=\"no-bottom-margin\"><strong>{0}</strong></p>",errorPair.Key);
var innerUl = new TagBuilder("ul");
foreach (var message in errorPair.Value)
{
var innerLi = new TagBuilder("li");
innerLi.InnerHtml = message;
innerUl.InnerHtml += innerLi.ToString(TagRenderMode.Normal);
}
li.InnerHtml += innerUl.ToString(TagRenderMode.Normal);
ul.InnerHtml += li.ToString(TagRenderMode.Normal);
}
return MvcHtmlString.Create(ul.ToString(TagRenderMode.Normal));
}
A: You are going to have to extend the HtmlHelper methods and roll your own. Heres the bit of code that is important for your situation where you need a group by:
//HtmlHelper being extended
if(helper.ViewData.ModelState.IsValid)
{
foreach(KeyValuePair<string,ModelState> keyPair in helper.ViewData.ModelState)
{
//add division for group by here using keyPair.Key property (would be named "Person" in your case).
foreach(ModelError error in keyPair.Value.Errors)
{
//now add message using error.ErrorMessage property
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2466480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Salesforce to SAP connection inside Azure I am trying to connect Salesforce to SAP inside Azure. So far I've come across three ideas to do so.
*
*Generating IDOC messages in SAP using logic Apps? Is it possible, if so what configs do we need here?
*Using FTP/SFTP
*Using APIs/Web Services?
If you have tried to do this and you have some advice you think it might help me please, let me know. I will appreciate it a lot.
A: Yes, you can actually use Logic Apps in this case. You can connect to Salesforce to SAP. Configuration depends on the requirements that you have.
You can even use the web Services by Exposing SAP functionality to the cloud with Azure App Services which will use a combination of API Apps to create a Logic App that exposes BAPI functionality to an external website.
A: I would not recommend an Salesforce to SAP integration from scratch. This is too much effort and you need to take care of things like error handling, delta load and security. Instead I would propose to use a tool that was made for such scenarios.
In case you only need data replication, you can go with something like SAP CPI or Mulesoft. They even offer templates, that make your life easier. You should be aware that these options can be expensive in regards to their licenses/subscriptions.
Another way would be a solution like Vigience Overcast, that offers data replication as well, but also real time access to SAP from within Salesforce. Overcast goes beyond exchanging data between the two systems, but also allows you to create the user interface. They even have pre-defined, ready-to-use apps for the most common use cases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68501778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Issue Writing/Reading Dates when using MS Excel VBA to MS ACCESS Database I'm developing an app in MS Excel (2019) in which I'm trying to write/read a date to MS Access (2019, same suite) via MS Excel VBA code, then retrieve it. But no matter how I enter and format the date, all I get back from MS Access is gibberish.
Cannot figure this one out. Everything I've found online has missed the point in providing a simple explanation as to what the problem is. I did realize that there is a total disconnect between the two applications and I am by far not the only dismayed person.
I think it's fair to expect get out get the same data that you put in. I mean, really, why is this even remotely difficult to do?
The code provided is completely stripped down to the elements required to get at the heart of it all.
Any help would be greatly appreciated.
Robert.
Option Explicit
Public Conn As New ADODB.connection
Public rs As New ADODB.Recordset
Public sconnect As String
Public Const DATABASE_LOC As String = "C:\Users\Robert\Documents\ASAP\db1"
Public Const DATABASE_NAME As String = "Database1.accdb"
'MS Access datatable "TheDate" is a ShortDate
'My system date format is 'standard U.S. - mm/dd/yyyy
'The cell from which result is read is in Date format
'
'Tried:
'ADate = CDate("12/29/2022")
'ADate = #12/29/2022#
'ADate = 'Format("12/29/2022", "mm/dd/yy")
'
'ALL result in: Result IN: ? Date IN: 12/29/2022 - Access table field: 12:00:18 AM
'Result Out: ? Date OUT: 12:00:18 AM - Cell "B1" (Date format) cell value: 1/0/1900 12:00:18 AM
Sub TestDateInAndOut()
TestDateIntoDB
TestDateOutOfDB
End Sub
Sub TestDateIntoDB()
Dim SQLString As StringDim ADate As Date
'option 1
ADate = CDate("12/29/2022")
'option 2
ADate = #12/29/2022#
'option 3
ADate = Format("12/29/2022", "mm/dd/yy")
SQLString = "INSERT INTO Table1 (TheDate) Values(" & ADate & ")" '
OpenSQLConnection ' open connectionrs.Open SQLString, Conn ' &
recordsetCloseSQLConnections
Debug.Print "Date IN: " & CStr(ADate)
End Sub
Sub TestDateOutOfDB()
Dim sSQLSting As String
OpenSQLConnection
sSQLSting = "SELECT * From [Table1]" ' get all data from Table1
rs.Open sSQLSting, Conn
'write the table to worksheetWorksheets("Sheet1").Range("A1").CopyFromRecordset rs
'this will have the record just added to DB (first & only record)
Debug.Print "Date OUT: " & Worksheets("Sheet1").Range("B1")
CloseSQLConnections
End Sub
'Open Access DB connection
Sub OpenSQLConnection()
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DATABASE_LOC & DATABASE_NAME & ";Persist Security Info=False;"
Conn.Open sconnect
End Sub
'Close any DB Connection
Sub CloseSQLConnections()
On Error Resume Next
rs.CloseSet rs = Nothing
Conn.Close
Set Conn = Nothing
End Sub
A: Consider the best practice of SQL parameterization which is supported with ADO library. This approach which is not limited to VBA or MS Access but any programming language connecting to any backend database allows for binding of values to a prepared SQL query to safely bind literal values and properly align data types:
...
Public cmd As ADODB.Command ' AVOID DECLARING OBJECT WITH New
...
Sub TestDateIntoDB()
Dim SQLString As String
Dim ADate As Date
Const adDate = 7, adParamInput = 1
'option 1
ADate = CDate("12/29/2022")
' PREPARED STATEMENT WITH QMARK PLACEHOLDER
SQLString = "INSERT INTO Table1 (TheDate) Values(?)"
' CONFIGURE ADO COMMAND
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = Conn
.CommandText = SQLString
.CommandType = adCmdText
' BIND VALUES
.Parameters.Append .CreateParameter("paramDate", adDate, adParamInput, , ADate)
End With
' EXECUTE ACTION QUERY
cmd.Execute
Set cmd = Nothing
Debug.Print "Date IN: " & CStr(ADate)
End Sub
A: Force a format of the string expression for the date value:
Sub TestDateIntoDB()
Dim SQLString As String
Dim ADate As Date
' Option 0.
ADate = DateSerial(2022, 12, 29)
SQLString = _
"INSERT INTO Table1 (TheDate) " & _
"VALUES (#" & Format(ADate, "yyyy\/mm\/dd") & "#)"
' <snip>
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74946478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Example of using scoped try_shared_lock and upgrade lock in boost I have a thread pool that is using shared mutexes from the boost library.
While the answers to my other question were helpful,
Example of how to use boost upgradeable mutexes
What I have realised that what I actually need is not to block if a shared lock or upgrade lock could not be obtained. Unfortunately, the boost docs are lacking any examples of those in use.
Could someone please point me to or provide an example of specifically the shared_lock being used in this way.
i.e.
boost:shared_mutex mutex;
void thread()
{
// try to obtain a scoped shared lock
// How do I do that?
}
void thread2()
{
// try to obtain a scoped upgrade lock
// and then a scoped unique lock
}
A: The answer seems to be that you can provide boost:try_to_lock as a parameter to several of these scoped locks.
e.g.
boost::shared_mutex mutex;
// The reader version
boost::shared_lock<boost::shared_mutex> lock(mutex, boost::try_to_lock);
if (lock){
// We have obtained a shared lock
}
// Writer version
boost::upgrade_lock<boost::shared_mutex> write_lock(mutex, boost::try_to_lock);
if (write_lock){
boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
// exclusive access now obtained.
}
EDIT:
I also found by experimentation that upgrade_to_unique_lock will fail if you don't have the upgrade lock. You can also do this:
boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
if (unique_lock){
// we are the only thread in here... safe to do stuff to our shared resource
}
// If you need to downgrade then you can also call
unique_lock.release();
// And if you want to release the upgrade lock as well (since only one thread can have upgraded status at a time)
write_lock.unlock().
Note: You have to call release followed by unlock or you'll get an locking exception thrown.
You can of course just let unique_lock and write_lock go out of scope thereby releasing the locks, although I've found that sometimes you want to release it earlier and you should spend minimal time in that state.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3963771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP OOP: Parenting objects/functions? How is parenting functions in PHP done properly according to the following example?
Can I make sure that my array isn't overwritten and the previous values inside array lost, on each addArray call?
function arraybase() {
$this->array = new ArrayObject();
return $this;
}
function addArray($value) {
parent::$this->arraybase();
$this->array->append($value);
return $this;
}
$this->addArray('1')->addArray('2')->addArray('3');
// outputs:
Array
(
[0] => 3
)
A: In function addArray you keep recreating the array with the line:
parent::$this->arraybase();
Remove this line and call arraybase when you want to create it.
A: Well, first off, you don't need to parent::$this->arraybase(). Just do $this->arraybase(). In fact, I'm not even sure your way is even valid syntax. But I digress.
As for your specific problem, you can either:
*
*Add a constructor (and remove the ->arraybase() call from addArray()):
public function __construct() {
$this->array = new ArrayObject();
}
*Add an if check around the call to ->arraybase():
public function addArray($value) {
if (!isset($this->array) || !is_object($this->array)) {
$this->arraybase();
}
...
}
Personally, I'd do #1. It's going to be more reliable, faster, and more in keeping with OOP paradigms.
EDIT: Adding Constructor Info
So, if your base class has this constructor:
public function __construct($some, $vars) {
......
}
You would do this in your extending class:
public function __construct($some, $vars) {
parent::__construct($some, $vars);
$this->array = new ArrayObject();
}
NOTE: Don't call parent::__construct() unless one of the parents has a __construct method...
A: Why do you want to set a wrapper around ArrayObject? If it's for adding the possibility of chaining method calls, then you'd better extend ArrayObject:
<?php
class MyArrayObject extends ArrayObject {
public function append($value)
{
parent::append($value);
return $this;
}
}
$ao = new MyArrayObject();
$ao->append('a')->append('b')->append('c');
var_dump($ao->getArrayCopy());
/*
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
*/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2930345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to restart SoapUI's JVM? I am currently testing some changes to SoapUI JRE's settings on 'Preferences -> SSL' tab and to apply changes I close and then open again a SoapUI instance.
(Windows 10; SoapUI 5.3.0)
Is there a better (smarter) way of restarting SoapUI's JVM?
Preferably the one without closing the instance.
A: This comment answers the question:
You have to close the GUI instance and start it again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45818212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery Templates {{each}} - How to address the underlying objects individually? I got the data collection:
var messages = {
0: {who:'aaa', age: 33, id: 2},
1: {who:'bbb', age: 44, id: 3},
// ...
};
I got the template:
<script type="text/jquery-template" id="chat-message-template">
{{each $data}}
<p id="id${$value.id}">${$value.who}</p>
{{/each}}
</script>
Now I am rendering it and put the result to #container:
$('#chat-message-template').tmpl(messages).appendTo('#container');
And It works fine, BUT how do I get a single element (single 'p' element) of the rendered template to be able to update it?
$('#oneOfParagraphsId').tmplItem(); OR $.tmplItem('#oneOfParagraphsId')
return all the collection of added paragraphs.
Yeah, I could walk through the collection and find the one I want, BUT, can I just somehow get a single item, not all the collection?
Even if I put a click event on each <p> and in handler do something like $(this).tmplItem() it still gives me all the p's of the template!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35557282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How does one get Properties using Reflection, while ignoring the inherited properties? To get the properties is not big deal, but I don´t want to get the properties inherited from another class. The bindingFlags option doesn´t have any option of this kind.
Is that possible ?
cheers
A: Use BindingFlags.DeclaredOnly with your Type.GetProperties call in order to specify to just get the properties from the specified type.
For example, to get all non-static properties on a type without looking up it's hierarchy, you could do:
var properties = theType.GetProperties(
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3407767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Validation for form on Button Click I have a form where I have many textboxes which are getting validated through Required field validator, But there is a captcha control also which is not getting validated. However I can validate it through javascript.
Here alert gets displayed when I click on 'OK' of alert message box.
But I want this message to be displayed on button click simultaneously with other validations.
Please help.
Thanks in Advance.
A: I think you want to display the "Please enter captcha text." as part of the ValidationSummary control.
To do this, you just need to let the server-side know the captcha text. Do this:
*
*Add another textbox, but keep it hidden with display:none:
<asp:textbox id="txtCaptcha" runat="server" style="display:none;">
*Modify your Javascript to copy the captcha value into the txtCaptcha textbox:
<script type="text/javascript">
$(document).ready(function () {
$('#' +'<%=btnSend.ClientID %>').on('click', function (e) {
var captcha = $("input[name$=CaptchaControl1]").val();
$('#' + '<%=txtCaptcha.ClientID %>').val(captcha);
})
});
</script>
*Create a RequiredValidator for txtCaptcha textbox:
<asp:RequiredFieldValidator ID="RequiredFieldValidatorForCaptcha" runat="server" ErrorMessage="Please enter captcha text." ControlToValidate="txtCaptcha" Display="None" ValidationGroup="VG"></asp:RequiredFieldValidator>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24166435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access denied exception using C# / UWP The execute() function is linked to a button press.
The first time it is pressed - everything runs the way it should/
The second time is is pressed (within the same execution of the app; if I close and re-open it works fine) - on the DeleteAsync line I get this exception:
An exception of type 'System.UnauthorizedAccessException' occurred in
mscorlib.ni.dll but was not handled in user code
Additional information: Access is denied. (Exception from HRESULT:
0x80070005 (E_ACCESSDENIED))
I think something is staying open longer than it should, hence the error. But I'm not sure what is causing it exactly. If anyone can see from the code below what could be happening I would be most grateful:
private async void execute(string url)
{
StorageFolder filesFolder = null;
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
if (await localFolder.TryGetItemAsync(DIRECTORY_NAME) != null)
{
filesFolder = await localFolder.GetFolderAsync(DIRECTORY_NAME);
await filesFolder.DeleteAsync(StorageDeleteOption.PermanentDelete); // << THIS IS THE EXCEPTION LINE
}
if (await localFolder.TryGetItemAsync(DIRECTORY_NAME) == null)
{
await Task.Run(() => {
repository.Clone(url, DIRECTORY_NAME);
});
}
// This won't be called until task above finished running
filesFolder = await localFolder.GetFolderAsync(DIRECTORY_NAME);
IEnumerable<StorageFile> files = await filesFolder.GetFilesAsync();
addFiles(files);
}
Clone function:
void Repository::Clone(Platform::String^ url, Platform::String^ path)
{
OutputDebugString(L"Clone ");
OutputDebugString(url->Data());
OutputDebugString(L" into ");
char temp[1024];
GetLocalPath(path, temp, 1024);
OutputDebugStringA(temp);
OutputDebugString(L"\n");
char urlt[1024];
wcstombs(urlt, url->Data(), 1024);
git_clone_options clone_opts = GIT_CLONE_OPTIONS_INIT;
git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT;
// Set up options
checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE;
checkout_opts.progress_cb = on_checkout_progress;
clone_opts.checkout_opts = checkout_opts;
clone_opts.fetch_opts.callbacks.sideband_progress = on_sideband_progress;
clone_opts.fetch_opts.callbacks.transfer_progress = on_fetch_transfer_progress;
clone_opts.fetch_opts.callbacks.credentials = on_credentials_required;
clone_opts.fetch_opts.callbacks.payload = this->native;
// Start the cloning
report_error(git_clone(&repo, urlt, temp, &clone_opts));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38988937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Qt: how to dynamic change the position of other widget? Let's say I have a GUI:
When I click the left button, I expect the object would locate at left just like:
layout.addWidget(object)
layout.addStretch()
How can I dynamically change the position?
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class Widget(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
self.btnPos = QPushButton('left')
self.btnPos.clicked.connect(self.btnClick)
self.btnLayout = QHBoxLayout()
self.btn = QPushButton('object')
self.btnLayout.addStretch()
self.btnLayout.addWidget(self.btn)
self.btnLayout.addStretch()
layout.addWidget(self.btnPos)
layout.addLayout(self.btnLayout)
def btnClick(self, check=False):
print('click')
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Widget()
win.show()
app.exec_()
A: In your btnClick function, you can set the Stretch parameter for each item in self.btnLayout. In this case you want to set the Stretch for the spacer on the left to 0 and the right spacer to 1:
def btnClick(self, check=False):
print('click')
# align button left
self.btnLayout.setStretch(0,0)
self.btnLayout.setStretch(1,1)
self.btnLayout.setStretch(2,1)
pass
For centering the button, set left and right spacers stretch to 1:
# button is centered
self.btnLayout.setStretch(0,1)
self.btnLayout.setStretch(1,1)
self.btnLayout.setStretch(2,1)
And to align button on right, set left spacer to 1, right spacer to zero:
# align button right
self.btnLayout.setStretch(0,1)
self.btnLayout.setStretch(1,1)
self.btnLayout.setStretch(2,0)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73081149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Stretch an iframe with width and height of parent I've got a module in my Nextjs app that shows events that are currently being live-streamed. Within this module I've got an image preview with a play button that, when clicked, takes you to the live event.
What I'd like to do, however, is have this preview be the Vimeo video for the event, so it shows a video preview. That's easy enough to do, I can get the embed code for the Vimeo video from the events API, but I'm having trouble getting it to stretch into the full width and height of this rectangle. This is how it's looking right now:
Essentially, I can't figure out the correct styles to get it to stretch to this ratio, similarly to the image. I'm not concerned with what is being cut off or not, I just want to use the video as a background.
Here's what I've got so far (I'm using Nextjs and SASS modules):
The HTML in the component:
<div className={s.liveStream__player}>
<Link href={`/events/${live.event_id}`} title="Play" className={s.liveStream__play}>
<PlayButton />
</Link>
<iframe
src={`https://player.vimeo.com/video/${vimeoId[1]}?background=1`}
className={s.liveStream__preview}/>
</div>
And the SASS:
.liveStream {
&__play {
position: relative;
z-index: 10;
}
&__player {
display: flex;
height: 100%;
width: 100%;
flex-grow: 1;
align-items: center;
justify-content: center;
position: relative;
overflow: hidden;
}
&__preview {
position: absolute;
top: 0;
left: 0;
width: 100%;
pointer-events: none;
}
}
Is there an easy way to accomplish this and get the iframe to stretch to the full width and height of the parent?
A: You have missed one property to stretch iframe (height):
.liveStream {
&__play {
position: relative;
z-index: 10;
}
&__player {
display: flex;
height: 100%;
width: 100%;
flex-grow: 1;
align-items: center;
justify-content: center;
position: relative;
overflow: hidden;
// make sure wrapper has necessary sizes
// min-height: 100vh;
// just for example purposes:
height: 300px;
width: 300px;
}
&__preview {
position: absolute;
top: 0;
left: 0;
width: 100%;
pointer-events: none;
// add height prop to stretch iframe to parent height
height: 100%;
}
}
Also make sure wrapper has necessary sizes.
You can check codes in Codepen.io example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70793223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the difference between `raw.githubusercontent` and raw in the URL itself When I see URLs like https://github.com/hasura/graphql-engine/raw/stable/cli/get.sh, it contains "raw" in the URL itself. However when you actually go to that URL, it redirects to "raw.githubusercontent", same as when you went to that file on GitHub and clicked "raw" on the UI.
I assume instinctively it's perhaps because of some legacy thing, perhaps GitHub is redirecting all previous URLs to the new "raw.githubusercontent" URL?
Or is there another reason, is there some difference or something specific that happens when it's specifically "raw" in the URL?
This is made even more confusing when I see there's a difference between new and old URLs on GitHub. The above example is using https://github.com/<org>/<repo>/raw/<branch>/<dir>/<file>. However when you use that on a new repository it looks like https://github.com/<org>/<repo>/blob/<branch>/<dir>/<file> and that then gets converted to raw.githubusercontent. It seems like old repositories didn't use "tree" or "blob" at all in the URLs.
So what exactly is the most up to date and correct way to use it and if I wanted to retrieve the raw content of a file, which URL should I use?
A: The links you see on github.com are routes that are designed to be used on the website in web browsers. The domain githubusercontent.com is designed to be separate to prevent any malicious user content from trying to steal cookies for github.com.
In general, if you're just using a web browser, click on the link or the button, and it will automatically redirect you to the right place. Otherwise, you should use the REST API to either get the raw file contents directly or fetch the download URL. Using the API will always give you the correct location and contents.
If you just want to use curl with the API and don't want to fetch the download_url key manually, you can run this: curl -H'Accept: application/vnd.github.v3.raw' https://api.github.com/repos/hasura/graphql-engine/contents/cli/get.sh.
Note also that none of these ways are designed for high-speed automated access; for that, you should host your repository on your own server with a CDN in front.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73344633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: css with background image without repeating the image I have a column (lets assume the width is 40px) and there I have some rows. The height of the rows depends on the length of text (if the text is long then there is a break line and therefore the height increases).
Now I want to display an icon in each row next to the text to show the user for example that he has already completed something in that tab. So I was trying to solve this by using only css. So if the user completes a tab then I change the css of that row. However, I'm not able to add to that row an image without that the image is being repeated.
I'm using this css code:
padding: 0 8px;
padding-top: 8px;
padding-right: 8px;
padding-bottom: 8px;
padding-left: 8px;
overflow: hidden;
zoom: 1;
text-align: left;
font-size: 13px;
font-family: "Trebuchet MS",Arial,Sans;
line-height: 24px;
color: black;
border-bottom: solid 1px #BBB;
background-color: white;
background-image: url('images/checked.gif');
background-repeat-x: no-repeat;
background-repeat-y: no-repeat;
Does anyone know how to do that?
A: Instead of
background-repeat-x: no-repeat;
background-repeat-y: no-repeat;
which is not correct, use
background-repeat: no-repeat;
A: Try this
padding:8px;
overflow: hidden;
zoom: 1;
text-align: left;
font-size: 13px;
font-family: "Trebuchet MS",Arial,Sans;
line-height: 24px;
color: black;
border-bottom: solid 1px #BBB;
background:url('images/checked.gif') white no-repeat;
This is full css.. Why you use padding:0 8px, then override it with paddings? This is what you need...
A: This is all you need:
background-repeat: no-repeat;
A: body {
background: url(images/image_name.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Here is a good solution to get your image to cover the full area of the web app
perfectly
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8039094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: How do I use axios in vue3 I created a project in vue2 and now I'm migrating to vue3.
I had an api service which looked like this:
import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
import JwtService from "@/common/jwt.service";
import { API_URL } from "@/common/config";
const ApiService = {
init() {
Vue.use(VueAxios, axios);
Vue.axios.defaults.baseURL = API_URL;
},
setHeader() {
Vue.axios.defaults.headers.common[
"Authorization"
] = `Bearer ${JwtService.getToken()}`;
},
query(resource, params) {
return Vue.axios.get(resource, params).catch(error => {
throw new Error(`[RWV] ApiService ${error}`);
});
},
...
How do I change this to vue3. I'm not supposed to use vue.axios anymore. In the documentation it says that should use app or this. But am I then supposed to export the app from main? I can't find any examples for this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70183784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to do Form Customization for Unhiding Fields I am new to Ax,I am doing an customization on form.When I click on show more fields I want to show three more fields on form which are hiding(FieldC,FieldD,FieldF).Please tell me how to achieve this Functionality.
A: You can check an example in form VendTable > Design > MainTab > TabPageDetails > Tab > TabGeneral > HideShowGroup.
It contains two elements: a combobox (HideShowComboBox) and a button (HideShowButton).
By default, the button has following properties:
*
*AutoDeclaration = Yes
*Text = Show more fields
*HelpText = Show/hide fields.
*SaveRecord = No
*Border = None
*BackgroundColor = Dyn Background white
*ImageLocation = EmbeddedResource
*NormalImage = 7886
*ButtonDisplay = Text & Image left
The button also has method clicked responsible for hiding/showing the fields that need to be hidden/displayed and for changing its own look (Text, HelpText, NormalImage = 7882, etc.)
Please note that this logic is managed in class DirPartyFormHandler - you can set breakpoints there and debug the process to understand this functionality better.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55547712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: masm x86 Assembly Is it possible to check if an address is allocated or not? In masm, you can statically allocate memory using the .DATA, and .DATA? directives, and that is great, but what if I needed to allocate a block of memory dynamically? Lets say that I wanted to create a DWORD with the value 10 in dynamically allocated memory. One theory is that I could run through a range of addresses, check if they are allocated or not, and if not then allocate the address and use it to store the DWORD in. But there is only one problem; I do not know how to check if an address is allocated or not. :(
Make_Dword PROC
PUSH EBP
MOV EBP, ESP
PUSH ESI
PUSH EDI
PUSH EBX
MOV EBX, [EBP - 08h] ;EBP - 08h is the dword value
;Iterate through memory addresses and check if one is unallocated, if so
; use it to store the dword value in, finally return the newly allocated
; address of the dword in memory.
MOV EAX, [the newly allocated address of the dword]
POP EBX
POP EDI
POP ESI
MOV ESP, EBP
POP EBP
Make_Dword ENDP
PUSH DWORD PTR 0Ah
CALL Make_Dword
A: I am editing my response to see if maybe I can clarify. If you have a data directive, can you just allocate a static size block of memory with it? e.g.
.DATA
poolOfDwords DWORD 1000
Then, just initialize them to values that you know you cannot get (-1 maybe?). Then, when you need to "allocate" a DWORD, you can just iterate through the list for the first entry that is -1 (unallocated) and use it. You can return the offset to that location if you need to use it.
Hopefully that helps clarify my idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45247997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: jQuery Tools overlay draggable I have an overlay with the apple effect from jQuery Tools. I want to make it so the overlay is draggable, but when I use $( ".overlay" ).draggable(); the background image does not drag with it. I tried appendTo but it destroyed the apple effect. Also the image for the overlay is rendering outside of the .overlay div.
here is a jsfiddle http://jsfiddle.net/ZqNgy/
I am kind of new to jQuery and javascript and would really appreciate any help.
Thanks
A: if you do not need 'apple'effect, you can drag background image.
just effect set to 'default'.
and you may be need to change overlay style.
example(".overlay").overlay({
top: 50,
left: 50,
closeOnClick: false,
load: false,
effect: 'default',
speed: 1000,
oneInstance: false,
fixed: false,
});
.overlay {
display:none;
background-image:url(white.png);
background-size:cover;
width:160px;
padding:20px;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16705573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OMNet ++, SUMO and Veins with or without INET I just successfully accomplished the Veins (with OMNet++ and SUMO) tutorial (http://veins.car2x.org/tutorial/), but noticed that it did not use INET. Other YouTube tutorials on Veins use INET with Veins, almost as if it is a given. What is the benefit of incorporating INET into a Veins simulation? What do you gain?
My experience is limited to the tutorial, and an expectation of eventually learning/incorporating Plexe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74647186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: D3 data processing choice I have a question about which kind of data I should send to client for visualization:
I have an web that needs to display both processed data and database-like data(Processed one is from database-like)
So now I have 2 choices:
*
*Send to client Database-like data and process the logic there to get the processed data
*Send both processed data and database-like data. Redundant but ease of use
I would like to hear about your opinions n regard of these 2 approaches. And they are also in context of using d3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36568616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to print value of a hashmap? When I execute the below code:
map.forEach((key, value) -> System.out.println(key + ":" + value));
I get 15234:[com.org.myprj.Dashboard@18a6be14] as sysout.
How to I get object value in hashmap? Here object is a row inserted in arraylist.
A: implement overridden toString method in object
example
class Dashboard{
private double re, im;
public Dashboard(double re, double im) {
this.re = re;
this.im = im;
}
@Override
public String toString() {
return String.format(re + " + i" + im);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61522015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to Add External CSS in Laravel 5.4 I am new in Laravel...
web.php
<?php
Route::get('/', function () {
return view('method1.home');
});
home.blade.php
@extends('dashboard')
dashboard.blade.php
<!DOCTYPE html>
<html class="no-js">
<head>
@include('includes.head')
</head>
<body>
do something...
</body>
head.blade.php
<link rel="stylesheet" href="{{ URL::asset('front_view/css/main.css') }}">
<link rel="stylesheet" href="{{ URL::asset('front_view/css/shop.css') }}">
<script src="{{ asset('front_view/js/vendor/modernizr-2.6.2.min.js') }}"></script>
The path and folder name is correct.
But the CSS is not working.
A: open or create file if not exist constants.php inside config folder and then add this line inside that file
define('SITE_PATH', 'http://localhost:8000/'); // write here you site url
and then use like this in view
<link rel="stylesheet" type="text/css" href="<?php echo SITE_PATH; ?>css/custom.css">
it will search for custom.css inside public/css folder so create css folder inside public folder and the create your custom.css or create directly inside you public folder
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51361225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ruby find where before updated_at I am trying to search for results where the updated_at on one result is after the created at of another this is my code in a short and sweet version
i am getting a syntax error
PG::SyntaxError: ERROR: syntax error at or near "13"
LINE 1: ...ERE ((group_id = 14 and created_at >= 2016-08-04 13:39:35 U...
^
: SELECT "chats".* FROM "chats" WHERE ((group_id = 14 and created_at >= 2016-08-04 13:39:35 UTC)) ORDER BY created_at DESC
but i do not understand why is it something to do with the time?
@grouparchived = @groupread.updated_at
filter1 = "(group_id = "[email protected]_s + " and created_at >= "[email protected]_s+")"
@chats1 = Chat.where(@filter1).order('created_at DESC')
A: Chat.where(group_id: @arandomthing).where('created_at >= ?', @groupread.updated_at).order('created_at DESC')
Concating strings like you're doing is a recipe for disaster, much better to use the tools Rails gives you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41270689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dicom data training failed by pytorch I've got a problem about training the Pytorch models. I'm trying to train my Pytorch model using dicom data and nifti GT However, the size of the weight file is ridiculously small because model training is not performed normally.
I used network model Unet++
I think there is a problem with the data loader. But I can't fixe it...
I'd appreciate it if you could help me.
Raw image file format is dicom and GT image format is nifti
in my dataloder
def __getitem__(self, index):
image_path = self.image_paths[index]
image_GT_path = image_path[:8]+'_'+image_path[8:12]+'.nii'
GT_path = self.GT_paths + image_GT_path
ds = dcmread(self.root+image_path)
image = ds.pixel_array.astype(np.float32)
image = torch.from_numpy(image.transpose(0,1)/255)
image = image.unsqueeze(0)
GT = nib.load(GT_path)
GT = GT.get_fdata(dtype=np.float32)
print(GT.shape)
GT = torch.from_numpy(GT.transpose(0,1))
GT = GT.unsqueeze(0)
return image, GT, image_path
and Train Code is
for epoch in range(self.num_epochs):
self.unet.train(True)
epoch_loss = 0
for i, (images, GT,empty) in enumerate(tqdm(self.train_loader)):
# GT : Ground Truth
images = images.to(self.device)
GT = GT.to(self.device)
# SR : Segmentation Result
SR = self.unet(images)
SR_probs = torch.sigmoid(SR)
SR_flat = SR_probs.view(SR_probs.size(0),-1)
GT_flat = GT.view(GT.size(0),-1)
loss =self.criterion(SR_flat,GT_flat)
# self.criterion=DiceLoss() #BCE not use
# loss = self.criterion(GT,SR_probs)
epoch_loss += loss.item()
train_losses.append(loss.item())
# Backprop + optimize
self.reset_grad()
loss.backward()
self.optimizer.step()
A: Depending on what modality your images are, this might possibly be due to not converting the image data into the correct, clinically relevent, machine/vendor independent, units prior to any ML training 0-1 normalization.
Typically in dicom files, the actual raw data values aren't that - they need processing...
For instance, if you're trying to train on CT data, then the units you should be trying to train your model on are Houndsfield's (HU) numbers. (Do a google on that, CT and dicom to get some background).
However raw CT dicom data could be little or big endian, likely needs a slope/intercept correction applied and also could need to have look up tables applied to convert it into HU numbers. ...ie can get complicated and messy. (again do a bit of googling ...you at least should have a bit of background on this if you're trying to do anything with medical image formats).
I'm not sure how to process nifti data, however luckily for dicom files using pydicom this conversion can be done for you by the library, using (typically) a call to pydicom.pixel_data_handlers.util.apply_modality_lut:
dcm = pydicom.dcmread(my_ct_dicom_file)
data_in_HU = pydicom.pixel_data_handlers.util.apply_voi_lut(
dcm.pixel_array,
dcm
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70091655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP: How to get timezone value (ex: Eastern Standard Time) from timezone name (ex: America/New_York)? Is there a PHP function anywhere which converts between the timezone name (such as those found here: http://php.net/manual/en/timezones.america.php) and the "value" such as Eastern Standard Time, or Pacific Daylight Time?
Not looking to convert between zones, just get the EST, PDT, etc. names given the America/New_York (or other) name. The only similar question I found is for a different language.
A: If you you install the PHP Internationalization Package, you can do the following:
IntlTimeZone::createTimeZone('America/New_York')->getDisplayName()
This will return the CLDR English standard-long form by default, which is "Eastern Standard Time" in this case. You can find the other options available here. For example:
IntlTimeZone::createTimeZone('Europe/Paris')->getDisplayName(true, IntlTimeZone::DISPLAY_LONG, 'fr_FR')
The above will return "heure avancée d’Europe centrale" which is French for Central European Summer Time.
Be careful to pass the first parameter as true if DST is in effect for the date and time in question, or false otherwise. This is illustrated by the following technique:
$tz = 'America/New_York';
$dt = new DateTime('2016-01-01 00:00:00', new DateTimeZone($tz));
$dst = $dt->format('I');
$text = IntlTimeZone::createTimeZone($tz)->getDisplayName($dst);
echo($text); // "Eastern Standard Time"
Working PHP Fiddle Here
Please note that these strings are intended for display to an end user. If your intent is to use them for some programmatically purpose, such as calling into another API, then they are not appropriate - even if the English versions of some of the strings happen to align. For example, if you are sending the time zone to a Windows or .NET API, or to a Ruby on Rails API, these strings will not work.
A: If you know the value from your list at (http://php.net/manual/en/timezones.america.php) you can do something like.
<?php
$dateTime = new DateTime();
$dateTime->setTimeZone(new DateTimeZone('America/New_York'));
echo $dateTime->format('T');
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37146226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Unity: How to represent grid map data in ECS I have been trying to work with Unity's pure ECS approach to make a basic nxn grid of tiles.
Before using ECS I would just use a 2d array Tiles[,] grid where I can simply index (x,y) to find the tile I want.
Now moving into ECS, I want to create an entity for each tile using an IComponentData struct like so:
public struct Tile : IComponentData
{
public int xIndex;
public int yIndex;
public int isValid;
}
Somewhere during the start of my game I create the tile entities
for (int i = 0; i < tilesInMap; i++)
{
Entity tileEntity = entityManager.CreateEntity(tileArchetype);
int xIndex = i % terrainSize;
int yIndex = i / terrainSize;
entityManager.SetComponentData(tileEntity, new Position { Value = new float3(xIndex , 0, yIndex) });
Tile newTile;
newTile.xIndex = xIndex;
newTIle.yIndex = yIndex;
newTile.isValid = 1;
entityManager.SetComponentData(tileEntity, newTile);
}
Now somewhere else in my code I have a ComponentSystem that pulls in the tiles using a group struct
public struct TileGroup
{
public readonly int Length;
public EntityArray entity;
public ComponentDataArray<Tile> tile;
}
[Inject] TileGroup m_tileGroup;
As far as I'm aware, as long as I don't change the archetype of any of those entities in the TileGroup (for instance by calling AddComponent or RemoveComponent), the ordering of that injected array will be preserved (I'm not even sure of that!)
So say in my OnUpdate method I want to "get the tile at grid coordinate (23, 43)". I can calculate this (assuming a 1d array of tiles with the order preserved) by
int arrayIndex = yIndex * tilesPerMapWidth + xIndex;
But this only works as long as the injected array order of tiles is preserved which I doubt it will be eventually.
So a few questions:
1. Should I ever rely on the order of an injected array for behaviour logic?
2. Are there any better methods in achieving what I want using ECS?
A: From the Unity forums, "Order of Entities":
*
*ComponentDataArray<> / ComponentGroup makes zero gurantees on the actual ordering of your entities except for that its deterministic. But generally the indices are not stable. (E.g. Adding a component to an entity, will change the index in ComponentDataArray of that entity and likely of another one) The only stable id is the "Entity" ID.
To answer your questions:
So a few questions: 1. Should I ever rely on the order of an injected array for behaviour logic?
Based on "...makes zero guarantees on the actual ordering of your entities..." I would say no.
*Are there any better methods in achieving what I want using ECS?
You don't need arrayIndex to access entities in your tile group. You can iterate through the entities and access x and y for each to perform the required behavior. Depending on your actual functionality you may want to use the job system as well.
for (int i = 0; i < m_tileGroup.Length; i++) {
int x = m_tileGroup.tile[i].xIndex;
int y = m_tileGroup.tile[i].yIndex;
// do something with x and y
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51905153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Add T-SQL in maintenance plan in SQL Server How can I set a T-SQL statement as a part of a maintenance plan in SQL Server?
Since I can see options of backup etc but not the possibility of adding T-SQL
A: I am not sure why you are looking to set up a maintenance plan.But, the alternate approach would be to set up a SQL server agent job to execute your T-SQL statements (which can be put together as procedures) and schedule it accordingly.
At the same time, you can execute SQL jobs through maintenance plans as well. This page will also help you : https://learn.microsoft.com/en-us/sql/relational-databases/maintenance-plans/use-the-maintenance-plan-wizard?view=sql-server-2017
A: First I connected to my SQL server using SQL Server Management Studio.
I went to the node Management, right-clicked the subnode Maintenance Plans and created a new maintenance plan called Test. My maintenance plan automatically got a subplan called Subplan_1. I just kept it and saved the maintenance plan.
Next, I went to the node SQL Server Agent, opened the subnode Jobs and double-clicked node Test.Subplan_1. It had a job step called Subplan_1. Double-clicking that job step opened the job step's properties. There I could choose the type Transact-SQL script (T-SQL) and enter my SQL code.
I did not encounter any problems. I used SQL Server 2017, but I am pretty sure it works about the same way in earlier versions of SQL Server...
Edit:
Like sabhari karthik commented and answered, it is very well possible to just create a new job with SQL Server Agent and schedule that job. So perhaps you do not need a maintenance plan at all. But if you do use maintenance plans (or are required to use and/or edit existing maintenance plans), it might be just the case that a maintenance plan's subplan automatically gets a related SQL Server Agent job. But I am not sure. I have never configured and used any maintenance plans before. I'm just a software developer, not a DBA.
Edit 2:
I see in the Maintenance Plan Wizard that there is an option to execute a SQL Server Agent Job as a maintenance task as well. But it seems you need to create that SQL Server Agent Job first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55528827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: position:sticky does not leave parent How can make an element sticky, so it stays at the top of the viewport? I want the element to remain sticky even if it leaves it's container.
I tried this
HTML
<div class="page">
<div class="parent">
<div class="child-sticky">
<p>i want to be sticky, even when I'm outside my parent.</p>
</div>
</div>
</div>
CSS
.child-sticky {
position:sticky;
top:20px;
}
.page {
height: 3000px;
}
Here's a pen to illustrate the problem. Scroll down to see what I mean.
https://codepen.io/pwkip/pen/OxeMao
A: This is how position: sticky is intended to work. If you need it to also work outside the parent than you have to change the HTML structure.
See also the official definition: https://www.w3.org/TR/css-position-3/#sticky-pos
A: There is a little trick you can try.
In some cases it will break your layout and in others it won't. In my case, I have a header with some buttons but when I scroll down, I want to have access to some action buttons which are inside that one-line header. The only change is to set the display property of your parent to be inline.
.parent {
display: inline;
}
A: Sticky works that way, it will remain sticky relative to its parent. You need to use fixed.
Check this codepen
A: Already 7 months ago, but I found a CSS only solution if the element you want to be sticky is the last one of its parent, its very simple: Just give the parent element position: sticky; and also give it top: -xx;, depending on the height of the elements before the last one.
#parent {
position: -webkit-sticky;
position: sticky;
top: -3em;
}
#some_content {
height: 3em;
}
#sticky {
background-color: red;
}
#space {
height: 200vh;
}
<div id="parent">
<div id="some_content">Some Content</div>
<div id="sticky">Sticky div</div>
</div>
<div id="space"></div>
<p>Scroll here</p>
A: Based on https://stackoverflow.com/a/46913147/2603230 and https://stackoverflow.com/a/37797978/2603230's code, here's an combined solution that does not require hard-coded height.
$(document).ready(function() {
// Get the current top location of the nav bar.
var stickyNavTop = $('nav').offset().top;
// Set the header's height to its current height in CSS
// If we don't do this, the content will jump suddenly when passing through stickyNavTop.
$('header').height($('header').height());
$(window).scroll(function(){
if ($(window).scrollTop() >= stickyNavTop) {
$('nav').addClass('fixed-header');
} else {
$('nav').removeClass('fixed-header');
}
});
});
body { margin: 0px; padding: 0px; }
nav {
width: 100%;
background-color: red;
}
.fixed-header {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 10;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<div>
<h1 style="padding-bottom: 50px; background-color: blue;">
Hello World!
</h1>
</div>
<nav>
A nav bar here!
</nav>
</header>
<main style="height: 1000px;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</main>
A: Like mentioned, sticky works that way. However there is a CSS hack that you can play around with.
Disclaimer
This is an ugly hack and will probably create a lot of problems with the following content. So I would not recommend it for most usecases. Having that said...
Negative margin hack
There is a hack you could play around with including negative margin. If you extend the height of the container and then give it some negative bottom margin, it could at least "visually leave" the container.
I altered your code and created a JSFiddle for demonstration.
HTML
<div class="page">
<div class="parent">
<div class="child"><p>...<br>...<br>...<br>...<br>...</p></div>
<div class="child-sticky">
<p>i want to be sticky, even when I'm outside my parent.</p>
</div>
<div class="child"><p>...<br>...<br>...<br>...<br>...</p></div>
<div class="child"><p>...<br>...<br>...<br>...<br>...</p></div>
</div>
<div class="following-content">
</div>
</div>
CSS
.child-sticky {
height: 200px;
background: #333366;
position:sticky;
top:20px;
color:#ffffff;
}
.parent {
height: 1250px;
background: #555599;
margin-bottom: -500px;
}
.following-content {
background: red;
height:500px;
}
.child {
background-color: #8888bb;
}
.page {
height: 3000px;
background: #999999;
width: 500px;
margin: 0 auto;
}
div {
padding: 20px;
}
https://jsfiddle.net/74pkgd9h/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46913063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Draw Hexagonal Shapes using jQuery Is it possible to draw hexagonal shapes using jQuery, HTML and CSS?
If yes how can we do that?
A: jQuery doesn't draw things. You could do this using CSS + HTML only. Here is a cool tutorial showing one way it could be done:
http://jtauber.github.com/articles/css-hexagon.html
Note: HTML / CSS may not be ideal for all situations. It might be better to look at using SVG instead.
A: My best recommendation would to be use either SVG or canvas.
One example of a good SVG library is raphaeljs, check it out:
http://raphaeljs.com/
http://raphaeljs.com/animation.html
For canvas its quite simple to make shapes
https://developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Drawing_shapes
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15274867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to Compile Consumer-Producer-ApI in Linux I want to ./waf consumer-producer-api but it show some error CXXFLAGS error
and onChanged() error.
please help me...
I use linux-mint and set up complete ndn-cxx and openssl
$./waf configure
Setting top to : /home/ndn/ntorrent/Consumer-
Producer-API
Setting out to : /home/ndn/ntorrent/Consumer-
Producer-API/build
Checking for 'gcc' (C compiler) : /usr/bin/gcc
Checking for 'g++' (C++ compiler) : /usr/bin/g++
Checking for program 'doxygen' : /usr/bin/doxygen
Checking for program 'tar' : /bin/tar
Checking for program 'sphinx-build' : /usr/bin/sphinx-build
**Checking supported CXXFLAGS : -std=c++0x -std=c++11 -Wall -
Wno-long-long -Wno-nested-anon-types -O2 -g**
Checking supported LINKFLAGS :
Checking for program 'pkg-config' : /usr/bin/pkg-config
Checking for 'libndn-cxx' : yes
Checking boost includes : 1.58.0
Checking boost libs : ok
Checking for boost linkage : ok
'configure' finished successfully (4.485s)
$./waf
Waf: Entering directory `/home/ndn/ntorrent/build'
[ 1/12] Compiling src/file-manifest.cpp
../src/file-manifest.cpp: In member function ‘void
ndn::ntorrent::FileManifest::encodeContent()’:
../src/file-manifest.cpp:240:13: error: ‘onChanged’ was not declared in this
scope
onChanged();
^
At global scope:
cc1plus: warning: unrecognized command line option ‘-Wno-nested-anon-types’
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47470381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React: Absolute Position In Child Components Introduction: I have a React component structure that looks like this.
-- ParentComponent.tsx --
<div>Some Content Here</div>
<ChildComponent/>
<div style={{ position: "relative", zIndex: "1" }}>
Some Other Content -- should be covered when the absolutely positioned content
inside of ChildComponent renders on the screen!
</div>
-- ChildComponent.tsx --
/* at the top of my render method */
const [booleanCondition, setBooleanCondition] = useState(false);
const toggleBooleanCondition = () => { setBooleanCondition(!booleanCondition); };
...
/* much later, in the return value of render method */
<div style={{ position: "relative", zIndex: "2" }}>
Some Content Here, capable of calling toggleBooleanCondition()
{ booleanCondition ?
<div style={{ position: "absolute", width: "400px", height: "400px" }}>
Some Content Here. Should definitely cover the bottom <div> in parent!
</div>
: <></>
</div>
The toggle logic definitely works. The problem is, I would expect the div in ChildComponent.tsx to sit cleanly on top of the div in ParentComponent.tsx, which has a smaller z-index. However, this is not the case: the screenshot below shows that elements are being rendered in a random sort of order.
I feel like the issue may be due to different components assigning different meanings to their own z-indexes. No matter how I played with position: relative, and z-index: , nothing seemed to change. Does anybody know of a reliable solution to this problem??
A: My CSS background wasn't white. Lol.
<div style={{ position: "absolute", width: "400px", height: "400px", backgroundColor: "white"}}>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74542463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: nstimer count down not working as expected I am using nstimer to show count down timer in a label. I am able to start the timer and show the count down in the label but the timer jumps to next second rather than showing every second. If the count down timer is set to 10 sec then it shows only 9,7,5,3,1 in the count down timer label.
Below is my code.
NSTimer *tktTimer;
int secondsLeft;
- (void)startTimer {
secondsLeft = 10;
tktTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}
-(void) updateCountdown {
int hours, minutes, seconds;
secondsLeft--;
NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
if (--secondsLeft == 0) {
[tktTimer invalidate];
countDownlabel.text = @"Completed";
}
}
Any help will be really appreciated.
A: --secondsLeft updates the variable. To check if the next decrement will be 0, use if (secondsLeft - 1 == 0)
Each tick is decrementing the variable twice.
Additionally, this will trigger the "Completed" text on 1, not 0. Below is a better way to handle this:
-(void) updateCountdown {
int hours, minutes, seconds;
secondsLeft--;
if (secondsLeft == 0) {
[tktTimer invalidate];
countDownlabel.text = @"Completed";
return;
}
NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
A: //sweet and simple way to perform timer with easy and understandable code
DECLARE
int seconds;
NSTimer *timer;
//in viewDidLoad method
seconds=12;
timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(GameOver) userInfo:nil repeats:YES ];
-(void)GameOver
{
seconds-=1;
lblUpTimer.text=[NSString stringWithFormat:@"%d",seconds];//shows counter in label
if(seconds==0)
[timer invalidate];
}
THANK YOU
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40741035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Discord.py bot events formatted exactly the same yet one runs and one won't run I've recently been experimenting with discord bots and the discord API, but I have come to a problem with bot events. When made two events using the discord.py module, only one would work while the other one did not, yet both were formatted exactly the same. Why is this happening and how can I fix this problem? Here is my code:
@bot.event
async def on_message(message):
message = await bot.wait_for_message(author=message.author)
if message.content.startswith('!genlifetime password'):
global amount
amount = message.content[len('!genlifetime password'):].strip()
num = int(amount)
chars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
for x in range(0, num):
authkey1 = ''
authkey2 = ''
authkey3 = ''
authkey4 = ''
for i in range(0,4):
authkey1 = authkey1 + chars[random.randrange(0,35)]
for i in range(0,4):
authkey2 = authkey2 + chars[random.randrange(0,35)]
for i in range(0,4):
authkey3 = authkey3 + chars[random.randrange(0,35)]
for i in range(0,4):
authkey4 = authkey4 + chars[random.randrange(0,35)]
authkey = authkey1 + '-' + authkey2 + '-' + authkey3 + '-' + authkey4
print(authkey)
with open(keyfile, 'a') as f:
f.write(authkey + ' LIFETIME \n')
@bot.event
async def authorize(message):
message = await bot.wait_for_message(author=message.author)
if message.content.startswith('!activate'):
global key
key = message.content[len('!activate'):].strip()
print(key)
bot.run("NTM3Mzk1NDQzNzAxNjQ1MzEz.DykoDA.x5PrEwxZ0hlY2TeCtKVlg1QsbfQ")
When I run my bot and type in !genlifetime password 10, the bot will generate 10 keys like it is supposed to, print them in the shell, and put them in keys.txt. However, the authorize event does not work at all. If I type in !authorize key nothing happens in the shell. The key is not printed at all. I even tried putting a print before the message = await bot.wait_for_message(author=message.author) but that print would not print out either. Both events are formatted the same way, so why does one work while the other does not?
A: I am thinking that the code should maybe look like this:
@bot.event
async def on_message(message):
message = await bot.wait_for_message(author=message.author)
if message.content.startswith('!activate'):
global key
key = message.content[len('!activate'):].strip()
print(key)
if message.content.startswith('!genlifetime password'):
global amount
amount = message.content[len('!genlifetime password'):].strip()
num = int(amount)
chars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
for x in range(0, num):
authkey1 = ''
authkey2 = ''
authkey3 = ''
authkey4 = ''
for i in range(0,4):
authkey1 = authkey1 + chars[random.randrange(0,35)]
for i in range(0,4):
authkey2 = authkey2 + chars[random.randrange(0,35)]
for i in range(0,4):
authkey3 = authkey3 + chars[random.randrange(0,35)]
for i in range(0,4):
authkey4 = authkey4 + chars[random.randrange(0,35)]
authkey = authkey1 + '-' + authkey2 + '-' + authkey3 + '-' + authkey4
print(authkey)
with open(keyfile, 'a') as f:
f.write(authkey + ' LIFETIME \n')
Although, I haven't tested this.
A: The wait_for_message calls seem superfluous: according to the docs, the message argument passed into the callbacks is the message you want. If you were to remove the calls to wait_for_message and just use the message passed in directly, it would probably work as expected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54337435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: New Relic Plugin with Custom Page Since New Relic is a kind of “heart” of the operation of our IT Infrastructure, I would like to add static pages that has links to our Knowledge Base system, javascript based live debugging, etc.
I imagined something like to a Plugin that, instead of having graphs, it is HTML section to be show inside New Relic.
Is it possible?
Regards,
Vitor
A: Unfortunately, it is not possible to do this at this time with the New Relic User Interface. We always appreciate insight into the needs of our customers so we have submitted a feature request on your behalf and should such functionality become available you will be notified.
Thanks!
Dana
New Relic - Tech Support
A: If you only need it to support users within your company, a firefox/chrome extension that injects the relevant content into the page could work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18787024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Making a dynamic grid with jquery I'm trying to create a dynamic grid using jquery where it will eventually change with user input (i.e. 16x16, 32x32, etc). My logic is to create 16 rows and then 16 squares within each row, but I'm having trouble getting the squares to append the correct amount.
$(document).ready(function () {
for (var i = 0; i < 16; i++) {
$('.grid').append("<div class = 'row'></div>");
//$('.row').width(($('.square').width().val() * i);
//for (var i = 0; i < 16; i++) {
$('.row').append("<div class='square'></div>");
// }
}
});
Here is a link to what it looks like: https://lettda.github.io/EtchAsketch/
A: .row selects all the elements which have the class row which means that you're not appending the .square divs to only the last created row, you're appending them to all the previously created ones as well.
To prevent that, you can do something like this.
for (var i = 0; i < 16; i++) {
var row = $("<div class = 'row'></div>");
for (var j = 0; j < 16; j++) {
var square = $("<div class='square'></div>");
row.append(square);
}
$('.grid').append(row);
}
OR
for (var i = 0; i < 16; i++) {
$('.grid').append("<div class='row' id='row"+i+"'></div>");
for (var j = 0; j < 16; j++) {
$('#row'+i).append("<div class='square'></div>");
}
}
A: Moving your inner for loop outside of the outer for loop should create the proper amount of squares, as such:
for (var i = 0; i < 16; i++) {
$('.grid').append("<div class = 'row'></div>"); // Each grid gets 16 rows
}
for (var i = 0; i < 16; i++) {
$('.row').append("<div class='square'></div>"); // Each row gets 16 squares
}
Explicitly setting the width of the row is not necessary, as it will automatically be 16 times the width of your square plus any padding/margin you add. Note that all your squares would need display: inline-block; in the CSS to ensure that they are side by side. Also, the rows would wrap if there are too many squares in each row or the squares are too wide.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38964952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Not sure how to add image variance to php/sql population of HTML table Situation
I am currently populating an HTML table using PHP, which is working just fine using this code:
<?php
while ($row = mysqli_fetch_array($result)) {
$lineID = $row['lineID'];
$ediShipDate = $row['ediShipDate'];
$resolution = $row['resolution'];
$resolutionComments = $row['resolutionComments'];
?>
Issue
I am trying to make it so with each individual line, if ediShipDate equals one thing, I place one image there (instead of the text inside that variable), and if it equals another thing, to place a different image. I'm trying using this code in the middle here:
<td>
<?= $cost?>
<value="<?= $cost?>"></td>
<td>
<?php
if ($row['ediShipDate'] = "Before Debit Exp"){
print("<img src=/img/check-yes.png>");
print("one") ;
}
else if ($row['ediShipDate'] = "AFTER DEBIT EXP!"){
print("<img src=/img/check-no.png>");
print("two") ;
}
else {
print $row['ediShipDate'] ;
print("three") ;
}
?>
<value="<?= $ediShipDate ?>"></td>
<td>
<?= $cost?>
<value="<?= $cost?>"></td>
With my test data, I have 4 rows. The first three's value is "Before Debit Exp" while the fourth's value is "AFTER DEBIT EXP!", however, in the debug code I have here print("one") etc..., all four rows are evaluating to the first statement, regardless of their value, and printing out check-yes.png I've tried changing all of them to have the actual value of "AFTER DEBIT EXP!" to no avail.
Why is this? There is nothing in the logs or the console.
A: In your IF statement you're assigning the value not comparing.
= vs == or ===
You need to switch them to == at the very least, but it would be better to use ===.
<?php
if ($row['ediShipDate'] === "Before Debit Exp"){
print("<img src=/img/check-yes.png>");
print("one") ;
}
else if ($row['ediShipDate'] === "AFTER DEBIT EXP!"){
print("<img src=/img/check-no.png>");
print("two") ;
}
else {
print $row['ediShipDate'] ;
print("three") ;
}
?>
<value="<?= $ediShipDate ?>"></td>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26939627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disable CheckedListBox Autoscroll on item checked? Situation: I have a CheckedListBox with a horizontal scroll bar enabled with CheckOnClick set to true. The size of the CheckListBox is such that two column of items is shown.
Issue: When the user clicks on an item in the second column to check it on or off, the horizontal scroll bar automatically shifts the entire row such that it's in the first column.
Question: How do I disable the CheckedListBox from automatically shifting? I took a look at the properties but I can't seem to find one that would disable it, does the answer lie in inheriting the CheckedListBox and overriding methods?
Thanks for the help!
A: if you always want to go back to the top-left item (scroll back all the way to the left), just select item[0] programmatically on SelectedIndexChanged... this will still fire off the "check" and actually DO the "check on check off", but will return to the first item in the list...
like this:
private void lst_Servers_SelectedIndexChanged(object sender, EventArgs e)
{
this.lst_Servers.SelectedIndex = 0;
}
A: The problem was: when you size your table you have to do it very carefully, ensure that the rightmost column is entirely within the visible area, otherwise if you edit a cell in that column the table would scroll left...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23370714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Comparing columns in a list I have done splitting on the csv file(link given below) and my data output is given below. I need little help in comparing country column and return only the movie names that are made in the USA only. How do I do that?
data = open("movie_metadata.csv", "r").read().split("\\n")
movie_data = [i.split(",") for i in data]
print(movie_data[1:4])
output:
[['movie_title','director_name','color','duration','actor_1_name','language',
'country','title_year'],
['Avatar','James Cameron','Color','178','CCH Pounder','English','USA',
'2009'],
["Pirates of the Caribbean: At World's End",'Gore Verbinski','Color',
'169','Johnny Depp','English','USA','2007'],
['Spectre','Sam Mendes','Color','148','Christoph Waltz','English','UK',
'2015']]
CSV File
A: You want to filter the list based on the country column.
us_movies = [movie for movie in movies if movie[6] == 'USA']
You can also transform the line into just the title if you like.
us_movie_titles = [movie[0] for movie in movies if movie[6] == 'USA']
If you want a corresponding list of match predicate results, this will work:
is_match = [movie[6] == 'USA' for movie in movies]
Note, the size of the first two lists may be smaller than the original list, but is_match will have the same size and ordering as your original list.
To add the booleans to your full dataset:
movies_with_usa = [m[0] + [m[1]] for m in zip(movies, is_match)]
But what you really have is named data, so it's probably more appropriate in a dictionary or object. Also, if you're reading a csv file, a csv reader is part of the standard library. So for something a little more robust
import csv
def read_data(filename):
with open(filename) as f:
reader = csv.DictReader(f)
return [row for row in reader]
def match(record, field, value):
return record[field] == value
data = read_data("movie_metadata.csv")
us_movies = [record for record in data if match(record, 'country', 'USA')]
A: You want to use a pandas dataframe and then you can filter very easily based on the columns.
import pandas as pd
df = pd.DataFrame(movie_data[1:],columns = movie_data[0])
movie_title director_name color duration actor_1_name language country title_year
0 Avatar James Cameron Color 178 CCH Pounder English USA 2009
1 Pirates of the Caribbean: At World\'s End Gore Verbinski Color 169 Johnny Depp English USA 2007
2 Spectre Sam Mendes Color 148 Christoph Waltz English UK 2015
df[df.country == "USA"]
movie_title director_name color duration actor_1_name language country title_year
0 Avatar James Cameron Color 178 CCH Pounder English USA 2009
1 Pirates of the Caribbean: At World\'s End Gore Verbinski Color 169 Johnny Depp English USA 2007
A: Just iterate over all movies and compare the 7th column:
made_usa = []
for l in movie_data:
if l[6] == 'USA':
made_usa.append(l)
print (made_usa)
To add only the movie name, it is just to do this:
made_usa = []
for l in movie_data:
if l[6] == 'USA':
made_usa.append(l[0])
print (made_usa)
To save if there is a match or not, you can use a dictionary like this:
made_usa = {}
for l in movie_data:
if l[6] == 'USA':
made_usa.update({l[0]: 'True'})
else:
made_usa.update({l[0]: 'False'})
print (made_usa)
After that, if you want to look if a certain move was made in USA or not. All you need to do is, for example:
print(made_usa['Avatar'])
Output:
'True'
A: Probably you are looking for a generic solution without any third party libraries (i.e. only standard library). Here we go:
def filter_by(csv_data, column_name, column_value):
indices = [i for i, name in enumerate(data[0]) if name == column_name]
if not indices:
return
index = indices[0]
for row in data[1:]:
if row[index] == column_value:
yield row
And this is how you use it:
print(list(filter_by(movie_data, "country", "USA")))
This shall output (I formatted it a bit for clarity):
[
['Avatar', 'James Cameron', 'Color', '178', 'CCH Pounder', 'English', 'USA', '2009'],
["Pirates of the Caribbean: At World's End", 'Gore Verbinski', 'Color', '169', 'Johnny Depp', 'English', 'USA', '2007']
]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51430857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Download table generated independetly in renderTable output in R shiny I am trying to generate a table using the renderTable function in R shiny and then use the downloadHandler function to download that table/data.frame as a csv file. Somehow I keep getting the following error:
An error occured during download:
Error downloading http://127:0:0.1:3001/session/
0303bd426fce88837ae277aa3b406dd/download/downloadData?w= - server
replied: Internal Server Error
Below is an example code where I generate a simple data frame and try to download it using downloadHander:
library(shiny)
# Define UI for data download app ----
ui <- fluidPage(
# App title ----
titlePanel("Downloading Data"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Button
downloadButton("downloadData", "Download")
),
# Main panel for displaying outputs ----
mainPanel(
tableOutput("table")
)
)
)
# Define server logic to display and download selected file ----
server <- function(input, output) {
# Table of selected dataset ----
output$table <- renderTable({
data.frame(a =c(1,2,3),b=c("q","s","f"))
})
# Downloadable csv of selected dataset ----
output$downloadData <- downloadHandler(
filename = function() {
paste("test.csv")
},
content = function(file) {
write.csv(output$table, file, row.names = FALSE)
}
)
}
shinyApp(ui,server)
A: There are a few things that need to be done here:
*
*If your app is going to render data dynamically, then your data should be assigned to some reactive expression.
*Now the downloading of the data becomes easy, as you just call the reactive expression written in (1).
*
*Points (1) and (2) above will ensure that the user is downloading the same data that is seen on the screen.
Try the following:
library(shiny)
ui <- fluidPage(
titlePanel("Downloading Data"),
sidebarLayout(
sidebarPanel(downloadButton("downloadData", "Download")),
mainPanel(tableOutput("table"))
)
)
server <- function(input, output) {
data <- shiny::reactive(data.frame(a = c(1, 2, 3), b = c("q", "s", "f")))
output$table <- renderTable(data())
output$downloadData <- downloadHandler(
filename = function() {
paste("test.csv")
},
content = function(file) {
write.csv(data(), file, row.names = FALSE)
}
)
}
shinyApp(ui,server)
A: You cannot export a renderTable{} as this puts many of the elements into HTML,
you need to previously save the data going into the table and export it
seperately.
dataTable<-data.frame(a =c(1,2,3),b=c("q","s","f"))
output$downloadData <- downloadHandler(
filename = function() {
('test.csv')
},
content = function(con) {
write.table(dataTable,row.names = FALSE,col.names=T, sep=",",con)
},
contentType="csv"
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50590056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: gitlab-ci reference environmental variables in ssh command I have the following command in my gitlab-ci.yml file: - rsync -v -e ssh /builds/Sustersic/untitled-combat-game/build [email protected]:/var/www/html
I tried re-writing this command with environemntal varibales:
- rsync -v -e ssh /builds/Sustersic/untitled-combat-game/build "$HOST_USERNAME"@"$HOST_IP":/var/www/html
But the environment variables are not getting read correctly. What am I doing wrong?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60064869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating a symlink in WAMP server on Windows I am working on a downloaded version of an application and am getting multiple errors due to:
( ! ) Warning: include(/home/USERNAME/public_html/dir/includes/functions.php): failed to open stream: No such file or directory in C:\wamp\www\dir\includes\db_connection.php on line 6
I understand what the error is but I don't want to have to manually change all these includes in the code mainly as doing so means when I update my ive site they will then be wrong.
Is there a way using either WAMP or Windows of creating something like a symlink to tell WAMP that anything in /home/USERNAME/public_html/dir should be served from C:\wamp\www\dir?
I found an option in WAMP for creating an alias but I am not sure if this is the right thing to use?
A: There is an answer on SO here.
This link https://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html would serve well too (from the answer above).
Basically you have to use mklink Windows command from command prompt (the latter must be run as administrator).
Now. Assume you have WAMP installed and virtual host named mysite.local is created and pointinig to the physical d:\mysite folder. You want now the files in the folder f:\otherfolder\realfolder to be accessible via mysite.local/otherfolder/somefile.ext kind of URL.
For this you have to create the symbolic link named otherfolder in d:\mysite that will point to f:\otherfolder\realfolder. You have to execute:
mklink /D d:\myfolder\otherfolder f:\otherfolder\realfolder
from Windows command prompt. The link otherfolder is created in d:\myfolder and you can access files via an URL as mentioned above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35648882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Getting web.config error when publishing my ASP.Net website I'm trying to publish my first ASP.Net website, but I'm getting this error when I try to visit the homepage.
Unrecognized attribute 'targetFramework'. Note that attribute names
are case-sensitive.
Here's the section of the web.config file it is referencing:
<system.web>
<customErrors mode="Off" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
And here's the website itself if you want to see the full error page:
http://connellchamberofcommerce.com/
Is the ASP.Net version (4.5.2) supposed to match the .Net version my host uses or something? As I said, this is my first ASP.Net website and I'm pretty confused by this error.
A: The version information at the bottom of http://connellchamberofcommerce.com/ indicates that the .net version of app pool is 2.0.50727.5491, where as in your web.config file its 4.5.2. So change the app pool to use 4.0.
A: Your web.config looks fine to me. My guess would be that you have set the wrong .NET version in the AppPool under which your site is running.
Go to your IIS -> Select your desired AppPool -> Click Basic settings and change the .Net version accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41278584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use of Local_policy.jar and US_export_policy.jar and What is the use of these jars:
Local_policy.jar
US_export_policy.jar
I have seen other SO questions where they are asking how to upgrade. My question is what's the use of these jars. It seems they come as a violation in open source.
A: THEY ARE OBSOLETE (at least as separate added files)
They were used in an optional, and (nominally) geographically restricted, patch to versions of Sun-then-Oracle Java before late 2017, to enable (symmetric) ciphers with strength of more than 128 bits, which were disabled in the basic distribution packages in a lingering after-effect of conformity to US export regulations from the 1990s. No such patch was ever needed for OpenJDK, once that was released (which only started after the 'crypto thaw'), but in its early years it wasn't widely supported and sometimes not consistently available, so many people continued using the Oracle/Sun versions -- and many Stack Overflow questions and/or answers (both Stack Overflow and others like security.SX and Super User and Server Fault) were written for that case. Since Stack Overflow doesn't automatically delete or even deprecate old content, it remains available.
For the official details (of the versions that still have any support, even paid) see https://www.oracle.com/java/technologies/javase-jce-all-downloads.html .
IBM has long had its own implementation of Java, especially the cryptographic parts, and had a similar (but not the same) set of policy jars; I don't know if they still do, since I no longer have IBM systems running Java. In any case, Stack Overflow questions and answers for IBM Java are rare.
The 'openness' of the original Sun-centered model for Java was somewhat controversial for years, until finally settled by the establishment of OpenJDK. If you want to discuss that, it probably belongs on https://opensource.stackexchange.com/ .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65221732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Rails atttr_accesible not working as documented In rails 3.2.1, I have a model:
class Player < ActiveRecord::Base
attr_accessor :password
attr_accessible :email, :password
attr_accessible :email, :password, :confirmed, :as => :admin
end
I keep getting a ActiveModel::MassAssignmentSecurity::Error for the following:
params[:player]
#=> {:email => "[email protected]", :password => "12345", :confirmed => true)
player = Player.new(params[:player])
Why is this happening when all I want it to do is ignore the :confirmed attribute and move on with it's business. The documentation makes it seem like I should be able to do that, but I keep getting this exception and it's really getting to me because either I am doing it wrong or the docs are wrong.
I'd love any help with this.
A: You can configure what you want to happen when a mass assignment happens by setting Player.mass_assignment_sanitizer (or set it on ActiveRecord::Base for it to apply to all AR models)
You can also set it in your configuration files via config.active_record.mass_assignment_sanitizer
Our of the box you can set it to either :logger, which just logs when these things happen or :strict which raises exceptions. You can also provide your own custom sanitizer. The current application template sets it to strict, although that used not to be the case
A: Comment out this line in development.rb:
config.active_record.mass_assignment_sanitizer = :strict
The strict setting will raise an error and the default setting will just log a warning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9743232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does bootsfaces work with jsp servlets? I am trying to migrate a project which has been working of JSF1.2 to JSF2.1 and have succeeded in doing so ,now we want to use bootsfaces1.0.2 in the project to enhance look and feel of the application.
Our codebase is pretty old and we want to stick to JSP to avoid complexity and time needed to migrate to facelets
When I checked bootsfaces-b.taglib.xml file under META-INF of bootsfaces-1.0.2.jar, it basically uses facelets tag library
http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
We include the bootsfaces tag lib <%@ taglib uri="http://bootsfaces.net/ui" prefix="b" %> and it was failing , so I manually created a tld file which points to jsp tag library and changed the tag structure to be compliant with jsp 2.1 tag library , here is the stacktrace of exception I get
PWC6197: An error occurred at line: 28 in the jsp file: /jsp/login/login2.jsp
PWC6199: Generated servlet error:
method get in class org.apache.jasper.runtime.TagHandlerPool cannot be applied to given types;
required: java.lang.Class
found: java.lang.Class
reason: inferred type does not conform to upper bound(s)
inferred: net.bootsfaces.component.inputText.InputText
upper bound(s): javax.servlet.jsp.tagext.JspTag
PWC6197: An error occurred at line: 28 in the jsp file: /jsp/login/login2.jsp
PWC6199: Generated servlet error:
cannot find symbol
symbol: method setPageContext(javax.servlet.jsp.PageContext)
location: variable _jspx_th_b_inputText_0 of type net.bootsfaces.component.inputText.InputText
It seems the tag library is expecting a servlet , but bootfaces would supply a facelet component instead,
Has anyone tried to run bootsfaces on jsf2.1/Jsp ,can you provide me any suggestions on this.
Thanks,
Santosh
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42792325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why can't update my form even though my session is working php So i want a very simple update page like this example:
<?php
$sql_article = "SELECT* FROM articles WHERE article_unique_id = '". $_SESSION['article_unique_id']."' ";
$result_article = $conn->query($sql_article);
if ($result_article->num_rows > 0) {
while($row = $result_article->fetch_assoc())
{?>
<form action="trry15.php" method="post">
<input type="text" name="title" value="<?php echo $row['title'] ?>">
<input type="submit" name="submitUpdate" value="Submit"></form> <?php }}?>
and to this point code works fine session works and ect.
but when I write my update code
if (isset($_POST['submitUpdate'])) {
$update_title=$_POST['title'];
$sql_update_title = "UPDATE `articles` SET title='$update_title' WHERE article_unique_id = '". $_SESSION['article_unique_id']."'";
$result_update_title=$conn->query($sql_update_title);
}
This dosent work.
But if change article_unique_id = '". $_SESSION['article_unique_id']."'"; to
article_unique_id = '12'";
The code works. And I don't what is happening. I have session start function and $_SESSION['article_unique_id']=$_GET['article_id'];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42447475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add known_hosts for passwordless ssh within docker container in docker-compse.yml? I want to have passwordless ssh within two docker containers. How to add known_hosts entry for that using docker-compose.yml file
I want to implement ansible on docker env. To deploy and run rpm on deployment node, I need passwordless ssh from container1 to container2. For that I have to add known_hosts key of container1 in container2 node.
How to do this ???
A: I don't know any solution using docker-compose.yml. The solution I propose implies create a Dockerfile and execute (creating a shellscript as CMD):
ssh-keyscan -t rsa whateverdomain >> ~/.ssh/known_hosts
Maybe you can scan /ect/hosts or pass a variable as ENV.
A: try to mount it from host to container. .
--volume local/path/to/known_hosts:/etc/ssh/ssh_known_hosts
in case it didnt work, take a look at some similar case related to ssh key in docker like : this
and this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48258546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it a good practice to use alternate exchange in RabbitMQ as dead letter exchange? I know that RabbitMQ has alternative and dead letter exchange types.
Since we don't have mapped queues for some message, from my perspective it is some kind of problem when we don't know what the message is. In this case we use alternative exchange to rout the message to another exchange by default (that can solve our routing problem).
Is it a good practise to use alternative exchange as dead letter exchange simultaneously?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47463274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Where do I merge or add the drop down menu script on the header. Jsfiddle I'm trying to merge 2 codes. I found the two codes I'm looking for. I'm really new @ this so please under stand.
This is the header footer & background:
http://jsfiddle.net/F6dez/
This is the drop down menu:
http://jsfiddle.net/Mrdel/Wxs5n/2/
This is my attempt to merge the two:
I tried to leave a link but it won't let me leave more then 2 links :/
Heres the code for the menu:
HTML:
<ul id="nav">
<li>
<a href="#">Music</a>
<ul>
<li><a href="#">New Tracks</a></li>
<li><a href="#">Old Tunes</a></li>
<li><a href="#">Downloads</a></li>
<li><a href="#">Upcoming</a></li>
</ul>
</li>
</ul>
</li>
</ul>
And the css:
ul { list-style: none; padding: 0; margin: 0;}
/* Style */
a {
color: #000;
display: block;
font-size: 14px;
text-decoration: none;
font-family: 'Open Sans', serif;
}
nav {
width: 100%;
height: 45px;
}
#nav ul li:hover,
#nav > li:hover {
background: #2e98d5;
}
#nav ul > li:hover > a,
#nav > li:hover > a {
color: #fff;
}
#nav > li {
float: left;
position: relative;
}
#nav > li > a {
padding: 13px 30px;
height: 20px;
}
#nav > li:hover ul {
visibility: visible;
-webkit-transition-delay: 0s;
-moz-transition-delay: 0s;
-o-transition-delay: 0s;
transition-delay: 0s;
}
#nav ul {
top: 46px;
width: 170px;
position: absolute;
background-color: #eee;
z-index: 1;
visibility: hidden;
-webkit-transition-property: visibility;
-moz-transition-property: visibility;
-o-transition-property: visibility;
transition-property: visibility;
-webkit-transition-duration: 0s;
-moz-transition-duration: 0s;
-o-transition-duration: .0s;
transition-duration: 0s;
-webkit-transition-delay: .25s;
-moz-transition-delay: .25s;
-o-transition-delay: .25s;
transition-delay: .25s;
}
/* The slide */
#nav li li a {
height: 0px;
padding: 0px 30px;
opacity: 0;
-webkit-transition-property: height, padding, opacity;
-moz-transition-property: height, padding, opacity;
-o-transition-property: height, padding, opacity;
transition-property: height, padding, opacity;
-webkit-transition-duration: .25s, .25s, .08s;
-moz-transition-duration: .25s, .25s, .08s;
-o-transition-duration: .25s, .25s, .08s;
transition-duration: .25s, .25s, .08s;
-webkit-transition-delay: 0s, 0s, .05s;
-moz-transition-delay: 0s, 0s, .05s;
-o-transition-delay: 0s, 0s, .05s;
transition-delay: 0s, 0s, .05s;
}
#nav li:hover li a {
height: 20px;
padding: 13px 30px;
opacity: 1;
}
Heres the code for the background:
HTML:
<!Doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div class="container">
<div class="header">
This is header
</div>
<div class="content">
<div class="gap"></div>
<p>First line...............</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Long content goes here...</p>
<p>Last line................</p>
<div class="gap"></div>
</div>
<div class="footer">
This is footer
</div>
</div>
</body>
</html>
And the css:
html {
height:100%;
max-height:100%;
padding:0;
margin:0;
border:0;
overflow: hidden;
}
body {
height:100%;
max-height:100%;
overflow:hidden;
padding:0;
margin:0;
border:0
font: 12px Verdana, Helvetica, sans-serif;
color: #F3F3F3;
}
.container {
width : 100%;
height: 100%;
max-height:100%;
}
.header {
position:absolute;
margin:0;
top:0;
display:block;
width:100%;
height:80px;
z-index:5;
background-color: #656565;
text-align : center;
right:18px;
line-height: 80px;
font-size:2em;
}
.footer {
position:absolute;
margin:0;
bottom:-1px;
display:block;
width:100%;
z-index:4;
height : 80px;
background-color: #656565;
text-align : center;
right:18px;
line-height: 80px;
font-size:2em;
}
.content {
display:block;
height:100%;
max-height:100%;
overflow:auto;
position:relative;
z-index:3;
background-color: #909090;
text-align : center;
}
.gap {height : 80px;}
A: I'm not entirely sure I understand what you're looking for here, since it should be as easy as copying the menu code:
<ul id="nav">
<li>
<a href="#">Music</a>
<ul>
<li><a href="#">New Tracks</a></li>
<li><a href="#">Old Tunes</a></li>
<li><a href="#">Downloads</a></li>
<li><a href="#">Upcoming</a></li>
</ul>
</li>
</ul>
and pasting it into the head container:
http://jsfiddle.net/LH5TC/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24541818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Server to Server communication with IBM SBT I would like to use the IBM SBT for server to server communication instead of displaying data from , for instance, connections at the user. In this particular usecase I would like to have data updated in Connections whenever a user saves or edits data.
Because we are not using oAuth we would like to use Basic authentication without prompting the user for authentication. Are there any examples how to do is?
A: yes there are some examples of using Pure Java, no J2EE.
http://bastide.org/2014/01/28/how-to-develop-a-simple-java-integration-with-the-ibm-social-business-toolkit-sdk/
and
https://github.com/OpenNTF/SocialSDK/blob/master/samples/java/sbt.sample.app/src/com/ibm/sbt/sample/app/BlogServiceApp.java
Essentially, you'll need the dependent jar files.
once, you have the jar files you need to configure your class so you can get an Endpoint
once you have the endpoint you can use the endpoint in one of the top level services such
as ForumsService
then you can use the ForumsService to call back to Connections
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21525351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JS - function take a double result I got problem with this script:
<script>
var start = 400;
var interval = 40;
function counter() {
return start -= interval;
}
var stop = setInterval (
function add() {
if (counter() > 0)
document.getElementById("test").innerHTML = counter();
else
clearInterval(stop);
},1000);
</script>
<button onclick="clearInterval(stop)">stop!</button>
<br/>
<p id="test">On marks! Start!</p>
The script counts down from 400 to 0, with a variable interval = 40. When the script runs it subtracts 80 instead of 40. The result is double and I don't know why.
Can you help me?
A: You're calling counter() twice, subtracting 40 each time, call it just once
var start = 400;
var interval = 40;
function counter() {
return start -= interval;
}
var stop = setInterval(function() {
var count = counter();
if (count > 0) {
document.getElementById("test").innerHTML = count;
} else {
clearInterval(stop);
}
}, 1000);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28355577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does Git merge to master delete unchanged files? I have a two branch first one "master" second one "newFeature"
In the master branch, I add some file and change some functions it does not exist in newFeature branch and the same in newFeature have added some new files/code AND Change file it exists in two branches and I want to apply when merged
Now when I want to merge newFeature to master,
Should I lose something in the master or other branch?
A: Git's merge operation considers exactly three points when doing a merge: the two heads (usually branches) that you want to merge, and the merge base, which is usually the point at which one was forked from the other.
When a merge occurs, Git considers the changes computed between each head and the merge base. It then produces a result exactly like the merge base, but with both sets of changes added. In other words:
*
*If you made a change on one side and not the other, Git will include the change. A change in this case includes the addition, removal, or modification of a file or part of it.
*If you made a change to the same location on both sides, Git will produce a conflict.
*If you made no changes to a file or part of it, Git will include those portions unchanged.
So in your case, you've only added and modified things, so the merge result will include only additions and modifications, not removals. It is possible you'll see a conflict, though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60791476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Symfony All blank pages after cache clear I recently was making changes to my Symfony 2 site and then did a clear cache command on the site. Afterwards when I returned to the site the pages were blank.
Here's the command I ran
app/console cache:clear --env=prod
I've heard that it might be related to file permissions on the cache folder, but I'm not sure.
I logged in at the root level to be able to run the run the above command becuase I was getting an 'access denied' error when i was logged in at the user level.
Any helped/insight would be greatly appreciated.
A: You seem to have run cache:clear as root user without the --no-warmup flag.
Now symfony has warmed the cache after clearing it using the root account which would result in the newly created cache files being owned by your root user. Depending on your umask the webserver-user now might not have r+w access to these files.
Make sure your webserver-user / cgi-user has read and write access to your cache folder or give the ownership back to this user.
sudo chown webserver_user:webserver_group -R app/cache
sudo chmod 770 -R app/cache # or use acl to permit read/write to your webserver-user
A: Make sure the permissions for the app/cache and app/logs are set correctly for both the web server user and the CLI user.
The Symfony Book has instructions on how to do it.
If your OS supportschmod +a (OSX) you can do the following:
$ rm -rf app/cache/*
$ rm -rf app/logs/*
$ sudo chmod +a "www-data allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
$ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
If your OS supports setfacl (Ubuntu, for example) and ACL support is enabled, you can do the following:
$ sudo setfacl -R -m u:www-data:rwX -m u:`whoami`:rwX app/cache app/logs
$ sudo setfacl -dR -m u:www-data:rwx -m u:`whoami`:rwx app/cache app/logs
Note: both examples assume that the username for the web server user is www-data
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17729973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I test this async piece of code in Flutter using Mockito? I am trying to write some test for an app, but I can't test values stored in a provider. I am relatively new to testing, so there might be something that I am doing wrong, but anyway. What I want to test is to verify is two values are not the same, which should be the expected behavior, but I just can't make it pass.
This is the code that I want to test:
class RSAKeysProvider {
KeyPair? _keyPair;
KeyPair? get keyPair => _keyPair;
set setKeyPair(KeyPair keyPair) => _keyPair = keyPair;
Future<void> generate(String bits) async {
var keyPair = await RSA.generate(int.parse(bits));
_keyPair = keyPair;
notifyListeners();
}
}
I need to first call the generate() function, which will set the keyPair to actual values, and then check if keyPair.publicKey is different than keyPair.privateKey, but it gives me an error when I try to call generate() with await inside a test.
This is what I have for now, but it doesn't work. The test breaks when it cames to the line "await rsaKeys.generate('2048'). What can I do to make it work? I know the condition is not checking if both are different, but it is just a placeholder, I can't make the code arrive there!
test('Public and private key should be different', () async {
final MockRSAKeysProvider rsaKeys = MockRSAKeysProvider();
when(rsaKeys.generate(any)).thenAnswer((value) async {
KeyPair keyPair = await RSA.generate(2048);
rsaKeys.setKeyPair = keyPair;
});
await rsaKeys.generate('2048');
expect(rsaKeys.keyPair?.privateKey, isNotNull);
expect(rsaKeys.keyPair?.publicKey, isNotNull);
});
When it arrives at "await rsaKeys.generate('2048'), it gives me this error:
Invalid argument(s): Failed to load dynamic library 'librsa_bridge.dylib': dlopen(librsa_bridge.dylib, 0x0001): tried: 'librsa_bridge.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OSlibrsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/./librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/../../../librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/Frameworks/librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/./librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/../../../librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/Frameworks/librsa_bridge.dylib' (no such file), '/usr/lib/librsa_bridge.dylib' (no such file, not in dyld cache), 'librsa_bridge.dylib' (no such file), '/usr/lib/librsa_bridge.dylib' (no such file, not in dyld cache)
dart:ffi new DynamicLibrary.open
package:fast_rsa/bridge/binding.dart 117:33 Binding.openLib
package:fast_rsa/bridge/binding.dart 26:16 new Binding._internal
package:fast_rsa/bridge/binding.dart 17:45 Binding._singleton
package:fast_rsa/bridge/binding.dart Binding._singleton
package:fast_rsa/bridge/binding.dart 22:12 new Binding
package:fast_rsa/fast_rsa.dart 40:32 RSA.bindingEnabled
package:fast_rsa/fast_rsa.dart RSA.bindingEnabled
package:fast_rsa/fast_rsa.dart 43:9 RSA._call
package:fast_rsa/fast_rsa.dart 79:22 RSA._keyPairResponse
package:fast_rsa/fast_rsa.dart 437:18 RSA.generate
test/rsa_keys.test.dart 32:37 main.<fn>.<fn>.<fn>
package:mockito/src/mock.dart 185:45 Mock.noSuchMethod
test/rsa_keys.test.mocks.dart 75:53 MockRSAKeysProvider.generate
test/rsa_keys.test.dart 36:21 main.<fn>.<fn>
A: Your stub calls RSA.generate, so it depends on the RSA.generate implementation which involves FFI and loading a dynamically-loaded library on whatever platform you run tests on. Unless you're trying to test package:fastrsa itself, you should avoid calling things such as RSA.generate anyway; that is what you should be replacing with a stub.
The point of a Mock is to test how other code interacts with the mocked object. You cannot use a MockRSAKeysProvider to test the behavior of an RSAKeysProvider itself. If you want to test the behavior of your RSAKeysProvider class, you could change it to accept a stub for RSA.generate:
class RSAKeysProvider {
KeyPair? _keyPair;
KeyPair? get keyPair => _keyPair;
set setKeyPair(KeyPair keyPair) => _keyPair = keyPair;
Future<void> generate(String bits, {Future<KeyPair> Function(int)? generate}) async {
generate ??= RSA.generate;
var keyPair = await generate(int.parse(bits));
_keyPair = keyPair;
notifyListeners();
}
}
and then in your test:
Future<KeyPair> fakeGenerate(int bits) async {
return KeyPair('fakePublicKey', 'fakePrivateKey'); // Or use precomputed values.
}
test('Public and private key should not be null when generated', () async {
final RSAKeysProvider rsaKeys = RSAKeysProvider();
await rsaKeys.generate('2048', generate: fakeGenerate);
expect(rsaKeys.keyPair?.privateKey, isNotNull);
expect(rsaKeys.keyPair?.publicKey, isNotNull);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75493892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MVVM Sync Collections Is there a standardized way to sync a collection of Model objects with a collection of matching ModelView objects in C# and WPF? I'm looking for some kind of class that would keep the following two collections synced up assuming I only have a few apples and I can keep them all in memory.
Another way to say it, I want to make sure if I add an Apple to the Apples collection I would like to have an AppleModelView added to the AppleModelViews collection. I could write my own by listening to each collections' CollectionChanged event. This seems like a common scenario that someone smarter than me has defined "the right way" to do it.
public class BasketModel
{
public ObservableCollection<Apple> Apples { get; }
}
public class BasketModelView
{
public ObservableCollection<AppleModelView> AppleModelViews { get; }
}
A: I use lazily constructed, auto-updating collections:
public class BasketModelView
{
private readonly Lazy<ObservableCollection<AppleModelView>> _appleViews;
public BasketModelView(BasketModel basket)
{
Func<AppleModel, AppleModelView> viewModelCreator = model => new AppleModelView(model);
Func<ObservableCollection<AppleModelView>> collectionCreator =
() => new ObservableViewModelCollection<AppleModelView, AppleModel>(basket.Apples, viewModelCreator);
_appleViews = new Lazy<ObservableCollection<AppleModelView>>(collectionCreator);
}
public ObservableCollection<AppleModelView> Apples
{
get
{
return _appleViews.Value;
}
}
}
Using the following ObservableViewModelCollection<TViewModel, TModel>:
namespace Client.UI
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;
public class ObservableViewModelCollection<TViewModel, TModel> : ObservableCollection<TViewModel>
{
private readonly ObservableCollection<TModel> _source;
private readonly Func<TModel, TViewModel> _viewModelFactory;
public ObservableViewModelCollection(ObservableCollection<TModel> source, Func<TModel, TViewModel> viewModelFactory)
: base(source.Select(model => viewModelFactory(model)))
{
Contract.Requires(source != null);
Contract.Requires(viewModelFactory != null);
this._source = source;
this._viewModelFactory = viewModelFactory;
this._source.CollectionChanged += OnSourceCollectionChanged;
}
protected virtual TViewModel CreateViewModel(TModel model)
{
return _viewModelFactory(model);
}
private void OnSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
for (int i = 0; i < e.NewItems.Count; i++)
{
this.Insert(e.NewStartingIndex + i, CreateViewModel((TModel)e.NewItems[i]));
}
break;
case NotifyCollectionChangedAction.Move:
if (e.OldItems.Count == 1)
{
this.Move(e.OldStartingIndex, e.NewStartingIndex);
}
else
{
List<TViewModel> items = this.Skip(e.OldStartingIndex).Take(e.OldItems.Count).ToList();
for (int i = 0; i < e.OldItems.Count; i++)
this.RemoveAt(e.OldStartingIndex);
for (int i = 0; i < items.Count; i++)
this.Insert(e.NewStartingIndex + i, items[i]);
}
break;
case NotifyCollectionChangedAction.Remove:
for (int i = 0; i < e.OldItems.Count; i++)
this.RemoveAt(e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Replace:
// remove
for (int i = 0; i < e.OldItems.Count; i++)
this.RemoveAt(e.OldStartingIndex);
// add
goto case NotifyCollectionChangedAction.Add;
case NotifyCollectionChangedAction.Reset:
Clear();
for (int i = 0; i < e.NewItems.Count; i++)
this.Add(CreateViewModel((TModel)e.NewItems[i]));
break;
default:
break;
}
}
}
}
A: Well first of all, I don't think there is a single "right way" to do this. It depends entirely on your application. There are more correct ways and less correct ways.
That much being said, I am wondering why you would need to keep these collections "in sync." What scenario are you considering that would make them go out of sync? If you look at the sample code from Josh Smith's MSDN article on M-V-VM, you will see that the majority of the time, the Models are kept in sync with the ViewModels simply because every time a Model is created, a ViewModel is also created. Like this:
void CreateNewCustomer()
{
Customer newCustomer = Customer.CreateNewCustomer();
CustomerViewModel workspace = new CustomerViewModel(newCustomer, _customerRepository);
this.Workspaces.Add(workspace);
this.SetActiveWorkspace(workspace);
}
I am wondering, what prevents you from creating an AppleModelView every time you create an Apple? That seems to me to be the easiest way of keeping these collections "in sync," unless I have misunderstood your question.
A: You can find an example (and explanations) here too : http://blog.lexique-du-net.com/index.php?post/2010/03/02/M-V-VM-How-to-keep-collections-of-ViewModel-and-Model-in-sync
Hope this help
A: I may not exactly understand your requirements however the way I have handled a similar situation is to use CollectionChanged event on the ObservableCollection and simply create/destroy the view models as required.
void OnApplesCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// Only add/remove items if already populated.
if (!IsPopulated)
return;
Apple apple;
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
apple = e.NewItems[0] as Apple;
if (apple != null)
AddViewModel(asset);
break;
case NotifyCollectionChangedAction.Remove:
apple = e.OldItems[0] as Apple;
if (apple != null)
RemoveViewModel(apple);
break;
}
}
There can be some performance issues when you add/remove a lot of items in a ListView.
We have solved this by: Extending the ObservableCollection to have an AddRange, RemoveRange, BinaryInsert methods and adding events that notify others the collection is being changed. Together with an extended CollectionViewSource that temporary disconnects the source when the collection is changed it works nicely.
HTH,
Dennis
A: The «Using MVVM to provide undo/redo. Part 2: Viewmodelling lists» article provides the MirrorCollection<V, D> class to achieve the view-model and model collections synchronization.
Additional references
*
*Original link (currently, it is not available): Notify Changed » Blog Archive » Using MVVM to provide undo/redo. Part 2: Viewmodelling lists.
A: OK I have a nerd crush on this answer so I had to share this abstract factory I added to it to support my ctor injection.
using System;
using System.Collections.ObjectModel;
namespace MVVM
{
public class ObservableVMCollectionFactory<TModel, TViewModel>
: IVMCollectionFactory<TModel, TViewModel>
where TModel : class
where TViewModel : class
{
private readonly IVMFactory<TModel, TViewModel> _factory;
public ObservableVMCollectionFactory( IVMFactory<TModel, TViewModel> factory )
{
this._factory = factory.CheckForNull();
}
public ObservableCollection<TViewModel> CreateVMCollectionFrom( ObservableCollection<TModel> models )
{
Func<TModel, TViewModel> viewModelCreator = model => this._factory.CreateVMFrom(model);
return new ObservableVMCollection<TViewModel, TModel>(models, viewModelCreator);
}
}
}
Which builds off of this:
using System.Collections.ObjectModel;
namespace MVVM
{
public interface IVMCollectionFactory<TModel, TViewModel>
where TModel : class
where TViewModel : class
{
ObservableCollection<TViewModel> CreateVMCollectionFrom( ObservableCollection<TModel> models );
}
}
And this:
namespace MVVM
{
public interface IVMFactory<TModel, TViewModel>
{
TViewModel CreateVMFrom( TModel model );
}
}
And here is the null checker for completeness:
namespace System
{
public static class Exceptions
{
/// <summary>
/// Checks for null.
/// </summary>
/// <param name="thing">The thing.</param>
/// <param name="message">The message.</param>
public static T CheckForNull<T>( this T thing, string message )
{
if ( thing == null ) throw new NullReferenceException(message);
return thing;
}
/// <summary>
/// Checks for null.
/// </summary>
/// <param name="thing">The thing.</param>
public static T CheckForNull<T>( this T thing )
{
if ( thing == null ) throw new NullReferenceException();
return thing;
}
}
}
A: While Sam Harwell's solution is pretty good already, it is subject to two problems:
*
*The event handler that is registered here this._source.CollectionChanged += OnSourceCollectionChanged is never unregistered, i.e. a this._source.CollectionChanged -= OnSourceCollectionChanged is missing.
*If event handlers are ever attached to events of view models generated by the viewModelFactory, there is no way of knowing when these event handlers may be detached again. (Or generally speaking: You cannot prepare the generated view models for "destruction".)
Therefore I propose a solution that fixes both (short) shortcomings of Sam Harwell's approach:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;
namespace Helpers
{
public class ObservableViewModelCollection<TViewModel, TModel> : ObservableCollection<TViewModel>
{
private readonly Func<TModel, TViewModel> _viewModelFactory;
private readonly Action<TViewModel> _viewModelRemoveHandler;
private ObservableCollection<TModel> _source;
public ObservableViewModelCollection(Func<TModel, TViewModel> viewModelFactory, Action<TViewModel> viewModelRemoveHandler = null)
{
Contract.Requires(viewModelFactory != null);
_viewModelFactory = viewModelFactory;
_viewModelRemoveHandler = viewModelRemoveHandler;
}
public ObservableCollection<TModel> Source
{
get { return _source; }
set
{
if (_source == value)
return;
this.ClearWithHandling();
if (_source != null)
_source.CollectionChanged -= OnSourceCollectionChanged;
_source = value;
if (_source != null)
{
foreach (var model in _source)
{
this.Add(CreateViewModel(model));
}
_source.CollectionChanged += OnSourceCollectionChanged;
}
}
}
private void OnSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
for (int i = 0; i < e.NewItems.Count; i++)
{
this.Insert(e.NewStartingIndex + i, CreateViewModel((TModel)e.NewItems[i]));
}
break;
case NotifyCollectionChangedAction.Move:
if (e.OldItems.Count == 1)
{
this.Move(e.OldStartingIndex, e.NewStartingIndex);
}
else
{
List<TViewModel> items = this.Skip(e.OldStartingIndex).Take(e.OldItems.Count).ToList();
for (int i = 0; i < e.OldItems.Count; i++)
this.RemoveAt(e.OldStartingIndex);
for (int i = 0; i < items.Count; i++)
this.Insert(e.NewStartingIndex + i, items[i]);
}
break;
case NotifyCollectionChangedAction.Remove:
for (int i = 0; i < e.OldItems.Count; i++)
this.RemoveAtWithHandling(e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Replace:
// remove
for (int i = 0; i < e.OldItems.Count; i++)
this.RemoveAtWithHandling(e.OldStartingIndex);
// add
goto case NotifyCollectionChangedAction.Add;
case NotifyCollectionChangedAction.Reset:
this.ClearWithHandling();
if (e.NewItems == null)
break;
for (int i = 0; i < e.NewItems.Count; i++)
this.Add(CreateViewModel((TModel)e.NewItems[i]));
break;
default:
break;
}
}
private void RemoveAtWithHandling(int index)
{
_viewModelRemoveHandler?.Invoke(this[index]);
this.RemoveAt(index);
}
private void ClearWithHandling()
{
if (_viewModelRemoveHandler != null)
{
foreach (var item in this)
{
_viewModelRemoveHandler(item);
}
}
this.Clear();
}
private TViewModel CreateViewModel(TModel model)
{
return _viewModelFactory(model);
}
}
}
To deal with the first of the two problems, you can simply set Source to null in order to get rid of the CollectionChanged event handler.
To deal with the second of the two problems, you can simply add a viewModelRemoveHandler that allows to to "prepare your object for destruction", e.g. by removing any event handlers attached to it.
A: I've written some helper classes for wrapping observable collections of business objects in their View Model counterparts here
A: I really like 280Z28's solution. Just one remark. Is it necessary to do the loops for each NotifyCollectionChangedAction? I know that the docs for the actions state "one or more items" but since ObservableCollection itself does not support adding or removing ranges, this can never happen I would think.
A: Resetting an collection to a default value or to match a target value is something i've hit quite frequently
i Wrote a small helper class of Miscilanious methods that includes
public static class Misc
{
public static void SyncCollection<TCol,TEnum>(ICollection<TCol> collection,IEnumerable<TEnum> source, Func<TCol,TEnum,bool> comparer, Func<TEnum, TCol> converter )
{
var missing = collection.Where(c => !source.Any(s => comparer(c, s))).ToArray();
var added = source.Where(s => !collection.Any(c => comparer(c, s))).ToArray();
foreach (var item in missing)
{
collection.Remove(item);
}
foreach (var item in added)
{
collection.Add(converter(item));
}
}
public static void SyncCollection<T>(ICollection<T> collection, IEnumerable<T> source, EqualityComparer<T> comparer)
{
var missing = collection.Where(c=>!source.Any(s=>comparer.Equals(c,s))).ToArray();
var added = source.Where(s => !collection.Any(c => comparer.Equals(c, s))).ToArray();
foreach (var item in missing)
{
collection.Remove(item);
}
foreach (var item in added)
{
collection.Add(item);
}
}
public static void SyncCollection<T>(ICollection<T> collection, IEnumerable<T> source)
{
SyncCollection(collection,source, EqualityComparer<T>.Default);
}
}
which covers most of my needs
the first would probably be most applicable as your also converting types
note: this only Syncs the elements in the collection not the values inside them
A: This is a slight variation on Sam Harwell's answer, implementing IReadOnlyCollection<> and INotifyCollectionChanged instead of inheriting from ObservableCollection<> directly. This prevents consumers from modifying the collection, which wouldn't generally be desired in this scenario.
This implementation also uses CollectionChangedEventManager to attach the event handler to the source collection to avoid a memory leak if the source collection is not disposed at the same time as the mirrored collection.
/// <summary>
/// A collection that mirrors an <see cref="ObservableCollection{T}"/> source collection
/// with a transform function to create it's own elements.
/// </summary>
/// <typeparam name="TSource">The type of elements in the source collection.</typeparam>
/// <typeparam name="TDest">The type of elements in this collection.</typeparam>
public class MappedObservableCollection<TSource, TDest>
: IReadOnlyCollection<TDest>, INotifyCollectionChanged
{
/// <inheritdoc/>
public int Count => _mappedCollection.Count;
/// <inheritdoc/>
public event NotifyCollectionChangedEventHandler CollectionChanged {
add { _mappedCollection.CollectionChanged += value; }
remove { _mappedCollection.CollectionChanged -= value; }
}
private readonly Func<TSource, TDest> _elementMapper;
private readonly ObservableCollection<TDest> _mappedCollection;
/// <summary>
/// Initializes a new instance of the <see cref="MappedObservableCollection{TSource, TDest}"/> class.
/// </summary>
/// <param name="sourceCollection">The source collection whose elements should be mapped into this collection.</param>
/// <param name="elementMapper">Function to map elements from the source collection to this collection.</param>
public MappedObservableCollection(ObservableCollection<TSource> sourceCollection, Func<TSource, TDest> elementMapper)
{
if (sourceCollection == null) throw new ArgumentNullException(nameof(sourceCollection));
_mappedCollection = new ObservableCollection<TDest>(sourceCollection.Select(elementMapper));
_elementMapper = elementMapper ?? throw new ArgumentNullException(nameof(elementMapper));
// Update the mapped collection whenever the source collection changes
// NOTE: Use the weak event pattern here to avoid a memory leak
// See: https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/weak-event-patterns
CollectionChangedEventManager.AddHandler(sourceCollection, OnSourceCollectionChanged);
}
/// <inheritdoc/>
IEnumerator<TDest> IEnumerable<TDest>.GetEnumerator()
=> _mappedCollection.GetEnumerator();
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator()
=> _mappedCollection.GetEnumerator();
/// <summary>
/// Mirror a change event in the source collection into the internal mapped collection.
/// </summary>
private void OnSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
InsertItems(e.NewItems, e.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Remove:
RemoveItems(e.OldItems, e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Replace:
RemoveItems(e.OldItems, e.OldStartingIndex);
InsertItems(e.NewItems, e.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Reset:
_mappedCollection.Clear();
InsertItems(e.NewItems, 0);
break;
case NotifyCollectionChangedAction.Move:
if (e.OldItems.Count == 1) {
_mappedCollection.Move(e.OldStartingIndex, e.NewStartingIndex);
} else {
RemoveItems(e.OldItems, e.OldStartingIndex);
var movedItems = _mappedCollection.Skip(e.OldStartingIndex).Take(e.OldItems.Count).GetEnumerator();
for (int i = 0; i < e.OldItems.Count; i++) {
_mappedCollection.Insert(e.NewStartingIndex + i, movedItems.Current);
movedItems.MoveNext();
}
}
break;
}
}
private void InsertItems(IList newItems, int newStartingIndex)
{
for (int i = 0; i < newItems.Count; i++)
_mappedCollection.Insert(newStartingIndex + i, _elementMapper((TSource)newItems[i]));
}
private void RemoveItems(IList oldItems, int oldStartingIndex)
{
for (int i = 0; i < oldItems.Count; i++)
_mappedCollection.RemoveAt(oldStartingIndex);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1256793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
} |
Q: ui-grid columnDefs error I have a general purpose angular controller, which displays a grid view of data. I use it in multiple places of the page by providing different data.
I want to customize the column definition in html using ng-init like this:
<div ng-controller="DataTableController" ng-init="setColDefs([{field:'c_partno', displayName:'Part No',width:'60px'}, {field:'c_owner',displayName:'Owner',width:'60px'}])">
<div ui-grid="gridOptions" class="data-table"></div>
</div>
However, I get
Error: Cannot parse column width '60px' for column named 'c_partno'.
Very appreciated if anyone can help.
A: You should write width: 60 instead of width: '60px'
you can check this on the Documentation, hope it helps.
https://github.com/angular-ui/ui-grid/wiki/Defining-columns
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34796280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I want to display a picture
function rpsGame() {
var textAnswer = document.createTextNode('You chose a paper');
document.getElementById('this').appendChild("textAnswer");
}
<img id="paper" src="./paper.jpg" height=150 width=150 onclick="rpsGame()"></div>
<div class="answer">
<div id="this"></div>
</div>
</div>
The error I get is:
Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
I want it to show the text on the div called this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64260045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does chrome sometimes fail to redraw the page when I expand the browser window? I'm currently working on a responsive design site prototype. So far so good, but for one really strange thing which I can only seem to reproduce in Chrome. When expanding the window, sometimes the browser seems to get trapped between states, showing duplicate elements, and two scrollbars - that is, until I click somewhere outside of the browser window, then everything gets redrawn and looks just fine.
Screenshot:
I've tried a plethora of "tricks" to get chrome to "re-jig" the interface programmatically, such as changing the padding of the body element, modifying the scrollY position, and about 10 or so others, but nothing seems to do the trick. Does anyone have any experience with this? Any advice?
A: This looks like a bug in Chrome.
I searched Chromium bugs and found a few that are similar:
*
*Issue 516127: Rendering artifacts on osx when something moves above the browser (dock, other windows, etc)
*Issue 473933: Visual rendering issue
*Issue 476909: Page didn't redraw correctly
*Issue 245946: Content isn't layout correctly when resizing window
But actually none of them seems to describe your problem exactly. If you think so too, you can report your bug here.
Note that this might be as well an issue related to your old Mac OS version or even the graphics card.
A: Try adding this just after <head> tag
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
A: I had the same problem using cordova (hybrid html5/css3 mobile platform), when rotating the device the internal browser did not refresh correctly. I had a div containing everything with a fixed position. After some tries, I used style width/height: 100% and when rotating the browser refreshed correctly.
A: I second the suggestion to check plugins installed in case there's a conflict.
Looking on Google's forums, the issue has arisen before and was scheduled for a bugfix. Noticed while reading there that they also removed the support for browser window resizing via javascript :/
A: I'm guessing you have a retina display Mac and another external display connected? I see this sometimes on my setup and have tentatively narrowed it down to this situation. When using just the native screen I never see it and not in all screen configurations either.
Try and see if it happens when you use only the built in screen. If that works try switching which screen is the main screen or switch to another external screen altogether.
Sorry for the no fix, but maybe it will get you closer to a solution in your setup at least.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11633023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Read JSON data in JavaScript I Have method in my controller which returns json data.
public JsonResult Data()
{
return Json(model, JsonRequestBehavior.AllowGet);
}
Now how do i read and store above returned data using jQuery? I am trying belwo
$("#btn").click(function () {
$.getJSON("Controller/Data", function(result) {
alert(result.Name + " ");
});
});
Data returned
It returns multiple list,which has multiple items
eg : [0] {MyList} and then it has Name,Region etc
[1] {MyList} and then it has Name,Region etc
A: From the look of your returned JSON, you are returning an array of objects. To access these you can use the index of the object within the array. For example:
$.getJSON("Controller/Data", function(result) {
console.log(result[0].Name);
});
Alternatively, you can loop through all the returned items:
$.getJSON("Controller/Data", function(result) {
for (var i = 0; i < result.length; i++) {
console.log(result[i].Name);
}
});
A: Try this:
$.ajax({
cache: false,
type: "POST",
data: {},
async: true,
url: "/Controller/Data/",
datatype: "json",
success: function (data) {
$.each(data, function (key, data) {
alert(data.Name);
alert(data.Region);
});
}
});
A: you could do
$.getJSON("Controller/Data", function(result) {
console.log('result');
$.each(result, function(key,value) {
console.log(value.name);
// all other computations
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30570421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Class name is marked as 'not covered' while running code coverage in Android Studio I have tried AndroidStudio's code coverage feature and I have met a strange issue:
It is marks the tested class's name as 'not covered' code.
How is that possible? Is that a bug?
Picture here:
As you can see it has one method with 4 lines and each one of them is covered. So why is the red line at the class's name?
A: You are using a static method, so the class itself is never created as an object, therefore never testing that ability.
A: I tried the lombok @UtilityClass, it helped to ignore the class name and code coverage was improved to be 100%.
A: Since also a class with a static function has a default no-argument constructor, your code coverage tool will complain. A good way to solve this, is by adding a private constructor.
private EmailValidator() {
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42348077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Post a Facebook Story as map with C# is not working I am trying to post a Facebook story with a map attachement. I can post the story successfully, but the attachement is not shown as map.
I am using the Facebook C# SDK (http://facebooksdk.net/).
This is how I set up the story:
The custom object is set up with a custom property called geolocation, on which i reffer in the attachement configuration of my story:
And this is how I set the parameters for the FB post call:
parameters["location"] = new Dictionary<string, object>();
((Dictionary<string, object>)parameters["location"])["title"] = "Title";
((Dictionary<string, object>)parameters["location"])["geolocation:latitude"] = pokk.Location.Latitude.ToString(CultureInfo.InvariantCulture);
((Dictionary<string, object>)parameters["location"])["geolocation:longitude"] = pokk.Location.Longitude.ToString(CultureInfo.InvariantCulture);
The story is posted successfully, but this is how it looks like:
I hope you can help me..
Thanx in advance!
Greets!
A: I have spent the last couple hours trying to diagnose this issue and came up with a solution however the code changes quite abit. Basically the first thing you can do is actually set the property "location" to be required. You will notice that once you set it as required that the Graph API is failing due to a required property missing.
This is a good sign, it means that something is not quite right with the submission. After digging around and manually creating objects in the Object Browser I came up with a solution. Now it is worth noting that I am using dnyamic ExpandoObjects instead of dictionaries but the concept is the same. Review the commented code
//create our location object
dynamic locationData = new ExpandoObject();
locationData.title = "sample app testing " + DateTime.Now.ToString();
//create our geolocation object
dynamic geoData = new ExpandoObject();
geoData.latitude = 37.416382;
geoData.longitude = -122.152659;
geoData.altitude = 42; //<-- important altitude figure
//create our geo data item container and add the geoData object to the geolocation property
dynamic geoDataItem = new ExpandoObject();
geoDataItem.geolocation = geoData;
//set the data property of our location data to the geo data item container
locationData.data = geoDataItem;
//create our root object setting the location property to the location data object
dynamic objItem = new ExpandoObject();
objItem.location = locationData;
var response = context.Client.Post("me/<my_app_name>:<app_action>", objItem);
Really all we are doing is creating a simple structure using the expando object. Where I personally got stuck what not understanding how the complete GeoPoint operates. If you notice we have to create 2 containers.
One container so we can set the geolocation property on the data property of the location object.
The final structure resembles
--- MyStory
--- location
--- title : 'Sample app testing....'
--- data
--- geolocation
--- latitude : 37.416...
--- longitude : -122.1526...
--- altitude : 42
This does seem rather complex but here is a final output preview.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21140975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: custom taxonomy sort order not working I have created a custom taxonomy named product_categories.
It has three fields :
*
*for banner image
*for category image and
*for sort order.
I have added 10 categories in it giving its sort order input also.
Now i want to show this in sorting order but it is not working.
In pt-categories input for sort order is this
<tr class="form-field">
<th scope="row" valign="top"><label for="cat_sort_order"><?php _e('Product Sort Order'); ?></label></th>
<td>
<input id="banner-url" name="term_meta[sort_order]" type="text" style="width: 100%;" value="<?php echo $term_meta['sort_order'] ? $term_meta['sort_order'] : ''; ?>" />
<span class="description"><?php _e(' '); ?></span>
</td>
Saving funtion is this
function save_product_categories_custom_fields($term_id)
{
if (isset($_POST['term_meta'])) {
$t_id = $term_id;
$term_meta = get_option("taxonomy_term_$t_id");
$cat_keys = array_keys($_POST['term_meta']);
foreach ($cat_keys as $key) {
if (isset($_POST['term_meta'][$key])) {
$term_meta[$key] = $_POST['term_meta'][$key];
}
}
//save the option array
update_option("taxonomy_term_$t_id", $term_meta);
}
}
Here is the categories called
function getLatestProducts() {
$args = array(
'post_status' => 'publish',
'post_type' => 'products',
'posts_per_page' => 12,
'meta_key' => '_cus_sort_order',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
?>
<?php
$args = array(
'orderby' => 'name',
);
$terms = get_terms('product_categories', $args);
foreach($terms as $term) {
$prod_meta = get_option("taxonomy_term_".$term->term_id);
?>
<a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
<?php
echo '<img src="'.$prod_meta['img'].'" title="" alt=""></a>'; ?>
</div>
<div class="product-name">
<h5>
<a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
<?php echo $term->name;?>
</a>
</h5>
It is showing the categories names and images but not in sorted order.
A: You have a mistake in your code of Categories Called
Corrected Code
function getLatestProducts() {
$args = array(
'post_status' => 'publish',
'post_type' => 'products',
'posts_per_page' => 12,
'meta_key' => '_cus_sort_order',
'orderby' => 'meta_value_num, name',
'order' => 'ASC'
);
$terms = get_terms('product_categories', $args);
foreach($terms as $term) {
$prod_meta = get_option("taxonomy_term_".$term->term_id);
?>
<a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
<?php
echo '<img src="'.$prod_meta['img'].'" title="" alt=""></a>'; ?>
</div>
<div class="product-name">
<h5>
<a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
<?php echo $term->name;?>
</a>
</h5>
I have removed an array of argument which is called after main arguments array. As the below mentioned argument array is overriding the above mentioned arguments array.
Removed Arguments Array
$args = array(
'orderby' => 'name',
);
Hope this helps!
A: Extending on Mehul's answer, your saving function has also some mistakes.
Have you checked previously saved sort orders of your categories ?
"taxonomy_term_$t_id" should be "taxonomy_term_" . $t_id . Otherwise you are saving everything as taxonomy_term_$t_id option and not with a dynamic term id.
function save_product_categories_custom_fields($term_id)
{
if (isset($_POST['term_meta'])) {
$t_id = $term_id;
$term_meta = get_option("taxonomy_term_" . $t_id);
$cat_keys = array_keys($_POST['term_meta']);
foreach ($cat_keys as $key) {
if (isset($_POST['term_meta'][$key])) {
$term_meta[$key] = $_POST['term_meta'][$key];
}
}
//save the option array
update_option("taxonomy_term_" . $t_id, $term_meta);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36277018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Optimize Animation.Sample I'm trying to optimize the animation. As I see in profiler, about 20% of my CPU used for 'Animation.Sample'. Is there any way to reduce the sampling accuracy to gain performance.
A: Unless you want to write your own animation system for Unity, which would be probably slower due to Unity's optimizations. You can't do anything about it except tweaking the animation yourself.
*
*Use fewer bones
*Remove redundant curves
*Ensure that any bones that have colliders attached also have rigidbodies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26249029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Print result if statement to exec is an expression In python, if I exec a statement which prints a value, I will see the output, e.g., exec("print 10") gives me output 10. However, if I do exec("10") I got nothing as output, where as if I type 10 in the interactive shell I got 10 as output. How do I get this output when using exec? That is if the statement to be executed is an expression, I print its result.
My question is how I can decide whether the statement to execute is an expression. Am I supposed to do the following:
def my_exec(script):
try:
print eval(compile(script, '<string>', 'eval'))
except SyntaxError:
exec(script)
# Prints 10.
my_exec("print(10)")
# Prints 10 as well.
my_exec("10")
UPDATE:
Basically I want the behavior of executing a cell in a jupyter notebook.
A: First of all, executing 10 doesn't make sense in real life. How can you execute a number? But, you can execute a command like exec("print(10)"). I don't see the need of creating a my_exec function. It behaves the same as the normal exec. In the interactive shell, everything works differently, so don't try to compare. Basically, exec("print(10)") is the command you are looking for. Another way not using exec is print(10).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42684108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wix Bootstrap prevent temp directory use I have builded "HelloWord" installer with the Bootstrapper Project for Wix v3 project type.
My bundle.wxs is
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"
xmlns:bal="http://schemas.microsoft.com/wix/BalExtension">
<Bundle Name="Bundle_name"
Version="1.0.0.0"
Manufacturer="Producter"
UpgradeCode="C82A383C-751A-43B8-90BF-A250F7BC2863"
IconSourceFile="..\WpfForms\Assets\my_lovely.ico" >
<BootstrapperApplicationRef Id="ManagedBootstrapperApplicationHost">
<Payload SourceFile="..\WpfForms\BootstrapperCore.config"/>
<Payload SourceFile="..\WpfForms\bin\Debug\WpfForms.dll"/>
<Payload SourceFile="..\WpfForms\bin\Debug\GalaSoft.MvvmLight.dll"/>
<!--<Payload SourceFile="..\WpfForms\bin\Debug\Microsoft.Practices.ServiceLocation.dll"/>
<Payload SourceFile="..\WpfForms\bin\Debug\Microsoft.WindowsAPICodePack.dll"/>
<Payload SourceFile="..\WpfForms\bin\Debug\Microsoft.WindowsAPICodePack.Shell.dll"/>-->
<Payload SourceFile="C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.ServiceProcess.dll"/>
<Payload SourceFile="C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Configuration.Install.dll"/>
<Payload SourceFile="C:\Program Files (x86)\WiX Toolset v3.11\SDK\Microsoft.Deployment.WindowsInstaller.dll"/>
</BootstrapperApplicationRef>
<Chain>
<PackageGroupRef Id='Netfx4Full'/>
<MsiPackage SourceFile="..\WixSetupProject\bin\Debug\WixSetupProject.msi" Id="InstallationPackageId" Cache="yes" Visible="no"/>
</Chain>
</Bundle>
<Fragment>
<WixVariable Id="WixMbaPrereqPackageId" Value="Netfx4Full" />
<WixVariable Id="WixMbaPrereqLicenseUrl" Value="NetfxLicense.rtf" />
<util:RegistrySearch Root="HKLM" Key="SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full" Value="Version" Variable="Netfx4FullVersion" />
<util:RegistrySearch Root="HKLM" Key="SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full" Value="Version" Variable="Netfx4x64FullVersion" Win64="yes" />
<PackageGroup Id="Netfx4Full">
<ExePackage Id="Netfx4Full" Cache="no" Compressed="yes" PerMachine="yes" Permanent="yes" Vital="yes" Name="DotNet_4"
SourceFile="../WixBootstrapper/DotNet/NDP462-KB3151800-x86-x64-AllOS-ENU.exe"
DownloadUrl="http://go.microsoft.com/fwlink/?LinkId=164193"
DetectCondition="Netfx4FullVersion AND (NOT VersionNT64 OR Netfx4x64FullVersion)" />
</PackageGroup>
</Fragment>
</Wix>
My problem is that the work station's antivirus configured to block any activity from temp directories and the builded installer.exe make copy of itself as "C:\Windows\Temp{74EA5B2A-DA46-4B3F-A8E9-4FCEC4B4523C}.cr\WixBootstrapper.exe" and run it by default. So it get locked by antivirus so instalation is over on start.
Do somebody know how can i prevent WiX components from create a cache or something in temp directories and set to run any nested executable and themselfs from the curent folder, not from the temp?
A:
After checking Windows's group policy settings this turned out to be
an anti-virus blocking problem.
Group Policy?: Does the log contain something like this:
Error 0x800704ec: Failed to launch clean room process: "C:\WINDOWS\Temp\{AB10C981-0D7D-4AA6-857F-CC37696DB4BE}\.cr\Bundle.exe" -burn.clean.room="C:\Test\Bundle.exe" -burn.filehandle.attached=652 -burn.filehandle.self=656 -log "C:\Test\bundle.log"
Error 0x800704ec: Failed to run untrusted mode.
Or does it say something else? There is a group policy that can cause similar issues. See WiX issue 5856.
Anti-Virus Grace Period?: If you are administrator, there should be a possiblity to get a temporary grace period from your anti virus I would think. So you can perform your testing. I would give your own support desk a call first and then hit the Kaspersky user forums if unsuccessful. Perhaps you have a Kaspersky support agreement with priority support available?
False Positives: I also insist that you upload your binaries to virustotal.com to test for false positives. That you should do no matter what. Antivirus Whitelisting Pains by Bogdan Mitrache.
False positives can actually be worse than actual malware at times (so far as the malware isn't devastating)
because you cannot just tell the user to rebuild their machine(s). Instead you actually have
to fix the problem for them in a general sense. Not only does the user have a problem to fix, you have one as the vendor as well. How do you whitelist your product with 60+ anti-malware suites? You try virustotal.com first I think (not affiliated) - to check if you actually have such a problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52977390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sequelize: can attribute have value from relation attribute data? i don't know if this is possible, there are 2 models which are associated through relation, and models are defined this way:
sequelize.define('account_has_plan', {
account_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
references: {
model: 'account',
key: 'id'
}
},
plan_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
references: {
model: 'plan',
key: 'id'
}
},
type_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
references: {
model: 'type',
key: 'id'
}
},
create_at: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: 'CURRENT_TIMESTAMP'
},
update_at: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: 'CURRENT_TIMESTAMP'
}
}, {
tableName: 'account_has_plan',
underscored: true,
freezeTableName: true,
timestamps: false
});
sequelize.define('type', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
element: {
type: DataTypes.ENUM('Meal','Workout','Status'),
allowNull: false
}
}, {
tableName: 'type',
freezeTableName: true,
timestamps: false
});
the code on which calls the models and execute the query to DB is this:
var model = $.loadModel("account_has_plan");
var type = $.loadModel("type");
model.belongsTo(type);
var query = {
where: {
account_id: $.params.accountId
},
limit: $.query.limit || 12,
offset: $.query.offset || 0,
attributes:["account_id"],
include: [{
model: type
}]
};
model.findAll(query)
.then(function(data){
$.data = data;
$.json();
})
.catch(function(err){
console.log(err);
errorHandler.throwStatus(500, $);
});
this way the data from the server responds like this:
{
"account_id": 1,
"type": {
"id": 2,
"name": "Arms",
"element": "Workout"
}
}
there is actually no problem with this data, but i am forced to follow a pattern from docs i was provided with, which the difference there is that type is actually a string value rather than object value as presented in the example, so in the end the data structure i try to get has to be like this:
{
"account_id": 1,
"type": "Arms"
}
i have actually how idea on how to achieve this, i know i have little practice with sequelize, maybe this has to be defined through a model method or using through in the reference (which i have tried but returns error)
but the point is.. i need to know if it can be possible before i have to report a change on the REST documentation which is big
A: First of all, since what you'll be getting through a sequelize query are instances, you need to convert it to "plain" object. You could do that by using a module called sequelize-values.
Then you should be able to manually map the value to the one you're looking for.
model.findAll(query)
.then(function(data){
return data.map(function(d){
var rawValue = d.getValues();
rawValue.type = rawValue.type.name;
return rawValue;
});
})
.then(function(data){
$.data = data;
$.json();
})
.catch(function(err){
console.log(err);
errorHandler.throwStatus(500, $);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37369931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: handle null from database I need to round and print a price like below, but this does not handle null values.
How can I handle null values on one line of code?
DBRSet is an SQLDataReader and the price is money type in SQL.
<%= Math.Round(DBRSet("price"))%>
I have about 200 .aspx pages of this so I could also use some tips on how to change these in an easy way? Can I do a search and replace with a reg-exp or something like that?
A: You have to handle the DbNull case explicitly, for example:
<%= DbNull.Equals(DBRSet["price"]) ? "null" : Math.Round(DBRSet["price"]).ToString() %>
This is unwieldy, so it makes sense to have a helper method something like this somewhere:
static class FormatDbValue {
public static string Money(object value)
{
if (DbNull.Equals(value)) {
return "0";
}
return Math.Round((decimal)value);
}
}
Which would allow
<%= FormatDbValue.Money(DBRSet["price"]) %>
Of course finding and changing all such code to use the helper method would be... unpleasant. I would do it by searching throughout the project (maybe in smaller chunks of the project) for something indicative (maybe Math.Round?) and review it manually before replacing.
A: If you don't want to change the aspx's, but can easily change the definition of the DBRSet property, you can put there a wrapper over the SqlDataReader and implement your own indexer that would first check for null and go into the inner dataReader to get the value if not null.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5486185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to collect a List to a Map> using Java lambdas? I have an object Foo that has references to Bar and Baz objects:
public class Foo {
private Bar bar;
private Baz baz;
public Foo(Bar bar, Baz baz) {
this.bar = bar;
this.baz = baz;
}
}
I have a List<Foo> that I'd like to convert into a Map. I'd like the key to be Bar and the value to be a List<Baz>.
I can create a Map where Bar is the key and the value is a List<Foo>:
Map<Bar, List<Foo>> mapBarToFoos = foos.stream().collect(Collectors.groupingBy(Foo::getBar));
I don't know how to take that last step and turn the value List into a List<Baz>. Is there a lambda conversion on the value that I'm not seeing?
A: I think you want
list.stream().collect(groupingBy(Foo::getBar,
mapping(Foo::getBaz, toList())));
Where getBaz is the "downstream collector" which transforms the grouped Foos, then yet another which creates the list.
A: You're close, you'll need to supply a "downstream" collector to further refine your criteria. in this case the groupingBy approach along with a mapping downstream collector is the idiomatic approach i.e.
list.stream().collect(groupingBy(Foo::getBar, mapping(Foo::getBaz, toList())));
This essentially works by applying a mapping downstream collector to the results of the classification (Foo::getBar) function.
basically what we've done is map each Foo object to Baz and puts this into a list.
Just wanted to show another variant here, although not as readable as the groupingBy approach:
foos.stream()
.collect(toMap(Foo::getBar, v -> new ArrayList<>(singletonList(v.getBaz())),
(l, r) -> {l.addAll(r); return l;}));
*
*Foo::getBar is the keyMapper function to extract the map keys.
*v -> new ArrayList<>(singletonList(v)) is the valueMapper
function to extract the map values.
*(l, r) -> {l.addAll(r); return l;} is the merge function used to
combine two lists that happen to have the same getBar value.
A: To change the classic grouping to a Map<Bar, List<Foo>> you need to use the method which allows to change the values of the map :
*
*the version with a downstream Collectors.groupingBy(classifier, downstream)
*which is a mapping operation Collectors.mapping(mapper, downstream)
*which requires another operation to set the container Collectors.toList()
//Use the import to reduce the Collectors. redundancy
//import static java.util.stream.Collectors.*;
Map<Bar, List<Baz>> mapBarToFoos =
foos.stream().collect(groupingBy(Foo::getBar, mapping(Foo::getBaz, toList())));
//without you'll get
Map<Bar, List<Baz>> mapBarToFoos =
foos.stream().collect(Collectors.groupingBy(Foo::getBar, Collectors.mapping(Foo::getBaz, Collectors.toList())));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53732841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to add `alt + mouse left click` as shortcut key in key map of android studio 3.0 (Ubuntu 16.4 LTS) I am trying to add alt + mouse left click as shortcut key in keymap but it only take alt or mouse-click and It takes nothing when try to add both.
Please help to resolve this issue.Below is the screen:
A: You should use not "Keyboard shortcut" but rather "Mouse shortcut" from a popup menu (number 2 at the picture):
https://developer.android.com/studio/images/intro/keymap-options_2-2_2x.png
Also by default on most linux desktop environments alt+mouse click is already assigned to window dragging. OS shortcuts have more priority. If it's the case for you then either use different shortcut in Android Studio or reassign OS shortcut (in this case Unity): https://askubuntu.com/questions/521423/how-can-i-disable-altclick-window-dragging
After that you should be able to use the shortcut in Android Studio
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48060177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Angular CLI: Generate htaccess using base-href With Angular CLI the base href in index.html can be set on build, e.g. ng --base-href /folder/someproject/. This is very useful for automatic deployment processes.
But projects like this may require a .htaccess also setting a base like so: RewriteRule ^(.*) /folder/someproject/index.html [NC,L]
Is it possible (with Webpack?) to set the path within htaccess also by use of base-href?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45420646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Serilogs not working in linux server in aspnet core 2.1 I'm creating dotnet core 2.1 project.I used serilogs.In my windows machine it's working fine.But after hosted it,serilogs not working.Not creating logs folder and log file.I hosted it in ubuntu 18.04 version server.
I tried it by creating logs folder manually and gave it to read write permissions
sudo chmod 775 /var/app/logs
sudo chown www-data /var/app/logs
here is the code in program class
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
.WriteTo.RollingFile(@"logs\log-{Date}.log", fileSizeLimitBytes: null, retainedFileCountLimit: null)
.CreateLogger();
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(builder =>
{
builder.SetMinimumLevel(LogLevel.Warning);
builder.AddFilter("ApiServer", LogLevel.Debug);
builder.AddSerilog();
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>();
}
here is my startup class code
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(s => s.UseMySql(Configuration.GetConnectionString("DefaultConnection"))
.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.AddCors();
services.AddAutoMapper();
services.AddTransient<Seed>();
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddScoped<IDatingRepository, DatingRepository>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddScoped<LogUserActivity>();
IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
{
opt.Password.RequireDigit = false;
opt.Password.RequiredLength = 4;
opt.Password.RequireNonAlphanumeric = false;
opt.Password.RequireUppercase = false;
});
builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
builder.AddEntityFrameworkStores<DataContext>();
builder.AddRoleValidator<RoleValidator<Role>>();
builder.AddRoleManager<RoleManager<Role>>();
builder.AddSignInManager<SignInManager<User>>();
// services.AddAuthorization(options => {
// options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
// options.AddPolicy("SuperAdminPhotoRole", policy => policy.RequireRole("SuperAdmin"));
// });
// services.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seed seeder, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"))
.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message);
}
});
});
// app.UseHsts();
}
// app.UseHttpsRedirection();
seeder.SeedUsers();
// app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseAuthentication();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Fallback", action = "Index" }
);
});
}
}
here is the way I used logs
public class PhotosController : ControllerBase
{
private readonly ILogger<PhotosController> _logger;
public PhotosController(ILogger<PhotosController> logger
)
{
_logger = logger;
}
[HttpPost("{id}/setMain")]
public async Task<IActionResult> SetMainPhoto(Guid id)
{
try
{
_logger.LogDebug("Starting to change main photo");
}
catch(Exception e) {
_logger.LogError("An error occurs while changing photo");
}}}
Please help me to solve this problem.this is working fine in windows machine.Only this happened after hosting
A: In your Program.cs file you need
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().UseSerilog();
the important part is .UseSerilog()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53906470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Modify PDF file uploaded in the request body in nodejs I'm trying to modify a pdf file that I get from the request then saving it in my server, I achieved to save it first as I received it from the request body and then modifying it, and once more saving it again with the modified version, but I was looking for another approach to modify it in the fly directly after receiving it from the request body then saving it only once in the server. I need to add a logo to the uploaded file, thanks in advance
This is my code
'''
const mongoose = require("mongoose");
const path = require("path");
const ErrorResponse = require("../utils/errorResponse");
const fs = require("fs");
// Form submition with photo
exports.uploadPdf = (req, folderPath, next) => {
if (!req.files) {
console.log("No file");
return next(new ErrorResponse("Please Upload a file", 400));
}
const file = req.files.pdf;
const extention = file.name.split(".").at(-1);
if (extention !== "pdf") {
console.log("It's not a valid PDF file");
return next(new ErrorResponse("Please Upload an pdf file", 400));
}
//Check image size
if (file.size > process.env.MAX_FILE_UPLOAD) {
return next(
new ErrorResponse(
`Please Upload an PDF file less than ${process.env.MAX_PDF_FILE_UPLOAD}`,
400
)
);
}
//Create custom filename
let id;
if (!req.params.id) {
id = mongoose.Types.ObjectId();
} else {
id = req.params.id;
}
file.name = `document_${id}${path.parse(file.name).ext}`;
var dir = `${process.env.FILE_UPLOAD_PATH}/${folderPath}`;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
file.mv(
`${process.env.FILE_UPLOAD_PATH}/${folderPath}/${file.name}`,
async (err) => {
if (err) {
console.log(err);
return next(new ErrorResponse(`Problem with file upload`, 500));
}
}
);
req.body = {
_id: id,
...req.body,
pdf: file.name,
};
};
'''
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75393620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to combine basename and filepath into a specialized list - R? I have a folder containing a variety of .img files. I can list all of the files in the folder using the following method:
files = "C:/imagery/Landsat"
rlist=list.files(path = files, pattern="img$", full.names=TRUE)
> rlist
[1] "C:/imagery/Landsat/image1.img"
[2] "C:/imagery/Landsat/image2.img"
[3] "C:/imagery/Landsat/image3.img"
I know how to extract the basename from the file paths, using the following approach:
> strsplit(basename(rlist[1]), '\\.')[[1]][1]
[1] "image1"
However, I am in need of a special list following this format:
rlist2 = list(image1 = "C:/imagery/Landsat/image1.img",
image2 = "C:/imagery/Landsat/image2.img",
image3 = "C:/imagery/Landsat/image3.img")
How should I put these disjointed pieces together to form the specialized list in rlist2?
A: First, you need to assign names to the entries in your vector (each entry will get the corresponding file name), as follows:
> library(tools)
> names(rlist) <- basename(file_path_sans_ext(rlist))
Then, to get a list in the format that you specified, you can simply do:
rlist2 <- as.list(rlist)
This is the output:
> rlist2
$image1
[1] "C:/imagery/Landsat/image1.img"
$image2
[1] "C:/imagery/Landsat/image2.img"
$image3
[1] "C:/imagery/Landsat/image3.img"
And you can access individual entries in the list, as follows:
> rlist2$image1
[1] "C:/imagery/Landsat/image1.img"
You can read more about the as.list function and its behavior here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29303419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I add internet permission to a Winform app in visual studio for windows Hello I am developing a Winform app, but I can't seem to see how to add internet permission to the app. Or does Winform have automatic default internet permission?
A: Any desktop app (including WinForms) has access to the network by default. There is no any permission system for this as for Android or iOS. But if the use has any firewall or other security software installed, he/she may be need to configure this software to allow your app to access network.
So, in your code you does not need perform any additional actions to get internet access.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67137786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: change an ascending sort to descending I have the following code to sort a list but I need to make it a descending sort,
List list = new LinkedList(thismap.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
});
Map output = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
output.put(entry.getKey(), entry.getValue());
}
A: A common, general purpose technique is to wrap a Comparator in a reverse Comparator by simply swapping the arguments.
class ReverseComparator<T> implements Comparator<T> {
private final Comparator target;
public ReverseComparator(Comparator<T> target) {
super();
this.target = target;
}
public int compare(T first, T second) {
return target.compare(second, first);
}
}
To use it with our example:
Comparator original = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
};
Collections.sort(list, new ReverseComparator(original));
A: The simple general answer is to use java.util.Collections.reverseOrder(Comparator).
Comparator myComparator = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
}
// ... or whatever.
Comparator myReverseComparator = Collections.reverseOrder(myComparator);
Alternatively, a specific solution would be to flip the parameters in the compare method:
Comparator myReverseComparator = new Comparator() {
public int compare(Object o2, Object o1) { // <== NOTE - params reversed!!
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
}
Note that multiplying by -1 is an incorrect solution because of the Integer.MIN_VALUE edge case. Integer.MIN_VALUE * -1 is ... Integer.MIN_VALUE
A: It's all about changing the content of the method below:
public int compare(Object o1, Object o2)
{
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
Return a different result than the value of the statement below:
((Comparable)((Map.Entry)(o2)).getValue()).compareTo(((Map.Entry)(o1)).getValue());
Let's say the statement above is assigned to x. Then you should return 1 if x < 0,
return -1 if x > 0 and return 0 if x == 0, just inside the compare() method.
So your method could look like this:
public int compare(Object o1, Object o2)
{
int x = ((Comparable)((Map.Entry)(o2)).getValue())
.compareTo(((Map.Entry)(o1)).getValue());
if(x > 0)
return -1;
else if (x < 0)
return 1;
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12755736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to exclude a jquery event for a popover I am facing an issue where a generic javascript in my appliaction is causing my popover to hide. Below is the generic code.
$(document).on('mouseenter mouseleave', '.popover', function(event) {
if (event.type == 'mouseenter') {
//Code abc
} else if (event.type == 'mouseleave') {
//Code Def
$("div.popover").remove();
}
Can anyone please tell me how to exclude this javascript for my popover?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50976556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.