text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: luajit run error after it use much memory My program embedded luajit. It run well most time. Buf after is uses much memory, it began to run some logic error such as the result of > will be wrong.
How to find and solve the problem?
My program is use lua,it runs well for years. I recently change it to luajit.
My program is built with gcc 4.7 and run on debian 7. The program build with
-DLUAJIT_ENABLE_GC64
tt = {}
for i = 1, 10000000 do
local k = string.format( "1kkkk%d" , i )
local v = string.format( "1vvv%d" , i )
tt[k] = v
end
After the program uses much memory, it'll cause error in the near future. For example,After run the above:
local nNum = 10
assert( nNum > 0 )
the assert will run error. Other code will also run error probably. The error will appear everywhere and every code will probably run error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58603681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to filter elements of an array based on a property inside double nested array Well, i have a complicated issue. at least it is complicated for myself.
So i have an Array which has an Array that has an Array in it.
and i want to filter The very top array based on properties inside the deepest array.
Lets say i have this Array of objects
var garages = [{
"GarageId": 1,
"GarageName": "Garage_001",
"Sections": [{
"SectionId": 1,
"Name": "Section_002",
"Cars": [{
"Id": 5,
"Model": "Bmw"
}, {
"Id": 6,
"Model": "Mercedes"
}]
}, {
"SectionId": 2,
"Name": "Section_003",
"Cars": [{
"Id": 8,
"Model": "Toyota"
}, {
"Id": 6,
"Model": "Mercedes"
}]
}]
},
{
"GarageId": 6,
"GarageName": "Garage_006",
"Sections": [{
"Id": 1,
"Name": "Section_007",
"Cars": [{
"Id": 5,
"Model": "Bmw"
}, {
"Id": 6,
"Model": "Mercedes"
}]
}, {
"Id": 2,
"Name": "Section_003",
"Cars": [{
"Id": 8,
"Model": "Toyota"
}, {
"Id": 6,
"Model": "Mercedes"
}]
}]
}
]
And i want to retrieve a list of garages that contain a Hyundai for example. how can i do it?
i have been trying for hours and this is what i came up with. it may be a stupid piece of code but i just got confused dealing with this much nested Arrays!
So my code is this:
garages: any[] = [];
selectedCarModel: number: 8;
filterOnCarModel(carId) {
this.garages = getGaragesFromServed();
this.selectedCarModel = this.CarModels.find(c => c.Id == id);
let filteredArray = this.garages
.filter((garage) =>
garage.Sections).
filter((section) =>
study.Cars.find((car) => car.Id == carId));
this.garages = filteredArray;
}
Thank you for understanding
A: var filteredGarages = garages.filter(garage =>
garage.Sections.filter(section =>
section.Cars.filter(car => car.Model.indexOf("Bmw")>=0)
.length > 0)
.length > 0)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55629114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to calculate quarterly wise churn and retention rate using python How to calculate quarterly wise churn and retention rate with date column using python. with date column i want to group that quarterly using python.
This is used to calculate the churn count groupby quarterly
quarterly_churn_yes = out.loc[out['Churn'] == 'Yes'].groupby(out["Date"].dt.quarter).count()
print(quarterly_churn_yes["Churn"])
Date
1 1154
2 114
3 68
4 69
Name: Churn, dtype: int64
This is used to calculate the churn rate groupby quarterly
total_churn = out['Churn'].count()
print(total_churn)
quarterly_churn_rate = out.groupby(out["Date"].dt.quarter).apply(lambda x: quarterly_churn_yes["Churn"] / total_churn).sum()
print(quarterly_churn_rate)
Date
1 0.862159
2 0.085170
3 0.050803
4 0.051550
dtype: float64
The above code i have tried to the find churn rate grouped on date column querterly wise. I am getting 1,2,3,4 but i want year wise quarterly churn rate.
For example , if i have four years in the dataframe like 2018,2014,2017 in that
2008
1 1154
2 114
3 68
4 69
2014
1 1154
2 114
3 68
4 69
A: I think need:
out = pd.DataFrame({ 'Date': pd.to_datetime(['2015-01-01','2015-05-01','2015-07-01','2015-10-01','2015-04-01','2015-12-01','2016-01-01','2016-02-01','2015-05-01', '2015-10-01']), 'Churn': ['Yes'] * 8 + ['No'] * 2 })
print (out)
Churn Date
0 Yes 2015-01-01
1 Yes 2015-05-01
2 Yes 2015-07-01
3 Yes 2015-10-01
4 Yes 2015-04-01
5 Yes 2015-12-01
6 Yes 2016-01-01
7 Yes 2016-02-01
8 No 2015-05-01
9 No 2015-10-01
df = (out.loc[out['Churn'] == 'Yes']
.groupby([out["Date"].dt.year,out["Date"].dt.quarter])["Churn"]
.count()
.rename_axis(('year','quarter'))
.reset_index(name='count'))
print(df)
year quarter count
0 2015 1 1
1 2015 2 2
2 2015 3 1
3 2015 4 2
4 2016 1 2
For separate DataFrames by years is possible create dictionary of DataFrames:
dfs = dict(tuple(out.groupby(out['Date'].dt.year)))
print (dfs)
{2016: Churn Date
6 Yes 2016-01-01
7 Yes 2016-02-01, 2015: Churn Date
0 Yes 2015-01-01
1 Yes 2015-05-01
2 Yes 2015-07-01
3 Yes 2015-10-01
4 Yes 2015-04-01
5 Yes 2015-12-01
8 No 2015-05-01
9 No 2015-10-01}
print (dfs.keys())
dict_keys([2016, 2015])
print (dfs[2015])
Churn Date
0 Yes 2015-01-01
1 Yes 2015-05-01
2 Yes 2015-07-01
3 Yes 2015-10-01
4 Yes 2015-04-01
5 Yes 2015-12-01
8 No 2015-05-01
9 No 2015-10-01
Tenure column looks like this
out["tenure"].unique()
Out[14]:
array([ 8, 15, 32, 9, 48, 58, 10, 29, 1, 66, 24, 68, 4, 53, 6, 20, 52,
49, 71, 2, 65, 67, 27, 18, 47, 45, 43, 59, 13, 17, 72, 61, 34, 11,
35, 69, 63, 30, 19, 39, 3, 46, 54, 36, 12, 41, 50, 40, 28, 44, 51,
33, 21, 70, 23, 16, 56, 14, 62, 7, 25, 31, 60, 5, 42, 22, 37, 64,
57, 38, 26, 55])
It contains no of months, it seems like 1 to 72.
I need to split tenure column into "range".
For example, this column contains 1 to 72 numbers, need to range up to 4 range.
like 1 to 18 --> 1 range
19 to 36 --> 2nd range
37 to 54 --> 3rd range like that
here i found quarterlywise churn count and with that churn count later i found churn rate with churn count and total count.
quarterly_churn_yes = out.loc[out['Churn'] == 'Yes'].groupby([out["Date"].dt.year,out["Date"].dt.quarter]).count().rename_axis(('year','quarter'))
quarterly_churn_yes["Churn"]
quarterly_churn_rate = out.groupby(out["Date"].dt.quarter).apply(lambda x: quarterly_churn_yes["Churn"] / total_churn).sum()
print(quarterly_churn_rate)
Like this I need to find tenure wise 4 range to find churn count.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49355891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to make an icon fit into a row element in react-bootstrap I am having a small issue fitting an icon into a Row element.
right now the icon takes up the whole row ::
<LinkedInIcon />
I was able to make it not take up the whole row ::
<div style={{ background: "white", display: "inline-block" }}>
<LinkedInIcon />
</div>
now I have to add some text on the right side of the icon, but its not working out. I added my code to the sandbox::
<Row>
<p className="text-center text-white">Bosky</p>
{/* this icon does not behave properly, it does not allow the text'Bosky' to show in the same row */}
<div style={{ background: "white", display: "inline-block" }}>
<LinkedInIcon />
</div>
</Row>
https://codesandbox.io/s/bosky-active-ow4qs7?file=/src/Components/Footer.js:447-559
A: Maybe like this? It's a lot of style inline, but seem to get the job done...
https://codesandbox.io/s/bosky-active-forked-bcbd35?file=/src/Components/Footer.js
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74777687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get value by xPath knowing only the child of another node - selenium I have some problem. I have a few checkboxes but there are no id or name for tags. Structure looks like this:
I would like to get green value but I only know red value: name=onlyWebsite. But this is different node.
Ofcourse when I do: //input[@name='onlyWebsite']//i this doesn't work.
Could you help me?
A: to go to check from onlyWebsite, you may try the below xpath :
//input[@name='onlyWebsite']/following-sibling::span/descendant::i
if there are multiple span's as a following-sibling, you can try this :
//input[@name='onlyWebsite']/following-sibling::span[1]/descendant::i
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68180806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How move the scroll only when there are the keyboard I used this function to move my scroll, but this function is activated when I don't have a keyboard, I only want to use it when there is a keyboard, how can I solve this?
<Entry Placeholder="entry" Focused="EntryKeyboardHandle_Focused"
void EntryKeyboardHandle_Focused(object sender, FocusEventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
await Task.Delay(10);
await MainScroll.ScrollToAsync(0, 100, true);
});
}
I found this thread Xamarin forms check if keyboard is open or not
I have my entry with name "Entry" and in my code behind Entry.Focused += keyboardService.KeyboardIsShown; but I get this error.
The event 'IKeyboardService.KeyboardIsShown' can only appear on the
left hand side of += or -=
A: ok accourding to the thread that you found you could try this code.
in the contructor add this code
private bool _keyboardIsOn;
cto(){
// Initio
keyboardService.KeyboardIsShown += (sender, e){ _keyboardIsOn = true; }
keyboardService.KeyboardIsHidden += (sender, e){ _keyboardIsOn = false; }
}
No you could check if _keyboardIsOn and add your coditions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61279486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Grid resizes the line based on the largest widget I'm having trouble resizing the ComboBox. Instead of being on the "Filter Order Status" side, she walked away. I realized that this happened because the size of the grid line was increased due to the size of the largest widget, which in this case are the tables.
How can I place the ComboBox next to "Filter Order Status" as it is in frame2, without changing the table size?
Here the sample code that shows the ComboBox being resized according to the size of the table
from tkinter import *
from tkinter import ttk
def make_table(row, column, window, text=0, headings=[], image=None, letter_pos=LEFT, borderwidth=1):
""" Returns a Frame with the created table """
data = [[0] * column for i in range(row)]
labels = [[0] * column for i in range(row)]
table = Frame(window)
while len(headings) < column:
headings.append(1)
for i in range(row):
# Insert "headings" values in the first line
if i == 0:
labels[i] = [Label(table, text=headings[j], image=image, compound=letter_pos, borderwidth=borderwidth,
relief='groove', anchor=W, width=0) for j in range(column)]
else:
labels[i] = [Label(table, text=0, image=None, compound=LEFT, borderwidth=1,
relief='groove', anchor=W, width=0) for j in range(column)]
for j in range(column):
labels[i][j].grid(row=i, column=j, sticky='we')
return table
window = Tk()
window.grid_rowconfigure(1, weight=1)
window.grid_columnconfigure(0, weight=1)
# Create the Frames
frame1 = Frame(window, bg='yellow')
frame2 = Frame(window, bg='red')
# Position the Frames
frame1.grid(row=0, column=0, sticky='nesw')
frame2.grid(row=0, column=1, sticky='nesw')
""" Frame1 content """
# Create the "frame1" widgets
label1 = Label(frame1, text='frame1')
filter_order_status1 = Label(frame1, text='Filter Order Status')
comboBox_1 = ttk.Combobox(frame1, values=['Entregado', 'Não entregado'])
table1 = make_table(8, 4, frame1, headings=['', 'Customer', 'Order Status', 'Order Date'])
# Place the "frame1" widgets
label1.grid(row=0, column=0, sticky='w')
filter_order_status1.grid(row=1, column=0, sticky='w')
comboBox_1.grid(row=1, column=1, sticky='w')
table1.grid(row=2, column=0, sticky='w')
""" Frame2 content """
# Create the "frame2" widgets
label2 = Label(frame2, text='frame2')
filter_order_status2 = Label(frame2, text='Filter Order Status')
comboBox_2 = ttk.Combobox(frame2, values=['Entregado', 'Não entregado'])
table2 = make_table(8, 4, frame2, headings=[' ', 'Customer'])
# Place the "frame2" widgets
label2.grid(row=0, column=0, sticky='w')
filter_order_status2.grid(row=1, column=0, sticky='w')
comboBox_2.grid(row=1, column=1, sticky='w')
table2.grid(row=2, column=0, sticky='w')
window.mainloop()
A: The way I would do it is to create a frame specifically to hold just the label and the combobox. You can then easily use pack to align the label to the left and the combobox right next to it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62662206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Applying/removing last-child styling in a dynamic listing I have an unordered list with dynamic contents that can be shown/hidden, with all the li having border-bottom except the last child.
However, with jquery's .hide() applied to the last child, the element is just given display:none, therefore making the visually last element still showing its border-bottom.
What's the best way to solve this, that is also reusable across other similar ul within the project?
A: If you want to remove border-bottom of last 'li' element, then use following CSS:-
.classname:last-child{
border-bottom:0;
}
Where classname is the class added to the 'li' element.
.hide() will hide the last 'li' element, not border.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37536498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: PHP variable declaration I have some simple system to upload files and keep track of them for each particular user, using a database.
The problem of mine is, I connect to the database in the file checklogin.php, which is responsible to handle the $_POST from main_login.php.
In file 'checklogin.php':
$current_user_name = NULL;
which is a global variable for all files. Now in file signup.php, I try to include the checklogin.php to define that variable:
require_once '/checklogin.php';
...
mysql_query("INSERT INTO " . tbl_name . " (username, userpassword, userisadmin)
VALUES (''" . $_POST['myusername'] . "',"
. "'" . md5($_POST['mypassword']). "',"
. "0)");
$current_user_name = $_POST['myusername'];
header("location:login_success.php");
As you can see, I'm trying to set the value of the variable $current_user_name = $_POST['myusername'];, but when header goes to the file login_success.php, which is having require_once '/checklogin.php'; too, the variable is set again to null.
How can I solve this problem? i.e. How can I store the current user so that it is accessible by all files?
A: You cannot store a variable like that. Each request will be new execution in sever. In this kind situation we have to use session please check this
And another issue with your code is SQL injection, Please read this too
A: You can not access the Parameter received at checklogin.php
what you can do you can check the the login status and set the current user in session.
From session variable you can access and set the current user.
A: you can set a session variable for it and on every you can use it like this
session_start();
if(isset($_SESSION['current_user_name']))
{
$current_user_name = $_SESSION['current_user_name'];
}
else
{
$current_user_name = NULL;
}
and set your session variable as follows
session_start();
require_once '/checklogin.php';
////...
mysql_query("INSERT INTO " . tbl_name . " (username, userpassword, userisadmin)
VALUES (''" . $_POST['myusername'] . "',"
. "'" . md5($_POST['mypassword']). "',"
. "0)");
$current_user_name = $_POST['myusername'];
$_SESSION['current_user_name'] = $current_user_name; // set your session here
header("location:login_success.php");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21694986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Plot "extended" predicted survival on top of KM ggsurvplot I would like to have those two plots gathered on one single plot. This would allow me to check how survival evolve on the long run while visually assessing the goodness of fit of the distribution.
Can you help me?
library(survminer)
require(flexsurv)
data(bc)
su_obj <- Surv(bc$rectime, bc$censrec)
fit_0 <- do.call(flexsurvreg, list(formula =su_obj~group, data = bc, dist = "exponential"))
ggsurvplot(fit_0)
time_0 = 5000
survival_ext = summary(fit_0, type = "survival",t=1:time_0)
survival_ext = as.data.frame(survival_ext)
survival_ext = survival_ext[,grep(".est", names(survival_ext))]
survival_ext = cbind(1:time_0, survival_ext)
names(survival_ext)[1]="time"
survival_ext = reshape2::melt(survival_ext,id="time")
ggplot(survival_ext,aes(x=time, y=value, color=variable)) +
geom_line() +
labs(x="Time",
y="Survival probability",
color="")
A: I would imagine there are a number of different thoughts about this, but here is one simple approach if it helps.
fit_0_obj <- ggsurvplot(fit_0)
ggplot(survival_ext,aes(x=time, y=value, color=variable)) +
geom_line() +
labs(x="Time",
y="Survival probability",
color="") +
geom_step(data = fit_0_obj$data.survplot, aes(x=time, y=surv, color=group))
Edit (9/20/21): With a bug in the survminer package, the "group" in the bc data needs to be character and not a factor. Until fixed, you can do the following to reproduce the plot:
bc$group <- as.character(bc$group)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59435385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use clang to compile code with gnu directives Is it possible to compile this code with clang so that it does not produce the "unknown directive" error?
.list
.text
.globl _main
.align 16, 0x90
_main:
ret
.nolist
Edited:
clang version 3.6.2.
test.s:1:1: error: unknown directive
.list
test.s:7:1: error: unknown directive
.nolist
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46489043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Backbone Routers: wait for data to be fetched first I think I don’t quite get the idea behind the proper usage of Backbone routers. Here’s what I’ve got:
I have some data that I fetch from the server when the page loads and then pack it into models and collections. The number of those models and collections is indefinite. I want to use the router to be able to render the certain collection’s view directly from the start.
The problem is: Backbone router starts up early, and since I ask it to access a certain view and trigger its render action, it cannot do that, because those views are not yet created. That means I actually have to make my routes start up after the fetch is complete.
I don’t know if this is a proper way to do it, but the only idea I came up with is to:
*
*Wrap the routes definition and the Backbone.history.start(); bit into a separate top-level-accesible function (i.e. prepare to call it manually later on).
*Run that function as the success callback for my collections’s fetch()
*The number of those collections is unknown, also I have no way to find out when all of them have been fetched, and I don’t want to start the routes more than once. So I make use of _.defer() and _.once().
This works, but it sure looks very weird:
Routers:
window.startRoutes = _.once(function() {
var AccountPage = Backbone.Router.extend({
routes: {
'set/:id': 'renderSet',
},
renderSet: function(setId) {
/** … **/
// Call the rendering method on the respective CardView
CardsViews[setId].render();
}
});
var AccountPageRouter = new AccountPage;
Backbone.history.start();
});
Collection:
window.CardsCollection = Backbone.Collection.extend({
model: Card,
initialize: function(params) {
/** … **/
// Get the initial data
this.fetch({success: function() {
_.defer(startRoutes);
}});
},
});
So my question is… am I doing it right? Or is there a better way to do this (must be)?
A: You can define your router ahead of time; it won't do anything until you call Backbone.History.start().
You can bind the "reset" event on your collection to start history like this:
my_collection.bind("reset", _.once(Backbone.History.start, Backbone.History))
Then the router will start doing stuff when your collection is fully loaded. I'm not sure if this is exactly what you're looking for (since you mentioned having a variable number of collections).
I have a similar situation, except that I know in advance which collections I want to have loaded before I start routing. I added a startAfter method to my Router, like so:
window.Workspace = new (Backbone.Router.extend({
. . .
startAfter: function(collections) {
// Start history when required collections are loaded
var start = _.after(collections.length, _.once(function(){
Backbone.history.start()
}))
_.each(collections, function(collection) {
collection.bind('reset', start, Backbone.history)
});
}
}));
and then after I've setup my collections
Workspace.startAfter([collection_a, collection_b, ...])
This could be adapted to work with standalone models too, although I think you'd need to bind to something other than the 'reset' event.
I'm glad I read your example code, the use of _.once and _.defer pointed me in the right direction.
A: I'm just checking in my .render() method that all required fields are filled, before using it. If it's not filled yet - i'm rendering an 'Loading...' widget.
And all my views are subscribed to model changes, by this.model.bind('change', this.render, this);, so just after model will be loaded, render() will be called again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7822542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Storing the name of a radio button when checked, then removing it when it's cleared This is the HTML code I currently have:
JSFiddle
<div class="container-cell col1 row1 component-sortable component-droppable ui-block-a" style="width:48%; text-align: left; vertical-align: top;" data-col="1" data-row="1">
<style>
label[for="checkbox-1"].ui-checkbox-on {}
label[for="checkbox-1"].ui-checkbox-off {}
</style>
<div data-control-type="checkbox" data-control-id="checkbox-1" data-control-name="checkbox-1" data-object-column="A">
<input type="checkbox" name="checkbox-1" id="checkbox-1" data-theme="a">
<label for="checkbox-1" data-translatable="Noise [A]">Noise [A]</label>
</div>
Is there a possible way I can have a global variable (say of var test;) then when the radio button is checked, store the name of the label as test = label; (for instance). Then when it's removed, it will call the variable and empty it as the box has now been unchecked?
I've looked in to it a bit but can't find much, sorry for the basic q - I'm new to JS and taking on my own projects but seem to struggle with basic stuff.
A: Get the text of label when checkbox .is(':checked')
var text = null;
$('input[type="checkbox"]').on('change', function() {
if ($(this).is(':checked')) {
var text = $(this).next('label').text();
alert(text);
} else {
alert(text);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-cell col1 row1 component-sortable component-droppable ui-block-a" style="width:48%; text-align: left; vertical-align: top;" data-col="1" data-row="1">
<style>
label[for="checkbox-1"].ui-checkbox-on {}
label[for="checkbox-1"].ui-checkbox-off {}
</style>
<div data-control-type="checkbox" data-control-id="checkbox-1" data-control-name="checkbox-1" data-object-column="A">
<input type="checkbox" name="checkbox-1" id="checkbox-1" data-theme="a">
<label for="checkbox-1" data-translatable="Noise [A]">Noise [A]</label>
</div>
Second Example:
You can store name if checked or unchecked in an array:
var store = new Array();
$('input[type="checkbox"]').on('change', function() {
if ($(this).is(':checked')) {
var text = $(this).next('label').text();
store.push(text);
} else {
var removeItem = $(this).next('label').text();
store = $.grep(store, function(value) {
return value != removeItem;
});
}
console.log(store);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-cell col1 row1 component-sortable component-droppable ui-block-a" style="width:48%; text-align: left; vertical-align: top;" data-col="1" data-row="1">
<style>
label[for="checkbox-1"].ui-checkbox-on {}
label[for="checkbox-1"].ui-checkbox-off {}
</style>
<div data-control-type="checkbox" data-control-id="checkbox-1" data-control-name="checkbox-1" data-object-column="A">
<input type="checkbox" name="checkbox-1" id="checkbox-1" data-theme="a">
<label for="checkbox-1" data-translatable="Noise [A]">Noise [A]</label>
</div>
A: You can try below code
var test = "";
$('input[type="checkbox"]').on('change', function() {
if ($(this).is(':checked')) {
test = $(this).next('label').text();
console.log("test value: " + test)
} else {
test = "";
console.log("test value: " + test)
}
});
body {
font: 13px Verdana;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-cell col1 row1 component-sortable component-droppable ui-block-a" style="width:48%; text-align: left; vertical-align: top;" data-col="1" data-row="1">
<div data-control-type="checkbox" data-control-id="checkbox-1" data-control-name="checkbox-1" data-object-column="A">
<input type="checkbox" name="checkbox-1" id="checkbox-1" data-theme="a">
<label for="checkbox-1" data-translatable="Noise [A]">Noise [A]</label>
</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48075136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ : avoiding compiler dependencies vs. avoiding pointer overuse I know it's considered old-fashioned / out-of-date style to overuse pointers where they aren't necessary. However, I'm finding this ideal conflicts with another consideration of avoiding compiler dependencies.
Specifically, I can use forward declarations in a header file and avoid #include statements if member variables are pointers. But then this leads me to member variables of my own classes to be pointers, even when there's not really a good reason to do so.
Incidentally, I find using the Qt framework (which I enjoy) leads me to program in this java-esque everything-on-the-heap programming style since that's the way the interface is setup.
How do I weigh these two competing considerations?
A: Qt needs it because it is a library that can be dynamically loaded. Users can compile and link without having to worry about implementation details. You can at runtime use many versions of Qt without having to recompile. This is pretty powerful and flexible. This wouldn't be possible if private object instances were used inside classes.
A: It depends. Reducing dependencies is definitely a good thing,
per se, but it must be weighed against all of the other issues.
Using the compilation firewall idiom, for example, can move the
dependencies out of the header file, at the cost of one
allocation.
As for what QT does: it's a GUI framework, which (usually---I've
not looked at QT) means lots of polymorphism, and that most
classes have identity, and cannot be copied. In such cases, you
usually do have to use dynamic allocation and work with
pointers. The rule to avoid pointers mainly concerns objects
with value semantics.
(And by the way, there's nothing "old-fashioned" or
"out-of-date" about using too many pointers. It's been the rule
since I started using C++, 25 years ago.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18340719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Invalid access_token when using RSpec request specs to authorize a request I'm trying to test CredentialsController, which works fine in production, using RSpec request specs.
Code
Controller
class CredentialsController < ApplicationController
before_action :doorkeeper_authorize!
def me
render json: current_user
end
end
(GET /me routes to CredentialsController#me.)
Request Specs
describe 'Credentials', type: :request do
context 'unauthorized' do
it "should 401" do
get '/me'
expect(response).to have_http_status(:unauthorized)
end
end
context 'authorized' do
let!(:application) { FactoryBot.create(:application) }
let!(:user) { FactoryBot.create(:user) }
let!(:token) { FactoryBot.create(:access_token, application: application, resource_owner_id: user.id) }
it 'succeeds' do
get '/me', params: {}, headers: {access_token: token.token}
expect(response).to be_successful
end
end
end
The unauthorized test passes, but the authorized test fails:
expected #<ActionDispatch::TestResponse:0x00007fd339411248 @mon_mutex=#<Thread::Mutex:0x00007fd339410438>, @mo..., @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil>>.successful? to return true, got false
The headers indicate a problem with the token:
0> response.headers['WWW-Authenticate']
=> "Bearer realm=\"Doorkeeper\", error=\"invalid_token\", error_description=\"The access token is invalid\""
token looks okay to me, though:
0> token
=> #<Doorkeeper::AccessToken id: 7, resource_owner_id: 8, application_id: 7, token: "mnJh2wJeEEDe0G-ukNIZ6oupKQ7StxJqKPssjZTWeAk", refresh_token: nil, expires_in: 7200, revoked_at: nil, created_at: "2020-03-19 20:17:26", scopes: "public", previous_refresh_token: "">
0> token.acceptable?(Doorkeeper.config.default_scopes)
=> true
Factories
Access Token
FactoryBot.define do
factory :access_token, class: "Doorkeeper::AccessToken" do
application
expires_in { 2.hours }
scopes { "public" }
end
end
Application
FactoryBot.define do
factory :application, class: "Doorkeeper::Application" do
sequence(:name) { |n| "Project #{n}" }
sequence(:redirect_uri) { |n| "https://example#{n}.com" }
end
end
User
FactoryBot.define do
factory :user do
sequence(:email) { |n| "email#{n}@example.com" }
password { "test123" }
password_confirmation { "test123" }
end
end
Questions
*
*Why am I getting invalid_token on this request?
*Do my Doorkeeper factories look correct?
A: I was passing the token wrong. Instead of:
get '/me', params: {}, headers: {access_token: token.token}
I had to use:
get '/me', params: {}, headers: { 'Authorization': 'Bearer ' + token.token}
A: You can check your Access Token factory's scopes, It should be same as initializer's default_scopes
e.g.
config/initializers/doorkeeper.rb
default_scopes :read
Below, your Access Token factory's scopes should be
factory :access_token, class: "Doorkeeper::AccessToken" do
sequence(:resource_owner_id) { |n| n }
application
expires_in { 2.hours }
scopes { "read" }
end
Additionally, if you encountered response status: 406 while get '/me'....
It means that the requested format (by default HTML) is not supported. Instead of '.json' you can also send Accept="application/json" in the HTTP header.
get '/me', params: {}, headers: {
'Authorization': 'Bearer ' + token.token,
'Accept': 'application/json'}
I resolved my problem with this solution, maybe you can try it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60764500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cannot publish .net application or to install Web Deploy 3.5 When I tried to publish my .net application on the server using using Web Deploy 3.0 I got this error:
Web deployment task failed. Microsoft.Web.Deployment.DeploymentBaseOptions' does not contain a definition for 'UserAgent'
Searching the web I found that someone fixed this problem upgrading Web Deploy to version 3,.5.
When I tried to upgrade Web Deploy to the version 3.5 I got this error:
http://sciepa.org/zalek/pictures/WebDeploy3.5Failed.png
MSI (s) (78:1C) [13:26:40:909]: Hello, I'm your 32bit Elevated custom action server.
DEBUG: Error 2738: Could not access VBScript runtime for custom action
MSI (s) (78:54) [13:26:40:916]: Product: Microsoft Web Deploy 3.5 -- The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2738
Then I tried to get current Web Deploy using Visual Studio 2013, and got this error:
http://sciepa.org/zalek/pictures/WebDeploy3.5FailedWithVS.png
Here are logs of the installation through Visual Studio:
http://sciepa.org/zalek/pictures/Log_with_vs_professional.txt
To fix error code is 2738 someone suggested this command:
[http://www.jakeludington.com/windows_7/20091115_error_2738_could_not_access_vbscript_run_time_for_custom_action.html][4]
I registered vbscript using command:
c:\windows\syswow64\regsvr32 vbscript.dll
c:\windows\system32\regsvr32 vbscript.dll
I also added to the PATH folders where vbscript.dll is located: C:\Windows\SysWOW64\;c:\windows\system32\
but it didn't help.
Any ideas what to do next?
A: After many hours of searching, repairing system using SFC.EXE /SCANNOW command I found that the problem was McAfee antivirus program. My PC come with McAfee, but I uninstall it it - at least this is what I thought I did.
This page explains how to do it in details:
detail explanation
What I did was to run this program:
McAfee uninstall
Zalek
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26831934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: database functional dependency decomposition Table - Person {ID, Name, Age, Line1, City, State, Zip}
FD set
1) ID -> every other attribute as it is PK
2) I'm not able to determine whether
zip -> {Line1, City, State} or..
{Line1, City, State} -> zip?
[both of these are candidate keys I guess]
In either case, it becomes transitive dependency since
ID -> Zip -> other address (or ID -> address related -> Zip).
It violates 3NF (transitive dependency).
Could you please explain how do I decompose the given relation, and what becomes PK in the other relation containing address related.
A: If you know (Line1, City, State) you can determine zip. So,
{Line1, City, State} -> zip
Not the other way around. Because the same zip may contain multiple Line1 values for the same City and State (e.g. different house numbers on the same street).
For 3NF the relations can be
*
*Person {ID, Name, Age, Line1, City, State}
*Address {Line1, City, State, Zip}
From practicality it seems redundent and waste of space in database tables.
A: Assuming {Line1, City, State}->{Zip} and {Zip}->{City, State} then the following decomposition is in 3NF:
Person {ID, Name, Age, Line1, Zip} (key= {ID})
Address {City, State, Zip} (keys = {City, State} and {Zip])
In practice that may not be useful because real address data is often inconsistent or has parts missing. The real question is which dependencies you actually want to enforcein your database. That is why exercises that depend on identifying dependencies only from a list of attribute names are so highly subjective. The only way to give a definitive answer is to start with the set of dependencies which you want the schema to satisfy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8161484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Append only if there are no duplicates I'm making a simple notification list with AJAX and I made it append html with data from a PHP script to a div with setInterval. It should only append if it hasn't appended that specific div already, and when I insert a new row in database it should add the new row only and not spam the div with old rows.
<div class="notification-slider">
<div class="title">Notifications</div>
<ul class="notifications-container">
<script type="text/javascript">
$(document).ready(function() {
var data = new FormData();
var user_id = <?php echo $this->session->userdata("id"); ?>;
data.append("user_id", user_id);
setInterval(function() {
m.request({
method: "POST",
url: document.location.origin + "/index.php/_notifications/" + user_id,
data: data
})
.then(function(response) {
$.each(response, function(index, value){
if($(".notification-item").attr("data-noti-attr") != response[index].id)
{
$(".notifications-container").append('<a href="'+response[index].url+'" class="notification-item" data-noti-attr="'+response[index].id+'"> <li class="uk-clearfix"> <img src="'+response[index].sender_user_id+'" class="notification-image"> <div class="message"> <b>'+response[index].sender_user_id+'</b> '+response[index].content+'<br><br> <div class="uk-text-muted"><i class="fa fa-clock-o"></i> '+response.time_received+' ago</div> </div> </li> </a>');
}
});
});
}, 1000);
});
</script>
</ul>
</div>
I'm currently using an attribute called data-noti-attr for this. Basically if a div with the attribute data-noti-attr with the value of response[index].id already exist, do not add it again. But it doesn't work like I want it to, as it keep posting duplicates of everything.
How can I accomplish this? (I tried to explain it as good as I could, ask if it's confusing)
A: Attr will return value only for the first item. Read the full docs about it here.
Description: Get the value of an attribute for the first element in the set of matched elements.
So you need to filter the found items with your condition (specific data attribute in your case).
For example, using .is() method
if ($('.item').is('[data-id="' + myId+ '"]')) {
// do stuff
}
A: just check the length. you can use this
if($('.notification-item[data-noti-attr="'+value.id+'"]').length ==0){
....
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48804841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: --inspect-brk node-args for hardhat js scripts I run a hardhat script like this:
npx hardhat run myscript.js
I'd like to be able to debug this in the Chrome inspector, but when I do
npx --node-arg=--inspect-brk hardhat run myscript.js
I get the error message "ERROR: --node-arg/-n can only be used on packages with node scripts."
Is there a way to debug hardhat scripts in Chrome without resorting to console.log?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68785576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Creating and appending a DOM element with the content of another element My code is as follows
;(function(window){
var $description_window= document.querySelector('.mg_post_description'),
$headings= document.querySelectorAll('.mg_blog_main_content h3'),
$paragraph = document.createElement('p');
for (var j = 0; j < $headings.length; j++) {
var $headingChildren=$headings[j].cloneNode(true).childNodes;
$paragraph.appendChild($headingChildren[j]);
}
$description_window.append($paragraph);
})(window);
Here what I am trying to do is; to copy the h3 tags of the content box. Then create a paragraph element. Then append the p tags with collected h3 tags. However, I get the following error on running this.
Failed to execute appendChild on Node: parameter 1 is not of type Node.
;(function(window){
var $description_window= document.querySelector('.post_description'),
$headings= document.querySelectorAll('.post_description h3'),
$paragraph = document.createElement('p');
for (var j = 0; j < $headings.length; j++) {
var $headingChildren=$headings[j].cloneNode(true).childNodes;
$paragraph.appendChild($headingChildren[j]);
}
$description_window.append($paragraph);
})(window);
.post_description{
width:200px;
height:200px;
background-color:#555;
position:absolute;
top:10%;
right:8%;
}
.post_description a {
color:white;
}
.main_body{
padding-top:40%;
}
<div class="main_body">
<h3>Testing one</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<h3>Testing two</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<h3>Testing three</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<h3>Testing four</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
<div class="post_description"></div>
Could someone please explain why this occurs and how to solve this
Thanks
A: To achieve expected result, use below option
function addElem() {
var mElem = document.querySelector('.mg_post_description')
var hElems = document.getElementsByTagName('H3');
var node = document.createElement("P");
for (var i = 0; i < hElems.length; i++) {
var textnode = document.createTextNode(hElems[i].innerHTML);
var cloneElem = node.cloneNode(true);
cloneElem.appendChild(textnode);
mElem.appendChild(cloneElem);
}
};
addElem()
Codepen- https://codepen.io/nagasai/pen/YVEzdJ
A:
var d = document.querySelector('.desc'),
h = document.querySelectorAll('.main h3');
h.forEach(function(n) {
var p = document.createElement('p');
p.innerHTML = n.cloneNode(true).innerHTML || '';
d.append(p);
});
.desc {
color: red;
}
<div class="main">
<h3>First</h3>
<h3>Second</h3>
<h3>Third</h3>
</div>
<div class="desc">
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43817360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pipe and select : sample code not working Am I missing something ?
I want to come out of select by calling write in another thread... It never comes out of select.
Code is tested on OSX snow.
fd_set rio, wio;
int pfd[2];
void test(int sleep_time)
{
sleep(sleep_time);
char buf[] = "1";
write(pfd[1], buf, 1);
}
int main(int argc, char* argv[])
{
char buff[80];
int ended = 0;
pipe(pfd);
FD_ZERO(&rio);
FD_ZERO(&wio);
FD_SET(pfd[1], &wio);
FD_SET(pfd[0], &rio);
pthread_t tid; /* the thread identifier */
pthread_attr_t attr; /* set of thread attributes */
pthread_attr_init(&attr);
pthread_create(tid, NULL, test, 3);
while (!ended)
{
// Check my numbers ... they do not go over 1 ... so 2
if (select(2, &rio, &wio, NULL, 0) < 0)
perror("select");
else
{
if (FD_ISSET(pfd[1], &wio))
{
if ((read(pfd[0], &buff, 80))<0)
perror("read");
ended = 1;
}
}
}
A: I believe you have 2 errors:
1 - your select call is limiting the check to a max of fd 2, where the pipe will probably have larger FDs since 0, 1, and 2 are already opened for stdin, stdout, stderr. The pipe FDs will presumably have fds 3 and 4 so you actually need to determine the larger of the 2 pipe FDs and use that for the limit in the select instead of 2.
int maxfd = pfd[1];
if( pfd[0] > maxfd ) {
maxfd = pfd[0];
}
...
2 - After select returns, you are looking at the wio and pipe write FD when you need to instead look to see if there is anything available to READ:
if (FD_ISSET(pfd[0], &rio)) {
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5185836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: symfony (doctrine): DQL query, how to exclude results? I have very basic knowledge of SQL and don't how to modify my query so it returns the expected result.
My entities Activity has a field members (a manyToMany relation). An activity can be done by several members.
I want to select all the activities a specific member does NOT take part into. I know the member's id (my variable $selfId).
Here's what I'm doing in ActivityRepository:
public function getCollectiveActivities($selfId)
{
$qb = $this->createQueryBuilder('a');
$qb->join('a.members', 'm')
->where('m.id != :selfId')
->setParameter('selfId', $selfId);
return $qb
->getQuery()
->getResult();
}
My problem: when an activity "owns" two or more members, if one of them has $selfId as id, this activity ends up in my query results.
But since one of the members of this activity has the id $selfId, it should not be returned. What am I doing wrong?
EDIT
I think I need to be more restrictive, I just don't know how.
Let's say I have two activities:
activity1 which is owned by member1 and member2
activity2 which is owned by member3 and member4
$selfId = 3 (this means I don't want to fetch activities owned by member3)
From what I understand, the join clause might return lines like these:
activity1 | memberId: 1 (different from selfId = 3 so activity1 will be fetched)
activity1 | memberId: 2 (different from selfId = 3 so activity1 will be fetched)
activity2 | memberId: 3 (= selfId so activity2 shouldn't be fetched)
activity2 | memberId: 4 (different from selfId = 3 so activity2 WILL be fetched. PROBLEM???)
EDIT 2
Others already faced the same problem and found this solution and this one, but they seem a bit hacky. Any clue on how to improve them would be welcome.
A: You have to specifically select the results you want to be hydrated. The problem you're seeing is that you're just selecting activity.
Then when you call $activity->getMembers() members are lazy loaded, and this doesn't take into account your query.
You can avoid this like so:
public function getCollectiveActivities($selfId)
{
$qb = $this->createQueryBuilder('a');
$qb->addSelect('m');
$qb->join('a.members', 'm')
->where('m.id != :selfId')
->setParameter('selfId', $selfId);
return $qb
->getQuery()
->getResult();
}
This means your fetched activity will already have its members hydrated and restricted by your query condition.
A: public function getCollectiveActivities($selfId)
{
return $this->createQueryBuilder('a')
->join('a.members', 'm')
->where($qb->expr()->neq('c.selfId', $selfId))
->getQuery()
->getResult();
}
A: I ended up adapting a solution posted by @NtskX.
public function getCollectiveActivities($selfId)
{
$qbMyCollectives = $this->createQueryBuilder('ca');
$qbMyCollectives
->select('ca.id')
->leftJoin('ca.members', 'm')
->where('m.id = :selfId')
->setParameter('selfId', $selfId);
$qb = $this->createQueryBuilder('a');
$qb
->where($qb->expr()->notIn('a.id', $qbMyCollectives->getDQL()))
->setParameter('selfId', $selfId); // I had to declare the parameter one more time
return $qb
->getQuery()
->getResult();
}
I really thought someone would show up with a better way to do the join, so any other answer is much welcome.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36637186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how check if doc was updated using updateOne() [mongoose,React , Node js, Mongodb] here is my updating code apparently this works but I have no clue as to how to programmatic check if it had worked, I had an idea of storing the field want to update in temp variable before updating and then compare it against updatedDoc but t seemed odd I wonder if there is a simpler way
router.post('/update',async(req,res)=>{
const {id,addresses}= req.body
try {
const targetDoc=await UserModel.findOne({_id:id});
const updates = { addresses};
const updateResponse = await targetDoc.updateOne(updates);
// need to check for succes here
const updatedDoc = await UserModel.findOne({_id:id});
res.sendStatus(200)
} catch (error) {
console.log(error)
}
})
A: The best way to check if a document can be updated is to check before it's updated. That way, if any of the assertions you've made before the update are passing, then you'll know it's been successfully updated:
router.post('/update',async(req,res)=>{
try {
// move this statement inside the try block; otherwise if "id" or "addresses"
// is missing from req.body, it'll throw an unhandled destructure error
const { id, addresses} = req.body;
// make sure the id is present
if (!id) throw String("Invalid request. You must supply a user id to update!");
/*
I'm not sure how "addresses" is structured, but if you expect
it to be an object, then make assertions against an object with structure:
if(!object || object.length <= 0 || !object.name || !object.city ...etc)
if it's an array, then make assertions that it's not empty...
*/
if (addresses assertions are invalid)
throw String("Invalid request. The addresses you've provided are not valid! Please try again.");
/*
If the above passes the req.body assertions, then the only thing
that can fail here is if "id" is invalid. If it's invalid, then Mongoose
will throw an error if "updateOne" doesn't find the document;
otherwise, you'll know the document has been successfully updated.
Optionally, you can manually handle "id" errors by finding and throwing
an error if the document is empty BEFORE attempting to update,
for example...
const existingUser = await UserModel.findOne({ _id: id });
if (!existingUser) throw String("Unable to locate that user to update.");
await existingUser.update(addresses);
await existingUser.save();
*/
await UserModel.updateOne({ _id: id }, { addresses });
// if the above is successful, then the client should receive this
// message:
res.status(200).send("Successfully updated user!");
} catch (error) {
// if any of the above assertions are unsuccessful, then the
// client should receive an error message:
res.status(400).send(error.toString());
}
});
On a side note, always return a response! Even if it's just res.end(). Failing to do so, will result in a hung request/unhandled promise.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64271816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accessing Sharepoint Project web app REST from separate app I need to connect to our corporate PWA. This is the code I'm using:
// var endpointUrl = 'https://<companySite>.sharepoint.com/sites/pwa/_api/web/lists';
var endpointUrl = 'https://<companySite>.sharepoint.com/sites/pwa/_api/ProjectData/Projects?$select=ProjectName';
var xhr = new XMLHttpRequest();
xhr.open("GET", endpointUrl);
// The APIs require an OAuth access token in the Authorization header, formatted like this: 'Authorization: Bearer <token>'.
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Accept", "application/json");
$("#header").html("Requesting: " + endpointUrl);
// Process the response from the API.
xhr.onload = function () {
if (xhr.status == 200) {
var formattedResponse = JSON.stringify(JSON.parse(xhr.response), undefined, 2);
$("#results").html("<pre>" + formattedResponse + "</pre>");
} else {
$("#results").html("HTTP " + xhr.status + "<br>" + xhr.response);
}
}
// Make request.
xhr.send();
I've tried also a few different ways, all using Bearer token.
The problem is that this code works for accessing https://<companySite>.sharepoint.com/sites/pwa/_api/web/lists but doesn't for https://<companySite>.sharepoint.com/sites/pwa/_api/ProjectData/Projects?$select=ProjectName
For the latter it returns:
{"odata.error":{"code":"20010, Microsoft.ProjectServer.PJClientCallableException","message":{"lang":"en-US","value":"GeneralSecurityAccessDenied"}}}
What could be the possible problem?
I know that my token is correct, as it works for accessing */web/lists. I also know that the url is correct, as I can open it in my browser (providing that I'm logged in into sharepoint)
A: You need to use a FormDigestValue.
Make a GET call to .../_api/contextinfo and store the value of 'FormDigestValue'. Then for all your other calls, add a header of X-RequestDigest: <FormDigestValue>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41719686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send array of custom object as a multiform data content to asp.net web api via postman? How to properly send array of custom objects to asp.net web api via Postman? What I have done is:
Custom class:
public class SystemConsumerConfiguration
{
public int SystemId { get; }
public Uri CallbackUrl { get; }
public SystemConsumerConfiguration()
{
}
public SystemConsumerConfiguration(int systemId, Uri callbackUrl)
{
SystemId = systemId;
CallbackUrl = callbackUrl;
}
}
View model in REST API:
public class PostDigitalPostSubscriptionConfiguration
{
public IReadOnlyList<SystemConsumerConfiguration> SystemsModel { get; set; }
public IFormFile Certificate { get; set; }
public PostDigitalPostSubscriptionConfiguration()
{
}
}
And now, I make a request in Postman
The problem is, that model is bound with default values:
A: Forgot to have public setters in SystemConsumerConfiguration.
Should be like this:
public class SystemConsumerConfiguration
{
public int SystemId { get; set; }
public Uri CallbackUrl { get; set; }
public SystemConsumerConfiguration()
{
}
public SystemConsumerConfiguration(int systemId, Uri callbackUrl)
{
SystemId = systemId;
CallbackUrl = callbackUrl;
}
}
Answered in:
Default value in an asp.net mvc view model
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54146281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I put my Extjs 4.2.x project inside latest Angular App I have a large app built in Ext4.2.x. Now the requirement is to do further development in Angular.
I am trying to create a wrapper of Angular around Ext app so that we can use angular for further development/ migration of code piece by piece. till the time both the framework should work in harmony.
Approach I am trying:
*
*I have created app(name is: NgApp) scaffolding using angular-cli and put that code inside the root directory of Ext app(ExtNg).
*Created a folder(ExtNg/NgBuild)to hold the build file of angular JS app(NgApp).
*Built angular app : ng build -vc false -op C:\Ext\Ext6Grid\ngBuild
*I have modified app.js autCreateViewPort: false so it will initiate the ext app but will not render it.
*modified my Ext app's index.html body as below:
<body>
<app-root></app-root>
<script type="text/javascript" src="ngBuild/inline.bundle.js"></script>
<script type="text/javascript" src="ngBuild/polyfills.bundle.js"></script>
<script type="text/javascript" src="ngBuild/styles.bundle.js"></script>
<script type="text/javascript" src="ngBuild/main.bundle.js"></script>
</body>
*Now I tried putting my Ext.onReady() code in app.component.ts class's ngOnInit() and specified renderTo: someElemIDinAppComponentTemplate method to start Ext inside an angular component.
So the problem here is as expected that while building angular app it does not find Ext object because Angular as framework dont know if Ext is there or not.
So could anyone help me getting Ext available inside my angular app's component??
So thought to share with all the geniuses out there.
I will be glad for any suggestions.
Thank you.
A: I think that you are looking into this issue from the wrong angle. I suggest that you may build the angular app, and put yor ExtJS components inside that thing, not the opposite.
Here, you have an approximated approach of what you are trying to do : https://www.sencha.com/blog/first-look-ext-js-bridge-to-angular-2/
I want to believe "The Bridge" is also compatible with new Angular versions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48524407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I trigger action back in the react-native from my WebView? I have a component <PaymentView />, this component display a credit card/cvc/expiry form.
It is displayed in a react-native application using react-native-webview.
I must trigger the form event and update the view on submit, the submit button is currently within the WebView.
*
*After pressing the submit <Button /> from within the webview, how can I close the WebView and display a success message?
*If I can't get the webview submit event from within my component, how can I read the form within the webview from my component?
A: I usually have this problem when dealing with payment iframes in web applications. I think the solution is the same or a similar approach.
Check the postMessage API.
What we usually do, is emit an event on the iFrame (your webView i guess) side. Usually is a navigation event, and then we listen for that event globally in our app like:
<script>
var defaultResponse = {
status: 0,
code: '',
message: ''
}
function queryParamsToObject(search = '') {
return search ? JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g, '":"') + '"}') : ''
}
function getResponseObject() {
return queryParamsToObject(decodeURI(location.search).substring(1))
}
var response = getResponseObject()
console.log('window:child', window.parent, response)
try {
window.parent.postMessage(response, '*')
} catch (e) {
console.log('window:child:send:error', e)
}
</script>
On a fast search to react-native-webview i see that they are already using it
Hope it helps
A: check out this
render() {
const html = `
<html>
<head></head>
<body>
<script>
setTimeout(function () {
window.ReactNativeWebView.postMessage("Hello!")
}, 2000)
</script>
</body>
</html>
`;
return (
<View style={{ flex: 1 }}>
<WebView
source={{ html }}
onMessage={event => {
alert(event.nativeEvent.data);
}}
/>
</View>
);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62346035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python, creating a new variable from a dictionary? not as straightforward as it seems? I'm trying to create a new variable that will consist of an existing dictionary so that I can change things in this new dictionary without it affecting the old one. When I try this below, which I think would be the obvious way to do this, it still seems to edit my original dictionary when I make edits to the new one.. I have been searching for info on this but can't seem to find anything, any info is appreciated
newdictionary = olddictionary
A: You're creating a reference, instead of a copy. In order to make a complete copy and leave the original untouched, you need copy.deepcopy(). So:
from copy import deepcopy
dictionary_new = deepcopy(dictionary_old)
Just using a = dict(b) or a = b.copy() will make a shallow copy and leave any lists in your dictionary as references to each other (so that although editing other items won't cause problems, editing the list in one dictionary will cause changes in the other dictionary, too).
A: You are just giving making newdictionary point to the same reference olddictionary points to.
See this page (it's about lists, but it is also applicable to dicts).
Use .copy() instead (note: this creates a shallow copy):
newdictionary = olddictionary.copy()
To create a deep copy, you can use .deepcopy() from the copy module
newdictionary = copy.deepcopy(olddictionary)
Wikepedia :
Shallow vs Deep Copy
A: Assignment like that in Python just makes the newdictionary name refer to the same thing as olddictionary, as you've noticed. You can create a new dictionary with the dict() constructor:
newdictionary = dict(olddictionary)
Note that this makes a shallow copy. For deep copies, see the copy standard library module.
A: newdictionary = dict(olddictionary.items())
This creates a new copy (more specifically, it feeds the contents of olddict as (key,value) pairs to dict, which constructs a new dictionary from (key,value) pairs).
Edit: Oh yeah, copy - totally forgot it, that's the right way to do it.
a = b
just copies a reference, but not the object.
A: You are merely creating another reference to the same dictionary.
You need to make a copy: use one of the following (after checking in the docs what each does):
new = dict(old)
new = old.copy()
import copy
new = copy.copy(old)
import copy
new = copy.deepcopy(old)
A: I think you need a deep copy for what you are asking. See here.
It looks like dict.copy() does a shallow copy, which is what Rick does not want.
from copy import deepcopy
d = {}
d['names'] = ['Alfred', 'Bertrand']
c = d.copy()
dc = deepcopy(d)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3525453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: PHP Delete MySQL Records Older Than 3 Days I have the following at the top of every page so when the website is loaded by anyone PHP deletes any record in a specific database table that is older than 3 days.
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < DATE_SUB(DATE('m-d-Y'), INTERVAL 3 DAY");
The problem is nothing is being deleted.
The data type for my date column is varchar(20) and when I insert a date into MySQL it is entered using date("m-d-Y"). The name of my date field is date. So it appears that the above query would be correct, but I have done something wrong, and I am not certain as to what since every example I've looked at has basically looked the same except they used now() instead of date() but I use a specific date format so I can't use now() in my query.
What have I done wrong?
I even tried putting it into a function:
function deleteOversizeRows() {
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < DATE_SUB(DATE('m-d-Y'), INTERVAL 3 DAY");
}
deleteOversizeRows();
A: Try to provide date by calculating first and then use it in query like below
$date = date("m-d-Y", strtotime('-3 day'));
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < '".$date."');
It might help you. If need any other solution or help, do ask here.
A: Use MySQL function TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2);
Function calculates difference between two dates and returns output based on the unit parameter passed .
Try this:
DELETE FROM postedLoads WHERE TIMESTAMPDIFF('DAY',date,now())<3;
For detailed info of function:http://www.w3resource.com/mysql/date-and-time-functions/mysql-timestampdiff-function.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36383351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Xamarin Forms Image to ASP.NET API Controller (Post) I have a controller in my API that requests a HttpPostedFileBase as one of the parameters.
I also have a Xamarin Forms application that is going to send out a post request to this API, passing the image as data. What would be the best way to send an image, I cannot figure out how to convert it.
I'm using the plugin "Xam.Plugin.Media" for the camera, taking the photo with the code below:
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", "No camera available", "OK");
}
else
{
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
SaveToAlbum = true
});
if (file == null)
return;
await DisplayAlert("File Location", file.Path, "OK");
UserPicture.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
}
The variable "file" that holds the photo is of type "Plugin.Media.Abstractions.MediaFile"
If anybody has any advice as to how I would convert this file type to one that can be uploaded to the API, as a HttpPostedFileBase file, that would be brilliant!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52820602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Nuxt: Cannot read property 'title' of undefined I am doing a Nuxt tutorial and I cant figure out why I keep getting thisCannot read property 'title' of undefined error. Is there something I am missing or could it be that Nuxt/Vue has been updated since the tutorial was released?
Recipes page:
<template>
<section class="recipes">
<Recipe
v-for="recipe in recipes"
:key="recipe.id"
:id="recipe.id"
:thumbnail="recipe.thumbnail"
:title="recipe.title"
:description="recipe.description"
/>
</section>
</template>
<script>
import Recipe from '@/components/Recipe';
export default {
components: {
Recipe
},
asyncData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
recipes: [
{
id: 23,
title: "Gatsby",
description: "Eat Gatsby",
thumbnail: "http://www.eatout.co.za/wp-content/uploads/2016/10/gatsby.jpg"
},
{
id: 26,
title: "Rolly",
description: "Eat Rolly",
thumbnail: "http://www.prontomama.co.za/wp-content/uploads/2011/11/Pronto-Mama-Recipe-Boerewors-Rolls.jpg"
}
]
})
},1500)
})
}
}
</script>
<style scoped>
.recipes {
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: center;
}
</style>
Recipe details page
<template>
<section class="single-recipe">
<h1>{{ recipe.title }}</h1>
<div>
<img :src="recipe.thumbnail" :alt="recipe.title">
</div>
<p>{{ recipe.description }}</p>
</section>
</template>
<script>
export default {
asyncData(context) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
recipe: [
{
id: 23,
title: "Gatsby",
description: "Eat Gatsby",
thumbnail: "http://www.eatout.co.za/wp-content/uploads/2016/10/gatsby.jpg"
},
{
id: 26,
title: "Rolly",
description: "Eat Rolly",
thumbnail: "http://www.prontomama.co.za/wp-content/uploads/2011/11/Pronto-Mama-Recipe-Boerewors-Rolls.jpg"
}
].find(i => i.id === context.params.id) // to simulate single item selection
})
},1500)
})
}
}
</script>
<style>
.single-recipe {
display: flex;
flex-flow: column;
justify-content: center;
align-items: center;
text-align: center;
padding: 30px;
}
</style>
A: There no asyncData/fetch methods on components in nuxt. It is available only for page components. Reference https://nuxtjs.org/api/
asyncData is called every time before loading the component (only for
page components).
A: context.params.id is a string and the id in the array of objects is an integer therefore find() is not returning the expected object. Changing id to a string in the array of objects fixed the error.
A: in my case I was missing the .id in context.params.id
simple oversight.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52948004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error in Github Action for Laravel / PHPUnit I have an error in my github action for my laravel unit/feature tests using PHPUnit. My tests are passing locally. This is the error:
1) Tests\Feature\ClientControllerTest::test_clients_index_page_is_rendered
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL (SQL: alter table "users" add column "role_id" integer not null)
It could be that I'm not fully understanding the way the testing works, but I'm using an in-memory sqllite database for testing. I have a migration for the users table and then another migration that adds a role_id to the user table after a roles table is created.
Not understanding why the error is occurring during the test_clients_index_page_is_rendered test because the database should already be up and populated at that point.
I don't know if it's because the roles table is not populated with data, and it's a foreign key on the users table. I would think that would fail locally as well though because I'm still using the in-memory database. I have a seeder to populate the roles, but I'm not calling it from anywhere in my tests. Not sure if I need to be doing that, or where to do it?
Here is the test mentioned in the error:
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ClientControllerTest extends TestCase
{
use RefreshDatabase;
protected $user;
public function setup() :void
{
parent::setUp();
$this->user = User::factory()->create();
}
public function test_clients_index_page_is_rendered()
{
$this->actingAs($this->user);
$response = $this->get('/clients');
$response->assertStatus(200);
}
Here are the related migrations that I suppose could also be causing the problems:
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
}
And then later the roles table is added, and then the foreignkey:
Schema::table('users', function (Blueprint $table) {
$table->foreignIdFor(Role::class)->after('password');
});
I'm not even sure how to troubleshoot this issue as it's passing locally. Any help would be greatly appreciated.
Here's the full trace in case it helps:
1) Tests\Feature\ClientControllerTest::test_clients_index_page_is_rendered
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL (SQL: alter table "users" add column "role_id" integer not null)
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Connection.php:705
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Connection.php:665
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Connection.php:495
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php:109
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php:363
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php:210
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:261
/home/runner/work/momentum/momentum/database/migrations/2022_01_01_222316_add_role_id_to_users_table.php:19
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:394
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:403
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:202
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:167
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:112
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:85
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:585
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:94
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:36
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Container/Util.php:40
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:93
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:37
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Container/Container.php:653
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Console/Command.php:136
/home/runner/work/momentum/momentum/vendor/symfony/console/Command/Command.php:298
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Console/Command.php:121
/home/runner/work/momentum/momentum/vendor/symfony/console/Application.php:1005
/home/runner/work/momentum/momentum/vendor/symfony/console/Application.php:299
/home/runner/work/momentum/momentum/vendor/symfony/console/Application.php:171
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Console/Application.php:94
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Console/Application.php:186
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:263
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Testing/PendingCommand.php:260
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Testing/PendingCommand.php:413
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithConsole.php:66
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabase.php:45
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Foundation/Testing/RefreshDatabase.php:20
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:122
/home/runner/work/momentum/momentum/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:91
/home/runner/work/momentum/momentum/tests/Feature/ClientControllerTest.php:19
Caused by
PDOException: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL
UPDATE
Adding my user factory:
namespace Database\Factories;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
public function definition()
{
return [
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'phone' => $this->faker->unique()->numerify('###-###-####'),
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi',
'remember_token' => Str::random(10),
'role_id' => rand(1,4)
];
}
}
A: As you can see in the stack trace, exception thrown during the migration step.
This happens because you adding not null column to your table, which generally impossible. SQLite don't know what value should be set to role_id for records that already in the table, so it prevents you from this operation.
You can either add default value to role_id, or move it to initial migration.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70669966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript - Would 'lunr' be a viable search library for Firebase? I'm trying to implement a search bar for my website that uses Firebase as its database. It's a bunch of links to certain images and embed videos. I'm thinking is it best to have a "tag" field for each link, that the lunr library would query for? I'd split each tag field into an array of strings and the lunr would look for each one?
My database has the JSON format of:
{ "Featured" : {
"Link1" : {
"isEmbed" : false,
"priority" : 4,
"url" : "https://s3.amazonaws.com/hagshs8282n23/image7.jpg",
"tag" : nba nfl nhl mlb yahoo
},
"Link2" : {
"isEmbed" : false,
"priority" : 3,
"url" : "https://s3.amazonaws.com/hagshs8282n23/image6.jpg",
"tag" : fire base stuff art cool
} }
Is this a slow way to go about searching for objects or is there a better way to think about it?
Alternatively, I was thinking that whenever a file is added to the database, I would export that new JSON structure to a folder in the home directory of the website (/dir/ or something like that) and then have lunr read from that instead of Firebase. Would that be quicker since the files would be local and not in Firebase or would it not make a difference?
A: If you want/need full text search then lunr could certainly be used for providing an index on the tags in those documents.
If these links had a description, then lunr (or any other full text search) would be a good fit, you really are then doing a full text search.
Tags, to me anyway, imply a faceted search. I would imagine that you would have a finite list of these tags, and you would then want to find which links have these exact tags. You could approximate something similar with lunr, but there are probably better tools for the job.
Now, if you had a large list of tags, potentially with some kind of description, then you could use lunr to allow users to search for tags, and then use those tags to perform the faceted search on your links.
As for using lunr with firebase, as long as lunr has access to all of the link data for indexing, it doesn't care where you actually store the documents. I'm not at all familiar with firebase so can't comment on the practicality of integrating lunr with that service, perhaps someone else can help you out with that aspect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38231475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Extracting the city boundary coordinates from an OpenStreetMap dataframe I have the OpenStreetMap data for a country stored in a dataframe df. How can I get the coordinates (which together form a polygon in OSM terminology) of specific cities?
A previous answer on how to access a city give me this code:
df.filter(df("tags").getItem("name")==="Baarle-Nassau").show()
I have tried to access specifically get the boundary by using
df.filter(df("tags").getItem("name")==="Baarle-Nassau" && df("tags").getItem("type")==="boundary").show()
But this does not yield what I expect: an array of coordinates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69242873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Definitive List of Common Reasons for Segmentation Faults
NOTE: We have a lot of segfault questions, with largely the same
answers, so I'm trying to collapse them into a canonical question like
we have for undefined reference.
Although we have a question covering what a segmentation fault
is, it covers the what, but doesn't list many reasons. The top answer says "there are many reasons", and only lists one, and most of the other answers don't list any reasons.
All in all, I believe we need a well-organized community wiki on this topic, which lists all the common causes (and then some) to get segfaults. The purpose is to aid in debugging, as mentioned in the answer's disclaimer.
I know what a segmentation fault is, but it can be hard to spot in the code without knowing what they often look like. Although there are, no doubt, far too many to list exhaustively, what are the most common causes of segmentation faults in C and C++?
A:
WARNING!
The following are potential reasons for a segmentation fault. It is virtually impossible to list all reasons. The purpose of this list is to help diagnose an existing segfault.
The relationship between segmentation faults and undefined behavior cannot be stressed enough! All of the below situations that can create a segmentation fault are technically undefined behavior. That means that they can do anything, not just segfault -- as someone once said on USENET, "it is legal for the compiler to make demons fly out of your nose.". Don't count on a segfault happening whenever you have undefined behavior. You should learn which undefined behaviors exist in C and/or C++, and avoid writing code that has them!
More information on Undefined Behavior:
*
*What is the simplest standard conform way to produce a Segfault in C?
*Undefined, unspecified and implementation-defined behavior
*How undefined is undefined behavior?
What Is a Segfault?
In short, a segmentation fault is caused when the code attempts to access memory that it doesn't have permission to access. Every program is given a piece of memory (RAM) to work with, and for security reasons, it is only allowed to access memory in that chunk.
For a more thorough technical explanation about what a segmentation fault is, see What is a segmentation fault?.
Here are the most common reasons for a segmentation fault error. Again, these should be used in diagnosing an existing segfault. To learn how to avoid them, learn your language's undefined behaviors.
This list is also no replacement for doing your own debugging work. (See that section at the bottom of the answer.) These are things you can look for, but your debugging tools are the only reliable way to zero in on the problem.
Accessing a NULL or uninitialized pointer
If you have a pointer that is NULL (ptr=0) or that is completely uninitialized (it isn't set to anything at all yet), attempting to access or modify using that pointer has undefined behavior.
int* ptr = 0;
*ptr += 5;
Since a failed allocation (such as with malloc or new) will return a null pointer, you should always check that your pointer is not NULL before working with it.
Note also that even reading values (without dereferencing) of uninitialized pointers (and variables in general) is undefined behavior.
Sometimes this access of an undefined pointer can be quite subtle, such as in trying to interpret such a pointer as a string in a C print statement.
char* ptr;
sprintf(id, "%s", ptr);
See also:
*
*How to detect if variable uninitialized/catch segfault in C
*Concatenation of string and int results in seg fault C
Accessing a dangling pointer
If you use malloc or new to allocate memory, and then later free or delete that memory through pointer, that pointer is now considered a dangling pointer. Dereferencing it (as well as simply reading its value - granted you didn't assign some new value to it such as NULL) is undefined behavior, and can result in segmentation fault.
Something* ptr = new Something(123, 456);
delete ptr;
std::cout << ptr->foo << std::endl;
See also:
*
*What is a dangling pointer?
*Why my dangling pointer doesn't cause a segmentation fault?
Stack overflow
[No, not the site you're on now, what is was named for.] Oversimplified, the "stack" is like that spike you stick your order paper on in some diners. This problem can occur when you put too many orders on that spike, so to speak. In the computer, any variable that is not dynamically allocated and any command that has yet to be processed by the CPU, goes on the stack.
One cause of this might be deep or infinite recursion, such as when a function calls itself with no way to stop. Because that stack has overflowed, the order papers start "falling off" and taking up other space not meant for them. Thus, we can get a segmentation fault. Another cause might be the attempt to initialize a very large array: it's only a single order, but one that is already large enough by itself.
int stupidFunction(int n)
{
return stupidFunction(n);
}
Another cause of a stack overflow would be having too many (non-dynamically allocated) variables at once.
int stupidArray[600851475143];
One case of a stack overflow in the wild came from a simple omission of a return statement in a conditional intended to prevent infinite recursion in a function. The moral of that story, always ensure your error checks work!
See also:
*
*Segmentation Fault While Creating Large Arrays in C
*Seg Fault when initializing array
Wild pointers
Creating a pointer to some random location in memory is like playing Russian roulette with your code - you could easily miss and create a pointer to a location you don't have access rights to.
int n = 123;
int* ptr = (&n + 0xDEADBEEF); //This is just stupid, people.
As a general rule, don't create pointers to literal memory locations. Even if they work one time, the next time they might not. You can't predict where your program's memory will be at any given execution.
See also:
*
*What is the meaning of "wild pointer" in C?
Attempting to read past the end of an array
An array is a contiguous region of memory, where each successive element is located at the next address in memory. However, most arrays don't have an innate sense of how large they are, or what the last element is. Thus, it is easy to blow past the end of the array and never know it, especially if you're using pointer arithmetic.
If you read past the end of the array, you may wind up going into memory that is uninitialized or belongs to something else. This is technically undefined behavior. A segfault is just one of those many potential undefined behaviors. [Frankly, if you get a segfault here, you're lucky. Others are harder to diagnose.]
// like most UB, this code is a total crapshoot.
int arr[3] {5, 151, 478};
int i = 0;
while(arr[i] != 16)
{
std::cout << arr[i] << std::endl;
i++;
}
Or the frequently seen one using for with <= instead of < (reads 1 byte too much):
char arr[10];
for (int i = 0; i<=10; i++)
{
std::cout << arr[i] << std::endl;
}
Or even an unlucky typo which compiles fine (seen here) and allocates only 1 element initialized with dim instead of dim elements.
int* my_array = new int(dim);
Additionally it should be noted that you are not even allowed to create (not to mention dereferencing) a pointer which points outside the array (you can create such pointer only if it points to an element within the array, or one past the end). Otherwise, you are triggering undefined behaviour.
See also:
*
*I have segfaults!
Forgetting a NUL terminator on a C string.
C strings are, themselves, arrays with some additional behaviors. They must be null terminated, meaning they have an \0 at the end, to be reliably used as strings. This is done automatically in some cases, and not in others.
If this is forgotten, some functions that handle C strings never know when to stop, and you can get the same problems as with reading past the end of an array.
char str[3] = {'f', 'o', 'o'};
int i = 0;
while(str[i] != '\0')
{
std::cout << str[i] << std::endl;
i++;
}
With C-strings, it really is hit-and-miss whether \0 will make any difference. You should assume it will to avoid undefined behavior: so better write char str[4] = {'f', 'o', 'o', '\0'};
Attempting to modify a string literal
If you assign a string literal to a char*, it cannot be modified. For example...
char* foo = "Hello, world!"
foo[7] = 'W';
...triggers undefined behavior, and a segmentation fault is one possible outcome.
See also:
*
*Why is this string reversal C code causing a segmentation fault?
Mismatching Allocation and Deallocation methods
You must use malloc and free together, new and delete together, and new[] and delete[] together. If you mix 'em up, you can get segfaults and other weird behavior.
See also:
*
*Behaviour of malloc with delete in C++
*Segmentation fault (core dumped) when I delete pointer
Errors in the toolchain.
A bug in the machine code backend of a compiler is quite capable of turning valid code into an executable that segfaults. A bug in the linker can definitely do this too.
Particularly scary in that this is not UB invoked by your own code.
That said, you should always assume the problem is you until proven otherwise.
Other Causes
The possible causes of Segmentation Faults are about as numerous as the number of undefined behaviors, and there are far too many for even the standard documentation to list.
A few less common causes to check:
*
*UD2 generated on some platforms due to other UB
*c++ STL map::operator[] done on an entry being deleted
DEBUGGING
Firstly, read through the code carefully. Most errors are caused simply by typos or mistakes. Make sure to check all the potential causes of the segmentation fault. If this fails, you may need to use dedicated debugging tools to find out the underlying issues.
Debugging tools are instrumental in diagnosing the causes of a segfault. Compile your program with the debugging flag (-g), and then run it with your debugger to find where the segfault is likely occurring.
Recent compilers support building with -fsanitize=address, which typically results in program that run about 2x slower but can detect address errors more accurately. However, other errors (such as reading from uninitialized memory or leaking non-memory resources such as file descriptors) are not supported by this method, and it is impossible to use many debugging tools and ASan at the same time.
Some Memory Debuggers
*
*GDB | Mac, Linux
*valgrind (memcheck)| Linux
*Dr. Memory | Windows
Additionally it is recommended to use static analysis tools to detect undefined behaviour - but again, they are a tool merely to help you find undefined behaviour, and they don't guarantee to find all occurrences of undefined behaviour.
If you are really unlucky however, using a debugger (or, more rarely, just recompiling with debug information) may influence the program's code and memory sufficiently that the segfault no longer occurs, a phenomenon known as a heisenbug.
In such cases, what you may want to do is to obtain a core dump, and get a backtrace using your debugger.
*
*How to generate a core dump in Linux on a segmentation fault?
*How do I analyse a program's core dump file with GDB when it has command-line parameters?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33047452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "72"
}
|
Q: Deploy Play 2.1 RC1 Java Application to Heroku Got 'NoSuchMethodError scala.Predef$.augmentString' This application was migrated from Play 2.0.4. to 2.1-RC1. When push to heroku, I got this error from heroku logs. Should I use a different build pack for Play 2.1?
2012-12-11T03:04:36+00:00 heroku[web.1]: Starting process with command `target/start -Dhttp.port=${PORT} -Dconfig.resource=prod.conf ${JAVA_OPTS}`
2012-12-11T03:04:38+00:00 app[web.1]: Exception in thread "main" java.lang.NoSuchMethodError: scala.Predef$.augmentString(Ljava/lang/String;)Lscala/collection/immutable/StringOps;
2012-12-11T03:04:38+00:00 app[web.1]: at play.core.server.NettyServer$.createServer(NettyServer.scala:111)
2012-12-11T03:04:38+00:00 app[web.1]: at play.core.server.NettyServer$$anonfun$main$5.apply(NettyServer.scala:153)
2012-12-11T03:04:38+00:00 app[web.1]: at play.core.server.NettyServer$$anonfun$main$5.apply(NettyServer.scala:152)
2012-12-11T03:04:38+00:00 app[web.1]: at scala.Option.map(Option.scala:145)
2012-12-11T03:04:38+00:00 app[web.1]: at play.core.server.NettyServer$.main(NettyServer.scala:152)
2012-12-11T03:04:38+00:00 app[web.1]: at play.core.server.NettyServer.main(NettyServer.scala)
Here is my Build.scala.
val appDependencies = Seq(
javaCore, javaJdbc, javaEbean,
"org.webjars" % "bootstrap" % "2.1.1",
"postgresql" % "postgresql" % "9.1-901-1.jdbc4",
"rome" % "rome" % "1.0",
"com.typesafe" %% "play-plugins-mailer" % "2.1-SNAPSHOT",
"commons-codec" % "commons-codec" % "1.6",
"commons-io" % "commons-io" % "2.3",
"com.typesafe" % "play-plugins-inject" % "2.0.2",
"com.typesafe" %% "play-plugins-mailer" % "2.1-SNAPSHOT",
"com.typesafe.akka" % "akka-testkit" % "2.0.2",
"org.imgscalr" % "imgscalr-lib" % "4.2",
"org.codehaus.jackson" % "jackson-jaxrs" % "1.9.5",
"org.codehaus.jackson" % "jackson-xc" % "1.9.5",
"org.codehaus.jackson" % "jackson-mapper-asl" % "1.9.5",
"org.codehaus.jackson" % "jackson-core-asl" % "1.9.5",
"org.mindrot" % "jbcrypt" % "0.3m"
)
val main = play.Project(appName, appVersion, appDependencies).settings(
resolvers += "webjars" at "http://webjars.github.com/m2",
resolvers += "Mave2" at "http://repo1.maven.org/maven2",
resolvers += "jets3t" at "http://www.jets3t.org/maven2",
resolvers += "Typesafe Releases Repository" at "http://repo.typesafe.com/typesafe/releases/",
resolvers += "Typesafe Snapshots Repository" at "http://repo.typesafe.com/typesafe/snapshots/",
resolvers += Resolver.url("Typesafe Ivy Snapshots", url("http://repo.typesafe.com/typesafe/ivy-snapshots/"))(Resolver.ivyStylePatterns),
resolvers += "Daniel's Repository" at "http://danieldietrich.net/repository/snapshots/"
)
A: For my case, I have to remove this dependency from build.scala
"com.typesafe" % "play-plugins-inject" % "2.0.2"
and remove plugin from play.plugins.
1500:com.typesafe.plugin.inject.ManualInjectionPlugin
This plugin brings in play_2.9 which has dependency on ehcache and causes play to initialize play's cache second time while play_2.10 from Play 2.1 has initialized it already.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13813078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: multiple database access from one application I am working on a C# application with SQL Server 2008. I have two different databases. I will be selecting the database name from the drop down list at login time.
When I'm inserting 5 rows into the table, that time 3 rows are inserted in the table of the database which I have selected at login time and 2 rows are inserted in another database.
We've checked the connection string and it is correct and it takes the selected database.
So here I am not understanding why database is changing at insertion time.
This is my insertion code.
SqlConnection _con = new SqlConnection(connection);
_con.Open();
SqlCommand cmd = new SqlCommand("insert into " + Tablename + "(" + ColumnNames + ")" + " values (" + Values + ")", _con);
cmd.ExecuteNonQuery();
_con.Close();
Dtb = "";
Here is the example about problem.
I am accessing application and doing interaction with database 'A' from one system.
same time I am accessing application and doing interaction with database 'B' from another system.
That time data is overloading like this A <-> B.
Means data from A is reflecting to B.(Nw both database is logged in application.)
A: Try not to create a connection instance ( like new sqlconnection) for each insertion. better loop 3 insertions with a same connection string/variable you already created.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29540277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Camera View Corner Borders In Css This is question not more specific. I want to so common, because most of the web developers have this problem.
We all know the camera view which has border in 4 corners but not in the right/left/bottom/top.
How can we make this effect using css?
html
<div id="div1" />
<div id="div2" />
css
#div1 {
position:absolute;
top:9px;
left:9px;
height:100px;
width:100px;
background-color:white;
border:1px solid black;
}
#div2 {
position:relative;
top:-1px;
left:-1px;
height:102px;
width:102px;
background-color:white;
border-radius: 15px;
}
I achieved it like this.Now I want to know how can achieve this using only one div
A: You should use parent->child logic
For example :
<div class="parent"><div class="child"></div></div>
EXAMPLE :
Codepen
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51646033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why javax.servlet package is distributed only as part of application servers? I'm not new to servlets. But I'm still curious: why javax.servlet package isn't distributed on its own? Why I need some application server installed before I can compile my code?
A: Short answer, it is distributed separately.
Servlets are a specification and an API. If you want the JAR, download it from the spec site Servlet Spec 3.0.
Obviously if you want to actually deploy your application, you'll still need an implementation (i.e. a server).
A: The servlet API is available through some jar and you can do with it what you want. On maven it is here. You can compile the code without any application server but it probably won't do what you want. It is only an interface afterall
Servlets are only really relevant in the context of a Web Application and this is why Servlet Containers exist. They are the implementation. Take a look at all the work the container does before a request reaches the servlet: Tomcat Sequence Diagram.
A: Servlets like other Java EE technology like EJB are Specification from JSR(Java Specification Requests) from Java Community Process Program
The onus is on the Application Server vendor to provide the implementation based on the specifications released.In this case
- for Servlet 2.5
- for Servlet 3.0
Sun / now Oracle does release the javax.servlet package separately and you can download it from Maven Repository also its available within the lib folder of any J2ee complaint application server/web container .
i.e for Tomcat its available in TOMCAT_HOMEDIR/lib/servlet-api
So for developing and compiling , this jar is sufficient , you would only need the Application server only when you want to actually deploy your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14967338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WPF - databinding controls in UserControl to class members within the same UC (C#) How can I databind the controls within my usercontrol to a class instance within the same UserControl in WPF/C#?
For example if I move the slider the value of a certain class member should update. If I change the class or some value within it it should change in the UserControl.
More general question: What is the easiest way to create UserControl that edits and loads public fields of one class?
Edit:
Usercontrol
public partial class ThresholdingSettingsUC : UserControl
{
public ThresholdingSettings Settings { get; set; }
public ThresholdingSettingsUC ()
{
InitializeComponent ();
}
}
xaml
<UserControl x:Class="ColonyCounterApp.ThresholdingSettingsUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="300"
>
<Grid>
<DockPanel HorizontalAlignment="Left" Name="dockPanel1" VerticalAlignment="Top" Width="300">
<GroupBox Header="Hue filter" Height="150" Name="gbHue" DockPanel.Dock="Top">
<Grid>
<CheckBox Content="Use hue filtering" Height="16" HorizontalAlignment="Left" Margin="6,6,0,0" Name="cbHue" VerticalAlignment="Top" />
</Grid>
</GroupBox/>
</DockPanel>
</Grid>
</UserControl>
Class that should be bound to the control
public struct ThresholdingSettings:INotifyPropertyChanged
{
/// <summary>
///
/// </summary>
public bool FilterHue {
get
{ return filterHue; }
set
{
if (filterHue==value)
{
return;
}
filterHue = value;
OnPropertyChanged ("FilterHue"); }
}
private bool filterHue;
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void OnPropertyChanged (string propertyName)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h (this, new PropertyChangedEventArgs (propertyName));
}
}
}
A: You could use ElementName (I'm assuming you mean members on the user control itself).
class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public int Value { get; set; }
}
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
Name="myUserControl"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Slider Value="{Binding Value, ElementName=myUserControl}" />
</Grid>
</UserControl>
A: You could set the class instance as the DataContext of your userControl and use the default bind mechanism with a relative Path.
To support two way binding (class updates UI, UI updates class) the class should implement INotifyPropertyChanged (or have the specified properties defined as DependencyProperty).
If you cant alter the Class code, you'll need to expose the required properties in the UserControl and invoke it's PropertyChanged event (to allow the UI to update) and update the instance with the new value
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6812783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cannot view code in Azure portal for function created / deployed via Visual Studio, yet I can when I make the function via the portal I have an Azure function that I created in the Azure portal. I added a timer function and some dummy code and it works fine; I created and wrote the code in browser - let's call this FunctionA.
I then created a new project (FunctionB) in Visual Studio 2017, added a new timer function and published it to the same Azure function mentioned before. Interestingly, when I go to the portal I can still FunctionA's code, but for FunctionB all I see is the local.settings.json file - no code is visible.
I then get this message at the top:
Your app is currently in read-only mode because you have published a
generated function.json. Changes made to function.json will not be
honored by the Functions runtime
I think this means the local.settings.json file in my VS2017 project has somehow made it readonly, but it doesn't explain why I can't even see the code in the Azure portal, let alone edit it.
Here is the code for FunctionB:
namespace DemoAzureFunction
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([TimerTrigger("0 0 5 * * *")]TimerInfo myTimer, TraceWriter log)
{
log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
}
}
}
The inbrowser code editing / viewing is a very cool feature. Even when I edit the default local.settings.json file and publish it makes no difference.
A: It's by design. Changing code does not make sense for VS created functions (precompiled functions) as your code already compiled to dll.
if you take a look on kudu (https://{your-function-app-name}.scm.azurewebsites.net/DebugConsole) you will see that folder stracture is different for portal and VS created functions.
More info about portal and VS created functions:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library
https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48798453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: add values from list to another list I am trying to add values from ListArray coords to the ListArray linhasCoords but the linhasCoords doesn't get all values.
My point is, for each ID, save all the coordinates Lat and Long.
My code: http://pastebin.com/P2k82wQ3
public HashMap<Integer, ArrayList<LatLong>> load_RoadAxis() {
HashMap<Integer,ArrayList<LatLong>> linhasCoords = new HashMap<Integer, ArrayList<LatLong>>();
ArrayList<LatLong> coords = new ArrayList<LatLong>();
int idAtual = 0;
int idAnterior = 1;
String query = "SELECT y, x, linha2 FROM trechos_pontos WHERE linha2 <5 ORDER BY linha2, path ";
try {
Stmt stmt = db.prepare(query);
while (stmt.step()) {
Double x = stmt.column_double(0);
Double y = stmt.column_double(1);
//Log.d("TRECHOS", "idAtual: " + idAtual + "X: " + x.toString() + " Y: " + y.toString());
idAtual = stmt.column_int(2);
Log.d("TRECHOS", "idAtual: " + idAtual + " idAnterior: " + idAnterior);
if (idAtual == idAnterior) {
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " Coords: " + coords);
} else {
linhasCoords.put(idAnterior,coords);
idAnterior = idAtual;
coords.clear();
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " LinhasCoords: " + linhasCoords);
}
}
stmt.close();
} catch (Exception e) {
e.printStackTrace();
Log.d("TRECHOS", "A consulta dos trechos falhou");
}
//Log.d("TRECHOS", linhasCoords.toString());
return linhasCoords;
}
A part of my logs: http://pastebin.com/pDUat9CL
D/TRECHOS(21428): idAtual: 1 idAnterior: 1
D/TRECHOS(21428): Coords: [latitude=43.5922273767277, longitude=1.44029380540736]
D/TRECHOS(21428): idAtual: 1 idAnterior: 1
D/TRECHOS(21428): Coords: [latitude=43.5922273767277, longitude=1.44029380540736, latitude=43.5922136050099, longitude=1.44047259717341]
D/TRECHOS(21428): idAtual: 2 idAnterior: 1
D/TRECHOS(21428): LinhasCoords: {1=[latitude=43.5925479521396, longitude=1.4365973553446]}
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003, latitude=43.5922914378148, longitude=1.43956435379756]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003, latitude=43.5922914378148, longitude=1.43956435379756, latitude=43.5923036302806, longitude=1.43941791555995]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003, latitude=43.5922914378148, longitude=1.43956435379756, latitude=43.5923036302806, longitude=1.43941791555995, latitude=43.5923244338855, longitude=1.43916026189481]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003, latitude=43.5922914378148, longitude=1.43956435379756, latitude=43.5923036302806, longitude=1.43941791555995, latitude=43.5923244338855, longitude=1.43916026189481, latitude=43.5923490976508, longitude=1.43888705045567]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003, latitude=43.5922914378148, longitude=1.43956435379756, latitude=43.5923036302806, longitude=1.43941791555995, latitude=43.5923244338855, longitude=1.43916026189481, latitude=43.5923490976508, longitude=1.43888705045567, latitude=43.592377137392, longitude=1.4385645839831]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003, latitude=43.5922914378148, longitude=1.43956435379756, latitude=43.5923036302806, longitude=1.43941791555995, latitude=43.5923244338855, longitude=1.43916026189481, latitude=43.5923490976508, longitude=1.43888705045567, latitude=43.592377137392, longitude=1.4385645839831, latitude=43.5924023567609, longitude=1.43825904413027]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003, latitude=43.5922914378148, longitude=1.43956435379756, latitude=43.5923036302806, longitude=1.43941791555995, latitude=43.5923244338855, longitude=1.43916026189481, latitude=43.5923490976508, longitude=1.43888705045567, latitude=43.592377137392, longitude=1.4385645839831, latitude=43.5924023567609, longitude=1.43825904413027, latitude=43.5924486368068, longitude=1.43771410203014]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003, latitude=43.5922914378148, longitude=1.43956435379756, latitude=43.5923036302806, longitude=1.43941791555995, latitude=43.5923244338855, longitude=1.43916026189481, latitude=43.5923490976508, longitude=1.43888705045567, latitude=43.592377137392, longitude=1.4385645839831, latitude=43.5924023567609, longitude=1.43825904413027, latitude=43.5924486368068, longitude=1.43771410203014, latitude=43.5924671434473, longitude=1.4375098967783]
D/TRECHOS(21428): idAtual: 2 idAnterior: 2
D/TRECHOS(21428): Coords: [latitude=43.5925479521396, longitude=1.4365973553446, latitude=43.5926291677532, longitude=1.43564264638214, latitude=43.5926625330203, longitude=1.43526523586817, latitude=43.5926642101564, longitude=1.43523990190003, latitude=43.5922914378148, longitude=1.43956435379756, latitude=43.5923036302806, longitude=1.43941791555995, latitude=43.5923244338855, longitude=1.43916026189481, latitude=43.5923490976508, longitude=1.43888705045567, latitude=43.592377137392, longitude=1.4385645839831, latitude=43.5924023567609, longitude=1.43825904413027, latitude=43.5924486368068, longitude=1.43771410203014, latitude=43.5924671434473, longitude=1.4375098967783, latitude=43.5925346838359, longitude=1.43673959999082]
D/TRECHOS(21428): idAtual: 3 idAnterior: 2
D/TRECHOS(21428): LinhasCoords: {1=[latitude=43.5921680888747, longitude=1.44100065185853], 2=[latitude=43.5921680888747, longitude=1.44100065185853]}
D/TRECHOS(21428): idAtual: 3 idAnterior: 3
D/TRECHOS(21428): Coords: [latitude=43.5921680888747, longitude=1.44100065185853, latitude=43.592147899421, longitude=1.4412301885968]
D/TRECHOS(21428): idAtual: 3 idAnterior: 3
D/TRECHOS(21428): Coords: [latitude=43.5921680888747, longitude=1.44100065185853, latitude=43.592147899421, longitude=1.4412301885968, latitude=43.5921435012598, longitude=1.44127947779876]
D/TRECHOS(21428): idAtual: 3 idAnterior: 3
D/TRECHOS(21428): Coords: [latitude=43.5921680888747, longitude=1.44100065185853, latitude=43.592147899421, longitude=1.4412301885968, latitude=43.5921435012598, longitude=1.44127947779876, latitude=43.5921339259824, longitude=1.44139493077248]
D/TRECHOS(21428): idAtual: 4 idAnterior: 3
D/TRECHOS(21428): LinhasCoords: {1=[latitude=43.5922136050099, longitude=1.44047259717341], 2=[latitude=43.5922136050099, longitude=1.44047259717341], 3=[latitude=43.5922136050099, longitude=1.44047259717341]}
D/TRECHOS(21428): idAtual: 4 idAnterior: 4
D/TRECHOS(21428): Coords: [latitude=43.5922136050099, longitude=1.44047259717341, latitude=43.5922090466017, longitude=1.44051065409724]
D/TRECHOS(21428): idAtual: 4 idAnterior: 4
D/TRECHOS(21428): Coords: [latitude=43.5922136050099, longitude=1.44047259717341, latitude=43.5922090466017, longitude=1.44051065409724, latitude=43.5922038095384, longitude=1.44057260588265]
D/TRECHOS(21428): idAtual: 4 idAnterior: 4
D/TRECHOS(21428): Coords: [latitude=43.5922136050099, longitude=1.44047259717341, latitude=43.5922090466017, longitude=1.44051065409724, latitude=43.5922038095384, longitude=1.44057260588265, latitude=43.592196812945, longitude=1.4406542751152]
D/TRECHOS(21428): idAtual: 4 idAnterior: 4
D/TRECHOS(21428): Coords: [latitude=43.5922136050099, longitude=1.44047259717341, latitude=43.5922090466017, longitude=1.44051065409724, latitude=43.5922038095384, longitude=1.44057260588265, latitude=43.592196812945, longitude=1.4406542751152, latitude=43.5921951761103, longitude=1.44068241680208]
You can see that linhasCoords doesn't have all the values and its generated before coords, and I doesn't know why.
A: if (idAtual == idAnterior) {
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " Coords: " + coords);
} else {
linhasCoords.put(idAnterior,coords);
idAnterior = idAtual;
coords.clear();
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " LinhasCoords: " + linhasCoords);
}
So if idAtual is equal to idAnterior it wont be added to linhasCoords, only to coords.
Replace it with this:
if (idAtual == idAnterior) {
linhasCoords.put(idAnterior,coords);
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " Coords: " + coords);
} else {
linhasCoords.put(idAnterior,coords);
idAnterior = idAtual;
coords.clear();
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " LinhasCoords: " + linhasCoords);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23371907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Convert Object properties into their own objects possible? Let's say I'm pulling some JSON data:
[{"a": "1", "b": "2", "c": "3"}]
Is it possible to convert the above to:
[{"a": "1"}, {"b": "2"}, {"c": "3"}]
How can this be achieved in JS? Thanks in advance.
A: Assuming:
var myObj = [{"a": "1", "b": "2", "c": "3"}];
Then, you can do this:
var result = []; // output array
for(key in myObj[0]){ // loop through the object
if(myObj[0].hasOwnProperty(key)){ // if the current key isn't a prototype property
var temp = {}; // create a temp object
temp[key] = myObj[0][key]; // Assign the value to the temp object
result.push(temp); // And add the object to the output array
}
}
console.log(result);
// [{"a": "1"}, {"b": "2"}, {"c": "3"}]
A: You can grab the object keys and loop over the objects with map:
var newArr = Object.keys(arr[0]).map(function (key) {
var obj = {};
obj[key] = arr[0][key];
return obj;
});
DEMO
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26255867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: python3.9 pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 61] Connection refused)") pls tell me how to deal with the problem
import pymysql
conn = pymysql.connect(host='localhost',port=3306,user ='root',password ='123456',database ='account',charset ='utf8')
cursor = conn.cursor()
cursor.execute('show databases;')
for x in cursor:
print (x)
cursor.close()
conn.close()
[run result]
File "/Users/user/Library/Python/3.9/lib/python/site-packages/pymysql/connections.py", line 353, in init
self.connect()
File "/Users/user/Library/Python/3.9/lib/python/site-packages/pymysql/connections.py", line 664, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 61] Connection refused)")
mysql version is mysql-8.0.28-macos11-x86_64
localhost change to 127.0.0.1 , is also not ok~~
but the same params is ok in navicat expect for
the config 'use socket file : /tmp/mysql.sock'~~
enter image description here
in navicat , if i do not check the socket option ,i receive the same problem as python code above
expect to link mysql succesfully , thx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71600650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Grails many-to-many and one-to-one with belongsTo I'm trying to achieve the following with Grails / Gorm:
Some users are lecturers. Several users can be assistants for several lecturers and several lecturers can have several assistants.
I'm trying to add an additional many-to-many relation to the existing one-to-one relation between User and Lecturer but keep the belongsTo.
This is what I had before:
class User {
...
Lecturer lecturer
}
class Lecturer {
...
static belongsTo = [user:User]
}
Then I added the many-to-many relationship:
class User {
...
Lecturer lecturer
static hasMany = [lecturers: Lecturer]
}
class Lecturer {
static belongsTo = [user:User, assistants:User]
static hasMany = [assistants: User]
}
I get three tables:
user:
------------------------------
| id | .. | lecturer_id | .. |
------------------------------
lecturer:
-----------
| id | .. |
-----------
user_lecturer:
-----------------------------------
| user_lecturers_id | lecturer_id |
-----------------------------------
When I now call lecturer.assistants on a Lecturer without an assistant, I will get one user. This is not correct, because the table is empty. So, I guess the relation is interpreted as one-to-many and is giving me the user where the lecturer_id matches.
What will do the trick? (mappedBy ?)
Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43258158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R how to reference a dynamically created object I have the following R code which creates 5 objects dynamically with names such as cluster1_dataset, ...., cluster5_dataset as follows:
# Extract cluster data
for (i in 1:K) {
assign(paste("cluster",i,"_dataset",sep=""), subset(clustered_input_dataset, cluster == i))
}
How do i access these 5 dynamically created objects in R?
I have tried the following:
# Plot histograms & boxplots for each cluster to look at shift_length_avg frequency distribution
par(mfrow=c(K,2))
for (i in 1:K) {
# Analyze cluster#1
hist(dataset$shift_length_avg)
}
which gives me the following error:
Error in dataset$shift_length_avg :
$ operator is invalid for atomic vectors
A: The assign() function has a twin called get(). This is the function that you need.
Refer to this concise and easy-to-understand article here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34403654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to check ID element via tagname? How I can get the ID of an element selected via getElementsByTagName? I want to check elements' IDs that are <img> elements.
A: You can access all element's attributes
document.getElementsByTagName("td")[0].id // returns the id attribute
document.getElementsByTagName("td")[0].style // returns the style attribute
You can access to the id directly with:
document.getElementById("myIdentifier") // returns the entire object
A: You can use .id. For example if I had the HTML:
<p id="test"></p>
You can get the id attribute by doing:
document.getElementsByTagName("p")[0].id;
A: Here is an exemple:
<html>
<head>
<script>
function getElements()
{
var x=document.getElementsByTagName("input");
alert(x[0].id);
}
</script>
</head>
<body>
<input id="hi" type="text" size="20"><br>
<input type="text" size="20"><br>
<input type="text" size="20"><br><br>
<input type="button" onclick="getElements()" value="What is the ID for the first element?">
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33131488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: My grid quickly disappears on page load due to incorrect force being applied? So I'm recreating the warping grid from Geometry Wars in a web page to further test my skills with JavaScript and I've hit another snag. I'm following a tutorial written in C# over on TutsPlus that I used a long time ago to recreate it while learning XNA Framework. The tutorial is straight forward, and most of the code is self-explanatory, but I think my lack of superior education in mathematics is letting me down once again.
I've successfully rendered the grid in a 300x300 canvas with no troubles, and even replicated all of the code in the tutorial, but since they're using the XNA Framework libraries, they have the advantage of not having to write the mathematical functions of the Vector3 type. I've implemented only what I need, but I believe I may have gotten my math incorrect or perhaps the implementation.
The initial grid (above) should look like this until I begin interacting with it, and it does, as long as I disable the Update function of my Grid. I've stepped through the code and the issue seems to be related to my calculation for the magnitude of my vectors. The XNA Framework libraries always called it Length and LengthSquared, but each Google search I performed was returning results for calculating magnitude as:
Now, this is incredibly simple to recreate in code, and my Vector3 class accounts for Magnitude and MagnitudeSquared since the tutorial calls for both. I've compared the results of my magnitude calculation to that of an online calculator and the results were the same:
V = (2, 3, 4)
|V| = 5.385164807134504
To top this off, the URL for this calculator says that I'm calculating the length of the vector. This is what leads me to believe that it may be my implementation here that is causing the whole thing to go crazy. I've included my snippet below, and it is unfortunately a bit long, but I assure you it has been trimmed as much as possible.
class Vector3 {
constructor(x, y, z) {
this.X = x;
this.Y = y;
this.Z = z;
}
Add(val) {
this.X += val.X;
this.Y += val.Y;
this.Z += val.Z;
}
Subtract(val) {
this.X -= val.X;
this.Y -= val.Y;
this.Z -= val.Z;
}
MultiplyByScalar(val) {
let result = new Vector3(0, 0, 0);
result.X = this.X * val;
result.Y = this.Y * val;
result.Z = this.Z * val;
return result;
}
DivideByScalar(val) {
let result = new Vector3(0, 0, 0);
result.X = this.X / val;
result.Y = this.Y / val;
result.Z = this.Z / val;
return result;
}
Magnitude() {
if (this.X == 0 && this.Y == 0 && this.Z == 0)
return 0;
return Math.sqrt(Math.pow(this.X, 2) +
Math.pow(this.Y, 2) +
Math.pow(this.Z, 2));
}
MagnitudeSquared() {
return Math.pow(this.Magnitude(), 2);
}
DistanceFrom(to) {
let x = Math.pow(this.X - to.X, 2);
let y = Math.pow(this.Y - to.Y, 2);
let z = Math.pow(this.Z - to.Z, 2);
return Math.sqrt(x + y + z);
}
}
class PointMass {
Acceleration = new Vector3(0, 0, 0);
Velocity = new Vector3(0, 0, 0);
Damping = 0.95;
constructor(position, inverseMass) {
this.Position = position;
this.InverseMass = inverseMass;
}
IncreaseDamping(factor) {
this.Damping *= factor;
}
ApplyForce(force) {
this.Acceleration.Add(force.MultiplyByScalar(this.InverseMass));
}
Update() {
this.Velocity.Add(this.Acceleration);
this.Position.Add(this.Velocity);
this.Acceleration = new Vector3(0, 0, 0);
if (this.Velocity.MagnitudeSquared() < 0.001 * 0.001)
Velocity = new Vector3(0, 0, 0);
this.Velocity.MultiplyByScalar(this.Damping);
this.Damping = 0.95;
}
}
class Spring {
constructor(startPoint, endPoint, stiffness, damping) {
this.StartPoint = startPoint;
this.EndPoint = endPoint;
this.Stiffness = stiffness;
this.Damping = damping;
this.TargetLength = startPoint.Position.DistanceFrom(endPoint.Position) * 0.95;
}
Update() {
let x = this.StartPoint.Position;
x.Subtract(this.EndPoint.Position);
let magnitude = x.Magnitude();
if (magnitude < this.TargetLength || magnitude == 0)
return;
x = x.DivideByScalar(magnitude).MultiplyByScalar(magnitude - this.TargetLength);
let dv = this.EndPoint.Velocity;
dv.Subtract(this.StartPoint.Velocity);
let force = x.MultiplyByScalar(this.Stiffness)
force.Subtract(dv.MultiplyByScalar(this.Damping));
this.StartPoint.ApplyForce(force);
this.EndPoint.ApplyForce(force);
}
}
class Grid {
Springs = [];
Points = [];
constructor(containerID, spacing) {
this.Container = document.getElementById(containerID);
this.Width = this.Container.width;
this.Height = this.Container.height;
this.ColumnCount = this.Width / spacing + 1;
this.RowCount = this.Height / spacing + 1;
let columns = [];
let fixedColumns = [];
let rows = [];
let fixedRows = [];
let fixedPoints = [];
for (let y = 0; y < this.Height; y += spacing) {
for (let x = 0; x < this.Width; x += spacing) {
columns.push(new PointMass(new Vector3(x, y, 0), 1));
fixedColumns.push(new PointMass(new Vector3(x, y, 0), 0));
}
rows.push(columns);
fixedRows.push(fixedColumns);
columns = [];
fixedColumns = [];
}
this.Points = rows;
for (let y = 0; y < rows.length; y++) {
for (let x = 0; x < rows[y].length; x++) {
if (x == 0 || y == 0 || x == rows.length - 1 || x == rows[y].length - 1)
this.Springs.push(new Spring(fixedRows[x][y], this.Points[x][y], 0.1, 0.1));
else if (x % 3 == 0 && y % 3 == 0)
this.Springs.push(new Spring(fixedRows[x][y], this.Points[x][y], 0.002, 0.002));
const stiffness = 0.28;
const damping = 0.06;
if (x > 0)
this.Springs.push(new Spring(this.Points[x - 1][y], this.Points[x][y], stiffness, damping));
if (y > 0)
this.Springs.push(new Spring(this.Points[x][y - 1], this.Points[x][y], stiffness, damping));
}
}
}
ApplyDirectedForce(force, position, radius) {
this.Points.forEach(function(row) {
row.forEach(function(point) {
if (point.Position.DistanceFrom(position) < Math.pow(radius, 2))
point.ApplyForce(force.MultiplyByScalar(10).DivideByScalar(10 + point.Position.DistanceFrom(position)));
});
});
}
ApplyImplosiveForce(force, position, radius) {
this.Points.forEach(function(point) {
let distance_squared = Math.pow(point.Position.DistanceFrom(position));
if (distance_squared < Math.pow(radius, 2)) {
point.ApplyForce(force.MultiplyByScalar(10).Multiply(position.Subtract(point.Position)).DivideByScalar(100 + distance_squared));
point.IncreaseDamping(0.6);
}
});
}
ApplyExplosiveForce(force, position, radius) {
this.Points.forEach(function(point) {
let distance_squared = Math.pow(point.Position.DistanceFrom(position));
if (distance_squared < Math.pow(radius, 2)) {
point.ApplyForce(force.MultiplyByScalar(100).Multiply(point.Position.Subtract(position)).DivideByScalar(10000 + distance_squared));
point.IncreaseDamping(0.6);
}
});
}
Update() {
this.Springs.forEach(function(spring) {
spring.Update();
});
this.Points.forEach(function(row) {
row.forEach(function(point) {
point.Update();
});
});
}
Draw() {
const context = this.Container.getContext('2d');
context.clearRect(0, 0, this.Width, this.Height);
context.strokeStyle = "#ffffff";
context.fillStyle = "#ffffff";
for (let y = 1; y < this.Points.length; y++) {
for (let x = 1; x < this.Points[y].length; x++) {
let left = new Vector3(0, 0, 0);
let up = new Vector3(0, 0, 0);
if (x > 1) {
left = this.Points[x - 1][y].Position;
context.beginPath();
context.moveTo(left.X, left.Y);
context.lineTo(this.Points[x][y].Position.X, this.Points[x][y].Position.Y);
context.stroke();
}
if (y > 1) {
up = this.Points[x][y - 1].Position;
context.beginPath();
context.moveTo(up.X, up.Y);
context.lineTo(this.Points[x][y].Position.X, this.Points[x][y].Position.Y);
context.stroke();
}
let radius = 3;
if (y % 3 == 1)
radius = 5;
context.beginPath();
context.arc(this.Points[x][y].Position.X, this.Points[x][y].Position.Y, radius, 0, 2 * Math.PI);
context.fill();
}
}
}
}
var grid = new Grid("grid", 40);
setInterval(function() {
grid.Update();
grid.Draw();
}, 5);
var mouseX = 0;
var mouseY = 0;
function updateMouseCoordinates(evt) {
var rect = grid.Container.getBoundingClientRect();
mouseX = evt.clientX - rect.left;
mouseY = evt.clientY - rect.top;
const context = grid.Container.getContext('2d');
context.clearRect(0, 0, this.Width, this.Height);
context.strokeStyle = "#ffffff";
context.fillStyle = "#ff3333";
context.beginPath();
context.arc(mouseX, mouseY, 15, 0, 2 * Math.PI);
context.fill();
grid.ApplyDirectedForce(new Vector3(0, 0, 5000), new Vector3(mouseX, mouseY, 0), 50);
}
html,
body {
margin: 0;
height: 100%;
background: #213;
background: linear-gradient(45deg, #213, #c13);
background: -webkit-linear-gradient(45deg, #213, #c13);
}
.container {
position: relative;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
<div class="container">
<canvas onmousemove="updateMouseCoordinates(event)" id="grid" class="grid" width="300" height="300"></canvas>
</div>
I believe the issue has something to do with the Update method in the Spring and PointMass classes as when I stepped through my code, I kept finding that the PointMass objects seemed to have acceleration when they shouldn't (as in, I haven't interacted with them yet). In all honesty, I think it's the implementation of my custom Vector3 functions in those update functions that are causing the issue but for the life of me, I can't figure out what I've done incorrectly here.
Perhaps I just need to take a break and come back to it, but I'm hoping someone here can help spot an incorrect implementation.
How do I prevent my grid from immediately dissipating due to forces that have not yet been exerted (as in they are just miscalculations)?
A: My advice is reduce the problem down. Have only a single point, slow the interval down, step through to see what's happening. The mouse doesn't appear to be doing anything. Commenting out the line grid.ApplyDirectedForce(new Vector3(0, 0, 5000), new Vector3(mouseX, mouseY, 0), 50); doesn't change the output. It goes wrong in grid.Update(), for some reason grid.Update() does something even if there's no force applied, maybe that means the spring code has a bug. The bottom right point doesn't move frame one maybe that means something. The debugger is your friend. Add a breakpoint to grid.Update() and see what the code is actually doing. I know this isn't a direct answer but I hope this guides you in the right direction.
I also want to point out that usually the whole point of Magnitude Squared is so that you can compare vectors or distances without having to do a square root operation. That is, in your Magnitude function you do a Square root operation and then in your Magnitude Squared function you square it. This is is the same as simply going x^2 + y^2 + z^2
frame 1:
frame 2:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58033180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL to return list of years since a specific year I need a list of years as a recordset starting with 2004 to current year (in desc order), without writing a stored procedure. Is this possible? (SQL Server 2005). So it should return:
2009
2008
2007
2006
2005
2004
A: Updated to return current year plus previous 5 years. Should be very fast as this is a small recordset.
SELECT YEAR(GETDATE()) as YearNum
UNION
SELECT YEAR(GETDATE()) - 1 as YearNum
UNION
SELECT YEAR(GETDATE()) - 2 as YearNum
UNION
SELECT YEAR(GETDATE()) - 3 as YearNum
UNION
SELECT YEAR(GETDATE()) - 4 as YearNum
UNION
SELECT YEAR(GETDATE()) - 5 as YearNum
ORDER BY YearNum DESC
A: This gets all years from 2004 to the present, using a recursive CTE:
with yearlist as
(
select 2004 as year
union all
select yl.year + 1 as year
from yearlist yl
where yl.year + 1 <= YEAR(GetDate())
)
select year from yearlist order by year desc;
A: Using ROW_NUMBER on any column from any large enough (stable) table would be one way to do it.
SELECT *
FROM (
SELECT TOP 100 2003 + ROW_NUMBER() OVER (ORDER BY <AnyColumn>) AS Yr
FROM dbo.<AnyTable>
) Years
WHERE Yr <= YEAR(GETDATE())
Note that <AnyTable> should contain at least the amount of rows equal to the amount of years you require.
Edit (Cudo's to Joshua)
*
*Preferably, you'd select a table wich you know will not get truncated and/or deleted. A large enough system table should come to mind.
*At present, being a lot older and wiser (older at least), I would implement this requirement using a CTE like mentioned in the answer given by Joshua. The CTE technique is far superior and less error prone than current given ROW_NUMBER solution.
A: DECLARE @YEARS TABLE (Y INT)
DECLARE @I INT, @NY INT
SELECT @I = 2004, @NY = YEAR(GETDATE())
WHILE @I <= @NY BEGIN
INSERT @YEARS SELECT @I
SET @I = @I + 1
END
SELECT Y
FROM @YEARS
ORDER BY Y DESC
A: Try this:
declare @lowyear int
set @lowyear = 2004
declare @thisyear int
set @thisyear = year(getdate())
while @thisyear >= @lowyear
begin
print @thisyear
set @thisyear = (@thisyear - 1)
end
Returns
2009
2008
2007
2006
2005
2004
When you hit Jan 1, 2010. The same code will return:
2010
2009
2008
2007
2006
2005
2004
A: WITH n(n) AS
(
SELECT 0
UNION ALL
SELECT n+1 FROM n WHERE n < 10
)
SELECT year(DATEADD( YY, -n, GetDate()))
FROM n ORDER BY n
A: My two cents:
The CTE is the best answer but I like @Lieven Keersmaekers answer as it doesn’t rely on recursion/loops or creating additional objects such as functions/date-tables. The key variation is mine simply uses the Top clause with an expression, instead of the top 100 (basically the whole table) I ask for N number of unordered rows first. This is quicker, if your base table happens to be quite large.
Tested on SQL Server 2016
DECLARE @startYear smallint;
SET @startYear = 2004;
DECLARE @endYear smallint;
SET @endYear = YEAR(GETDATE());
-- Top uses expression to bring in N number of rows. The (@startYear - 1) is to retain the start year
SELECT [Yr]
FROM (
SELECT TOP (@endYear - (@startYear - 1))
COUNT([object_id]) OVER (ORDER BY [object_id] DESC) + (@startYear - 1) AS [Yr] -- Add initial start year to Count
FROM sys.all_objects
) AS T1
ORDER BY [Yr] DESC
The comments above are valid, but Since OP’s requirements is literally a small set of values from 2004, the sys.all_objects will suffice, as SQL Server install comes with a ton of system objects.
Hope that's a different take.
A: I think you need to create a dates table, then just select your range from it. It can also come in useful when you need to select a date range with X data attached and not have any missed days.
A: SET NOCOUNT ON
DECLARE @max int
set @max = DATEPART(year, getdate())
CREATE TABLE #temp (val int)
while @max >= 2004
BEGIN
insert #temp(val) values(@max)
set @max = @max - 1
END
SELECT * from #temp
A: This is a simple query, check this
(SELECT REPLACE((TO_CHAR(SYSDATE,'YYYY')-Rownum)+1,' ',NULL) yr FROM dual CONNECT BY LEVEL < 32) year
A: Recursive CTE with no variables is a simpler way to go...
WITH Years AS (
SELECT DATEPART(YEAR, GETDATE()) AS Year
UNION ALL
Select Year - 1 FROM Years
WHERE Year > 2004
)
SELECT Year FROM Years
ORDER BY Year DESC
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/626797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: Printing on a thermal printer Java I'm using the following code to print some text on a thermal printer with 80mm roll paper:
public class printnow {
public static void printCard(final String bill) {
final PrinterJob job = PrinterJob.getPrinterJob();
Printable contentToPrint = new Printable() {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2d.setFont(new Font("Monospaced", Font.BOLD, 7));
pageFormat.setOrientation(PageFormat.PORTRAIT);
Paper pPaper = pageFormat.getPaper();
pPaper.setImageableArea(0, 0, pPaper.getWidth() , pPaper.getHeight() -2);
pageFormat.setPaper(pPaper);
if (pageIndex > 0)
return NO_SUCH_PAGE; //Only one page
String Bill [] = bill.split(";");
int y = 0;
for (int i = 0; i < Bill.length; i++) {
g2d.drawString(Bill[i], 0, y);
y = y + 15;
}
return PAGE_EXISTS;
}
};
boolean don = job.printDialog();
job.setPrintable(contentToPrint);
try {
job.print();
} catch (PrinterException e) {
System.err.println(e.getMessage());
}
}
}
This is printing extremely fine and is exactly what I want. But when I remove the following line to disable the print dialog box and automate the process of printing, my print messes up and the printer automatically takes some margin in the left.
boolean don = job.printDialog();
Any idea on why this is happening and how can it be solved?
A: After a lot of research and a applying a little brain, I found out the solution. It was a very small but silly mistake. Read the following source code:
public class printnow {
public static void printCard(final String bill ) {
final PrinterJob job = PrinterJob.getPrinterJob();
Printable contentToPrint = new Printable() {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2d.setFont(new Font("Monospaced", Font.BOLD, 7));
if (pageIndex > 0) {
return NO_SUCH_PAGE;
} //Only one page
String Bill [] = bill.split(";");
int y = 0;
for (int i = 0; i < Bill.length; i++) {
g2d.drawString(Bill[i], 0, y);
y = y + 15;
}
return PAGE_EXISTS;
}
};
PageFormat pageFormat = new PageFormat();
pageFormat.setOrientation(PageFormat.PORTRAIT);
Paper pPaper = pageFormat.getPaper();
pPaper.setImageableArea(0, 0, pPaper.getWidth() , pPaper.getHeight() -2);
pageFormat.setPaper(pPaper);
job.setPrintable(contentToPrint, pageFormat);
try {
job.print();
} catch (PrinterException e) {
System.err.println(e.getMessage());
}
}
}
In the previous source code (the wrong one), when the application triggers a print dialog box and the user clicks OK, the default printing preferences are transferred to the Java app and it prints what is required. but when we disable the print dialog box by removing this line:
boolean don = job.printDialog();
an unknow PageFormat is transferred which arises out of nowhere. The problem was not with our defined PageFormat, the problem was that the pageFormat is passed to a printing method which we were not doing initially:
job.setPrintable(contentToPrint, pageFormat);
Notice the second parameter being passed to the above method.
Hope this helps everyone. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17977510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: RewriteRule is not working after upgrade 2.4 I had upgrade my server to apache 2.4. After doing some configuration some .htaccess file is not working.
Following .htaccess is not working. It jest return 404 error. But this URL is working in land area.
RewriteEngine On
RewriteRule ^(.*)$ http://10.0.2.40/LandBank/$1 [NC,P]
But following .htaccess is working.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
How can it troubleshoot this?
A: Depending on your exact version of Apache, you may have encountered the same Apache rewrite bug that bit me: Internal URL rewrite no longer working after upgrading Apache to 2.4
See the workaround I linked to there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27481410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Replicate Webbrowser Save Page As function in C# I'm looking for a method that replicates a Web Browsers Save Page As function (Save as Type = Text Files) in C#.
Dilemma: I've attempted to use WebClient and HttpWebRequest to download all Text from a Web Page. Both methods only return the HTML of the web page which does not include dynamic content.
Sample code:
string url = @"https://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?trackingNumber=" + package.Item2 + "&LOCALE=en";
try
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
using (WebClient client = new WebClient())
{
string content = client.DownloadString(url);
}
}
The above example returns the HTML without the tracking events from the page.
When I display the page in Firefox, right click on the page and select Save Page As and save as Text File all of the raw text is saved in the file. I would like to mimic this feature.
A: If you are scraping a web page that shows dynamic content then you basically have 2 options:
*
*Use something to render the page first. The simplest in C# would be to have a WebBrowser control, and listen for the DocumentCompleted event. Note that there is some nuance to this when it fires for multiple documents on one page
*Figure out what service the page is calling to get the extra data, and see if you can access that directly. It may well be the case that the Canadapost website is accessing an API that you can also call directly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51289244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenModalWindow throws error first time the screen calls it I have been building an IT Ticketing / inventory system, and the program is done, now I'm adding instructions for the end users and the other techs in our school. Since I know nobody will read an instruction manual, I opted to make instructions for each screen, and put them in Modal Windows, activated by pushing a Help button I added to the Screen Commands section.
That works wonderfully, so I decided to capture the KeyDown event, and launch the window if they press F1. This is where things get a little weird.
If the HelpWindow for this particular screen has been opened at least once, pressing F1 opens it again with no trouble. If it has never been opened, pressing F1 results in an Error 'Control 'HelpWindow' doesn't contain a modal window. OpenModalWindow/CloseModalWindow cannot be used.'
After closing this error message, F1 will launch the HelpWindow exactly as expected. Very bizarre...
Background information:
Visual Studio 2012
Lightswitch project in VB (I work in both VB and C#, flipped a coin for this project)
The Modal Window is a group on the screen that is not visible, named "HelpWindow"; I use OpenModalWindow("HelpWindow") to open it. The exact same line of code in the HelpButton_Execute code, and the event handler for the KeyDown event.
It's the same method I use for every other modal window in the program, for submitting new tickets, adding equipment to the inventory, etc.
This problem only happens in the event handler, and only the first time the F1 key is pressed. The behavior is the same on every screen that has a help window.
My attempts to Google the problem were fruitless. Has anybody ever seen this behavior before?
A: That does sound very strange. I have to admit that I haven't seen anything like this myself with a modal window.
You don't mention where you're trapping the KeyDown key, so it's a bit hard to comment on that.
What I have seen sometimes, especially when doing something a little "different", is the error message not telling you the actual cause of the problem.
I would try wrapping the code with a dispatcher call, to make sure the call is being performed on the correct thread, as well as a try/catch to see if you can find the real cause of the error:
Private Sub YourClickHandler
Try
Me.Details.Dispatcher.BeginInvoke(
Sub()
OpenModalWindow("HelpWindow")
End Sub)
Catch ex As Exception
Me.ShowMessageBox(ex.Message)
End Try
End Sub
I hope that helps, or at least points you in the direction of a solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18516223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to hide Qcheckbox when Qcombox box selects an item? from PyQt5 import QtCore, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(762, 590)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.checkBox = QtWidgets.QCheckBox('box', self.centralwidget)
self.checkBox.setGeometry(QtCore.QRect(150, 75, 181, 20))
self.checkBox.setObjectName("checkBox")
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(150,160,100,20))
self.comboBox.addItem("Yes")
self.comboBox.addItem("No")
self.comboBox.setObjectName("comboBox")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "11"))
MainWindow.show()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I have created a combobox with "Yes" and "No", I want to hide the checkbox when I select "No" in the combobox, Can anyone help?
I tried to creat a function that when self.comboBox.currentText == "Yes" , run self.checkBox.hide(), but it didn't work...
A: You have to use the currentTextChanged signal that notifies you if the QComboBox selection has been changed sending you the new text, then you should only compare it with the text and together with the setVisible() method fulfill your requirement.
self.comboBox.currentTextChanged.connect(self.handle_current_text_changed)
def handle_current_text_changed(self, text):
self.checkBox.setVisible(text == "Yes")
A: Use signals and slots to do this. Capture the Combobox's editTextChanged signal with a slot hideCheckBox.
comboBox.currentTextChanged.connect(func)
In the function func simply setVisibility to false when the text is "NO" and true when text is "YES".
A: If you want to hide the checkbox when the comboBox state is HIDE, for example, and unhide checkBox when the combobox state is UNHIDE, use an IF construction to catch the state of the combobox. Depending on the state, apply one or the other value to the checkbox:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(762, 590)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.checkBox = QtWidgets.QCheckBox('box', self.centralwidget)
self.checkBox.setGeometry(QtCore.QRect(150, 75, 181, 20))
self.checkBox.setObjectName("checkBox")
self.comboBox = QtWidgets.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(150,160,100,20))
self.comboBox.addItem("UNHIDE")
self.comboBox.addItem("HIDE")
self.comboBox.setObjectName("comboBox")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.comboBox.currentTextChanged.connect(self.hidefunction) # code for connect to function below
def hidefunction(self):
text = str(self.comboBox.currentText())
# this is the state of the current text in combobox. Below simple IF block.
if text == "UNHIDE":
self.checkBox.setHidden(False)
# its HIDE - your checkBox when comboBox changed his state
else:
self.checkBox.setHidden(True)
# its HIDE your checkBox when comboBox changed his state
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "11"))
MainWindow.show()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52976860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: angularjs: directive and ng-repeat add extra div I've got the directive as follows:
app.directive("photos", function () {
return {
restrict: "E",
replace: true,
scope: {
"photoid": "@",
"scrollable": "@",
"size": "@",
"list": "=",
"inline": "@",
"extension": "@"
},
template:
'<div id="photos{{photoid}}" class="scroller" ng-class="[{{scrollable}}]" ng-style="{display:list.length==1?\'inline-block\':\'block\', width: list.length==1?\'{{size?size:\'171px\'}}\':\'auto\', height: \'{{size?size:\'171px\'}}\'}">\n\
length={{list.length}}\n\
<div ng-repeat="p in list"\n\
ng-style="{\'background-image\': \'url({{p.file}}.thumb.{{extension}})\', width: \'{{size?size:\'171px\'}}\', height: \'{{size?size:\'171px\'}}\'}"\n\
ng-click="$parent.$parent.openPopoverImageViewer(\'#photos{{photoid}}\', {{$index}})">\n\
<div>{{p.text}}</div>\n\
</div>\n\
<div>'
};
});
I invoke it twice as follows:
<h2 class="tintColor">Impact de la densité sur le rendement grain d'une variété</h2>
<photos photoid="ImpactPrecoce" list="[{file:'rsc/drive/4-Semis/d-ChoixDeLaDensite/ImpactPrecoce'}]" size="256px" extension="png"></photos>
<photos photoid="ImpactDemiPrecoce" list="[{file:'rsc/drive/4-Semis/d-ChoixDeLaDensite/ImpactDemiPrecoce'}]" size="256px" extension="png"></photos>
The result is OK, except that I end up with an extraneous did tag within the photos tag replacement.
I'm stuck with this, I really dont know where it comes from.
Any one can help?
[edit 1] Those div do not come from the option text div. Here is a version with optional text provided and the related screen shot.
<photos photoid="ImpactPrecoce"
list="[
{file:'rsc/drive/4-Semis/d-ChoixDeLaDensite/ImpactPrecoce', text:'first'},
{file:'rsc/drive/4-Semis/d-ChoixDeLaDensite/ImpactDemiPrecoce', text:'second'}
]"
size="256px"
extension="png"></photos>
See screen shot:
A: You have an unclosed div at the end of your block (which should be the closing tag), the browser closes it automatically, as well as the parent one. So two last lines:
</div>\n\
<div>'
should be:
</div>\n\
</div>'
A: Ok, I found it:
</div>\n\
<div>' <!-- this one was extraneous -->
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25961966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement SSL on Apache 2.2 Is there a step by step way to configure SSL on Apache 2.2. I have searched and tried a lot of things but the configuration is not working.
A: Check these links. These might be useful for your case
http://extrimity.in/content/enable-ssl-or-https-ubuntu-1104-apache-2
http://wiki.vpslink.com/Enable_SSL_on_Apache2
http://docs.oracle.com/cd/A95431_01/install/ssl.htm
Step by step
https://www.digitalocean.com/community/articles/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-12-04
http://www.digicert.com/ssl-certificate-installation-apache.htm
http://www.debian-administration.org/articles/349
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17218968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I search for a string using Line Input and then print the next 5 lines in Excel cell How do I search for a string, then when the string is found, write the entire line where the string is found, and then the next five lines into the same Cell in Excel using VBA?
Basically, I have a text file that I am importing into Excel using VBA. Based on a string, data from the file goes into cells under the appropriate column heading. The problem I am having is that some of my data is cut off at a line break. Due to the limitation of Line Input.
This condition does not happen for all values, just the ones with line breaks like this one:
How To Fix: To remove this functionality, set the following Registry key settings:
Hive: HKEY_LOCAL_MACHINE
Path: System\CurrentControlSet\Services...
Key: SomeKey
Type: DWORD
Value: SomeValue
Related Links: Some URL
I'm trying to get everything from How to Fix:... to Value:... to write to my Excel sheet, in the same Cell along with the data on the How to fix:... line.
I know that Input Line automatically stops at line breaks and moves on to the next line. Which, w/o the my loop attempts, is what the code below does.
If InStr(inputline, "How to Fix:") <> 0 Then
'Do While Not InStr(inputline, "Related Links:")
' Get rid of special characters in string
For i = 1 To Len(description)
sletter = Mid(description, i, i + 1)
iasc = Asc(sletter)
If Not (iasc <= 153 And iasc >= 32) Then
description = Left(description, i - 1) & " " & Right(description, Len(description) - i)
' End If
'Next
Do Until InStr(inputline, "Related Links:") = 1
description = Replace(description, "How to Fix:", "")
ws.Cells(rowndx4, 7).Value = Trim(description)
Loop
End If
I also tried using a FileSystemObject but it doesn't print anything to the Excel worksheet. The code is below:
Private Function ScanFile2$(FileToRead2 As String, rowndx4 As Long)
Dim wb As Workbook, ws As Worksheet, i As Long
Dim FNum3 As Integer, inputline As String, whatfile As Integer, testnum As String
Dim description As String
Dim finding As String
Set ws = ActiveWorkbook.Worksheets("Sheet1")
FNum3 = FreeFile()
Dim oFSO As FileSystemObject
Set oFSO = New FileSystemObject
Dim TS As TextStream
Const ForReading = 1
Set TS = oFSO.OpenTextFile(FNum3, ForReading)
Do While TS.AtEndOfStream <> True
inputline = TS.ReadAll
description = inputline
If InStr(inputline, "How To Fix:") <> 0 Then
description = Replace(inputline, "How To Fix:", "")
ws.Cells(rowndx4, 2).Value = inputline
End If
Exit Do
Loop
Close FNum3
Set ws = Nothing
Application.ScreenUpdating = True
ScanFile2 = rowndx4
End Function
A: Here's the full code
Sub test()
' Open the text file
Workbooks.OpenText Filename:="C:\Excel\test.txt"
' Select the range to copy and copy
Range("A1", ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
' Assign the text to a variable
Set my_object = CreateObject("htmlfile")
my_var = my_object.ParentWindow.ClipboardData.GetData("text")
' MsgBox (my_var) ' just used for testing
Set my_object = Nothing
pos_1 = InStr(1, my_var, "How to fix:", vbTextCompare)
pos_2 = InStr(pos_1, my_var, "Related Links", vbTextCompare)
my_txt = Mid(my_var, pos_1, -1 + pos_2 - pos_1)
' Return to the original file and paste the data
Windows("stackoverflow.xls").Activate
Range("A1") = my_txt
' Empty the clipboard
Application.CutCopyMode = False
End Sub
This works for me...
first, assign the text in the text file to a variable (my_var in the example below)
pos_1 = InStr(1, my_var, "How to fix:", vbTextCompare)
pos_2 = InStr(pos_1, my_var, "Related Links", vbTextCompare)
my_txt = Mid(my_var, pos_1, -1 + pos_2 - pos_1)
Range("wherever you want to put it") = my_txt
You can also clean up my_txt using the "replace" function if you like.
A: This code
*
*uses a RegExp to remove the linebreaks (replaced with a |) to flatten then string
*then extracts each match with a second RegExp
change your filepath here c:\temo\test.txt
sample input and output at bottom
code
Sub GetText()
Dim objFSO As Object
Dim objTF As Object
Dim objRegex As Object
Dim objRegMC As Object
Dim objRegM As Object
Dim strIn As String
Dim strOut As String
Dim lngCnt As Long
Set objRegex = CreateObject("vbscript.regexp")
Set objFSO = CreateObject("scripting.filesystemobject")
Set objts = objFSO.OpenTextFile("c:\temp\test.txt")
strIn = objts.readall
With objRegex
.Pattern = "\r\n"
.Global = True
.ignorecase = True
strOut = .Replace(strIn, "|")
.Pattern = "(How to Fix.+?)Related"
Set objRegMC = .Execute(strOut)
For Each objRegM In objRegMC
lngCnt = lngCnt + 1
Cells(lngCnt, 7) = Replace(objRegM.submatches(0), "|", Chr(10))
Next
End With
End Sub
input
test
How To Fix: To remove this functionality, set the following Registry key settings:
Hive: HKEY_LOCAL_MACHINE
Path: System\CurrentControlSet\Services...
Key: SomeKey
Type: DWORD
Value: SomeValue
Related Links: Some URL
otherstuff
How To Fix: To remove this functionality, set the following Registry key settings:
Hive: HKEY_LOCAL_MACHINE
Path: System\CurrentControlSet\Services...
Key: SomeKey
Type: DWORD
Value: SomeValue2
Related Links: Some URL2
output
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21067749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Python threading - continuously save results from other threads I want to get data from two sensor by means of threads. Assume, that these data are available by calling a corresponding funtion. These sensors should continuously be queried, but their values should only be saved when the time difference between two measurements is greater than a pre-defined threshold (only save data when the time difference to the last saved data is greater than 10 seconds). Since both threads for the data collection run in a while loop, I use another thread for saving the data. However, I have to somehow ensure that these data are available when saving. So the thread for saving has to wait for both other threads. Currently, I use time.sleep() which is working. But is there a better way to save the data of the two other threads?
import threading
import copy
import time
def thread1():
global connected
global data
while connected:
sensor_data = getSensorData()
data['x'] = sensor_data.x
data['y'] = sensor_data.y
data['time'] = sensor_data.time
def thread2():
global connected
global data
while connected:
other_sensor_data = getOtherSensorData()
data['h'] = other_sensor_data.h
def save_data():
global connected
global data
global results
while connected:
time.sleep(0.1)
if len(results) == 0 and len(data) > 0:
results.append(copy.deepcopy(data))
elif len(results) >= 1:
if data['time'] - results[-1]['time'] >= 10:
results.append(copy.deepcopy(data))
if __name__ == '__main__':
global connected
global data
global result
connected = True
data = {}
if 'result' not in globals():
result = []
first_thread = threading.Thread(target=thread1)
second_thread = threading.Thread(target=thread2)
save_thread = threading.Thread(target=save_data)
first_thread.start()
second_thread.start()
save_thread.start()
A: Personally I would use the build-in module queue which is designed to safely retrieve data from threads.
Using the LIFO functionality to create piles and then emptying them.
Here's a working example:
import threading
import queue
import time
sensor_pile = queue.LifoQueue()
other_sensor_pile = queue.LifoQueue()
def getSensorData():
time.sleep(0.05)
class Test:
x = "x " + str(time.time())
y = "y " + str(time.time())
time = time.time()
return Test
def getOtherSensorData():
time.sleep(0.01)
class Test:
h = "h " + str(time.time())
return Test
def thread1():
global connected
while connected:
sensor_pile.put(getSensorData())
def thread2():
global connected
while connected:
other_sensor_pile.put(getOtherSensorData())
def save_data():
global connected
global results
last_time = -float("inf")
# Use other_sensor_pile.get() if the first h value should not be None
h = None
while connected:
data = sensor_pile.get() # Will wait to receive data.
# As the main pile, the main while loop will keep it empty.
try:
# Update h to the latest value and then empty the pile.
# get_nowait will get the data if it is available
# or raise a queue.Empty error if it isn't.
h = other_sensor_pile.get_nowait().h
while True:
other_sensor_pile.get_nowait()
except queue.Empty:
pass
if data.time - last_time >= 0.2: # Shortened for the sake of testing.
last_time = data.time
results.append({
'time': last_time,
'x': data.x,
'y': data.y,
'h': h
})
if __name__ == '__main__':
global connected
global results
connected = True
if 'results' not in globals():
results = []
first_thread = threading.Thread(target=thread1)
second_thread = threading.Thread(target=thread2)
save_thread = threading.Thread(target=save_data)
first_thread.start()
second_thread.start()
save_thread.start()
time.sleep(1)
connected = False
save_thread.join()
second_thread.join()
first_thread.join()
for line in results:
print(line)
With the example output:
{'time': 1627652645.7188394, 'x': 'x 45.7188', 'y': 'y 45.7188', 'h': 'h 45.7032'}
{'time': 1627652645.9584458, 'x': 'x 45.9584', 'y': 'y 45.9584', 'h': 'h 45.9584'}
{'time': 1627652646.1991317, 'x': 'x 46.1991', 'y': 'y 46.1991', 'h': 'h 46.1991'}
{'time': 1627652646.4394188, 'x': 'x 46.4394', 'y': 'y 46.4394', 'h': 'h 46.4394'}
{'time': 1627652646.6793587, 'x': 'x 46.6793', 'y': 'y 46.6793', 'h': 'h 46.6793'}
The emptying of the pile isn't very efficient and can cause problems if the data is put in faster than it can be emptied.
There may be some other methods to do this but I'm not sure how it would work. See:
multithreading - overwrite old value in queue?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68576589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JNA with Fortran assumed size array I have a Fortran subroutine taking an assumed size array:
subroutine sub(arr)
implicit none
double precision arr(*)
end subroutine
I made a native call from Java using JNA, the Fortran subroutine is compiled as a shared library mylib.so:
import com.sun.jna.Library;
import com.sun.jna.Native;
public class Wrapper {
public interface MyLib extends Library {
public void sub_(double[] arr);
}
public static void main(String[] args) {
System.setProperty("jna.library.path", ".");
MyLib lib = (MyLib) Native.loadLibrary("mylib.so", MyLib.class);
double[] myarr = new double[10];
lib.sub_(myarr);
}
}
Now, is there a way to get (in the Fortran subroutine) the size of the array I passed into this subroutine without passing the actual size (10 in this case) as an additional argument?
I tried (Fortran) print*, size(arr), but that gives a compiler error:
print*,size(arr)
1
Error: The upper bound in the last dimension must appear in the reference to the assumed size array ‘arr’ at (1)
A: You will need to pass the length as an additional parameter. Using an assumed-shape array will not work, here's why:
In the ABI employed by most Fortran compilers, arrays as parameters ("dummy arguments") can take one of two representations, depending on the interface used in the subroutine/function:
*
*Those passed with known sizes or assumed sizes, like arr(n) or arr(*), usually receive just a pointer to the first element, with elements assumed to be contiguous.
*Those passed with assumed shapes, like arr(:) receive an array descriptor structure. This is completely implementation dependent, but usually such a structure contains the pointer to the first element of the data plus information on the bounds of each dimension, the stride, etc.
That is the reason why you can directly pass a single row, or only the elements in even indices, of an array if the function receives it as an assumed shape array: the descriptor structure encodes the information that the data is not necessarily contiguous and so the Fortran compiler does not need to copy arr(5:2:) to a temporary location in memory.
The reason why you cannot use such facilities to communicate with Java is that the descriptor structure is completely non-standard, a part of the particular ABI of each compiler. Thus, even if you somehow managed to understand how to build it (and it would be non trivial) the next version of your compiler could bring a total change.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37710480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Calling service from one docker container to other container is causing net::ERR_NAME_NOT_RESOLVED i am running application with multi containers as below..
feeder - is a simple nodejs container from image node:alpine
api - is nodejs container with expressjs from image node:alpine
ui-app - is react app container from image node:alpine
i am trying to call the api service in ui-app i am getting error as below
image to Console Log
image to Console Log
not sure what is causing the problem
if i access the services as http://192.168.99.100/ping it works (that is my docker machine default ip)...
but if i use container name like http://api:3200/ping it is not working...? please help..
the below is my docker-compose.
version: '3'
services:
feeder:
build: ./feeder
container_name: feeder
tty: true
depends_on:
- redis
links:
- redis
environment:
- IS_FROM_DOCKER=true
ports:
- "3100:3100"
networks:
- hmdanet
api:
build: ./api
container_name: api
tty: true
depends_on:
- feeder
links:
- redis
environment:
- IS_FROM_DOCKER=true
ports:
- "3200:3200"
networks:
hmdanet:
aliases:
- "hmda-api"
ui-app:
build: ./ui-app
container_name: ui-app
tty: true
depends_on:
- api
links:
- api
environment:
- IS_FROM_DOCKER=true
ports:
- "3000:3000"
networks:
- hmdanet
redis:
image: redis:latest
ports:
- '6379:6379'
networks:
- hmdanet
networks:
hmdanet:
driver: bridge
A: You can only use service name as a domain name when you are inside a container. In you case it's your browser making the call, it does not know what api is. In you web app, you should have an env like base url set to the ip of your docker machine or localhost.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53899300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Substring extraction using bash shell scripting and awk So, I have a file called 'dummy' which contains the string:
"There is 100% packet loss at node 1".
I also have a small script that I want to use to grab the percentage from this file. The script is below.
result=`grep 'packet loss' dummy` |
awk '{ first=match($0,"[0-9]+%")
last=match($0," packet loss")
s=substr($0,first,last-first)
print s}'
echo $result
I want the value of $result to basically be 100% in this case. But for some reason, it just prints out a blank string. Can anyone help me?
A: You would need to put the closing backtick after the end of the awk command, but it's preferable to use $() instead:
result=$( grep 'packet loss' dummy |
awk '{ first=match($0,"[0-9]+%")
last=match($0," packet loss")
s=substr($0,first,last-first)
print s}' )
echo $result
but you could just do:
result=$( grep 'packet loss' | grep -o "[0-9]\+%" )
A: Try
awk '{print $3}'
instead.
A: the solution below can be used when you don't know where the percentage numbers are( and there's no need to use awk with greps)
$ results=$(awk '/packet loss/{for(i=1;i<=NF;i++)if($i~/[0-9]+%$/)print $i}' file)
$ echo $results
100%
A: You could do this with bash alone using expr.
i=`expr "There is 98.76% packet loss at node 1" : '[^0-9.]*\([0-9.]*%\)[^0-9.]*'`; echo $i;
This extracts the substring matching the regex within \( \).
A: Here I'm assuming that the output lines you're interested in adhere strictly to your example, with the percentage value being the only variation.
With that assumption, you really don't need anything more complicated than:
awk '/packet loss/ { print $3 }' dummy
This quite literally means "print the 3rd field of any lines containing 'packet loss' in them". By default awk treats whitespace as field delimiters, which is perfect for you.
If you are doing more than simply printing the percentage, you could save the results to a shell variable using backticks, or redirect the output to a file. But your sample code simply echoes the percentages to stdout, and then exits. The one-liner does the exact same thing. No need for backticks or $() or any other shell machinations whatsoever.
NB: In my experience, piping the output of grep to awk is usually doing something that awk can do all by itself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2573009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to display percentile stats per URL on the console I'm am working on writing some performance tests using Taurus & Jmeter.
After executing a set of tests on a some URLs, I see the stats on console as below.
19:03:40 INFO: Percentiles:
+---------------+---------------+
| Percentile, % | Resp. Time, s |
+---------------+---------------+
| 95.0 | 2.731 |
+---------------+---------------+
19:03:40 INFO: Request label stats:
+--------------+--------+---------+--------+-------+
| label | status | succ | avg_rt | error |
+--------------+--------+---------+--------+-------+
| /v1/brands | OK | 100.00% | 2.730 | |
| /v1/catalogs | OK | 100.00% | 1.522 | |
+--------------+--------+---------+--------+-------+
I'm wondering if there is a way to display other labels per URL. for ex. percentile response time per URL.
Below are all the stats that could be captured from Taurus. (according to taurus documentation), but I couldn't figure out the configuration required to display them onto the console. Appreciate any help.
label - is the sample group for which this CSV line presents the stats. Empty label means total of all labels
concurrency - average number of Virtual Users
throughput - total count of all samples
succ - total count of not-failed samples
fail - total count of saved samples
avg_rt - average response time
stdev_rt - standard deviation of response time
avg_ct - average connect time if present
avg_lt - average latency if present
rc_200 - counts for specific response codes
perc_0.0 .. perc_100.0 - percentile levels for response time, 0 is also minimum response time, 100 is maximum
bytes - total download size
A: Looking into documentation on Taurus Console Reporter it is possible to amend only the following parameters:
modules:
console:
# disable console reporter
disable: false # default: auto
# configure screen type
screen: console
# valid values are:
# - console (ncurses-based dashboard, default for *nix systems)
# - gui (window-based dashboard, default for Windows, requires Tkinter)
# - dummy (text output into console for non-tty cases)
dummy-cols: 140 # width for dummy screen
dummy-rows: 35 # height for dummy screen
If you can understand and write Python code you can try amending reporting.py file which is responsible for generating stats and summary table. This is a good point to start:
def __report_summary_labels(self, cumulative):
data = [("label", "status", "succ", "avg_rt", "error")]
justify = {0: "left", 1: "center", 2: "right", 3: "right", 4: "left"}
sorted_labels = sorted(cumulative.keys())
for sample_label in sorted_labels:
if sample_label != "":
data.append(self.__get_sample_element(cumulative[sample_label], sample_label))
table = SingleTable(data) if sys.stdout.isatty() else AsciiTable(data)
table.justify_columns = justify
self.log.info("Request label stats:\n%s", table.table)
Otherwise alternatively you can use Online Interactive Reports or configure your JMeter test to use Grafana and InfluxDB as 3rd-party metrics storage and visualisation systems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52693979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: open a new page using onClick but after that back to the previous page is not working when I click a image. It's open a new page and a value pass through this click. It's working properly. but when I click back, It's do not show the previous page.
I use this code for click.
<img src="images/view.png" hspace="5" title="View" onClick="javascript:location.href='map_view.php?ad_id=<?php echo($row["ad_id"]); ?>'" style="cursor:pointer;" />
A: In order to geocode any phisical address, or get its coordinates , you should use a geocoding API, being google maps api v3 the most popular, which by the way gives you a free starting point of up to 2500 daily requests.
There is a bunch of documentation and starting guides, the best are the google maps's own.
Of course you can geocode on PHP or Javascript. Its really easy.
A: As other answer mentioned it is possible using google maps api, you can read more and get your own API KEY (More info and Get api key).
What you need is API key from google. This will help you fetching coordinates from given address.
I have made a little demonstration how it works it might be useful for other SO users.
By using following address
https://maps.googleapis.com/maps/api/geocode/json?address=YOUR_ADDRESS&key=YOUR_API_KEY
It will return you JSON formatted results with coordinates.
Now we need to build a tiny address form and pass it it to PHP script to return us the results
HTML Address form
<form action="index.php" method="post">
Enter Address:<br>
<input type="text" name="address">
<input type="submit">
</form>
PHP code
if (isset($_POST["address"]))
{
$addressInput = $_POST["address"];
$address = str_replace(" ", "+", $addressInput);
} else
{
// stack-overflow office address as default
$address = "110+William+St,+28th+Floor+New+York,+NY+10038";
}
echo "Latitude and Longitude for address : " . str_replace("+", " ", $address) . '<br>';
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&key=PUT_YOUR_OWN_API_KEY');
$data = json_decode($json, true);
//var_dump($data);
$getLat = $data['results'][0]['geometry']['location']['lat'];
$getLng = $data['results'][0]['geometry']['location']['lng'];
echo 'latitude ' . $getLat . ', longitude ' . $getLng;
The above working code can be tested on this link.
Moving theses data to mysql database or what ever you want to use it for, is left to you.
A: You'll probably use JavaScript for getting location of the user; not PHP. You can use HTML5 Geolocation for the purpose.
If you need to map the users location, pass the coordinates obtained using the HTML5 Geolocation API to Google Maps.
You may also need Modernizr to determine your users browser supports HTML5 Geolocation API.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35357948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: PHP & MySQL username submit problem I want to allow users to either have there username field empty at any time but I get the username error message Your username is unavailable! how can I correct this problem?
Here is the PHP code.
if(isset($_POST['username'])) {
$u = "SELECT *
FROM users
WHERE username = '$username'
AND user_id <> '$user_id'";
$r = mysqli_query ($mysqli, $u) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($mysqli));
if (mysqli_num_rows($r) == TRUE) { // Unavailable.
echo '<p class="error">Your username is unavailable!</p>';
$username = NULL;
} else if(mysqli_num_rows($r) == 0) { // Available.
$username = mysqli_real_escape_string($mysqli, $purifier->purify(htmlentities(strip_tags($_POST['username']))));
}
}
NONE of these examples are working. I want to know how can I let my users have no username?
A: if(isset($_POST['username']) && trim($_POST['username'])!=='') {
Otherwise, $_POST['username'] will be set even if the form is submitted with an empty field.
A: if(isset($_POST['username']) && !empty($_POST['username'])) {
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2650043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Important topics/APIs list for Java interview This is little different from what already been asked for here
I would like to know what topics/APIs are most important for Java interviews. for example -
*
*Concurrency,
*Collections
.....and like that.
The reason is because implementations like ConcurrentHashMap (read here) have so much details in them, that one would like to discuss about them as it covers many important aspects
A: *
*java.io - difference between streams and writers. Buffered streams.
*java.util - the collection framework. Set and List. What's HashMap, TreeMap. Some questions on efficiency of concrete collections
*java.lang - wrapper types, autoboxing
*java.util.concurrent - synchronization aids, atomic primitives, executors, concurrent collections.
*multithreading - object monitors, synchronized keyword, methods - static and non-static.
A: I'd say there are two things you need for every java interview:
*
*For Basic knowledge of the Language, consult your favorite book or the Sun Java Tutorial
*For Best Practices read Effective Java by Joshua Bloch
Apart from that, read whatever seems appropriate to the job description, but I'd say these two are elementary.
I guess these packages are relevant for every java job:
*
*java.lang (Core classes)
*java.io (File and Resource I/O)
*java.util (Collections Framework)
*java.text (Text parsing / manipulation)
A: IMHO its more important to have a firm understanding of the concepts rather than specific knowledge of the API and especially the internal workings of specific classes. For example;
*
*knowing that HashMap is not synchronized is important
*knowing how this might affect a multithreaded app is important
*knowing what kind of solutions exist for this problem is important
A: I wouldn't worry too much about specific API details like individual methods of ConcurrentHashMap, unless you're interviewing for a job that is advertised as needing a lot of advanced threading logic.
A thorough understanding of the basic Java API's is more important, and books like Effective Java can help there. At least as important though is to know higher level concepts like Object Orientation and Design Patterns.
Understanding what Polymorphism, Encapsulation and Inheritance are, and when and how to use them, is vital. Know how to decide between Polymorphism and Delegation (is-a versus has-a is a decent start, but the Liskov Substitution Principle is a better guide), and why you may want to favor composition over inheritance. I highly recommend "Agile Software Development" by Robert Martin for this subject. Or check out this link for an initial overview.
Know some of the core patterns like singleton, factory, facade and observer. Read the GoF book and/or Head First Design Patterns.
I also recommend learning about refactoring, unit testing, dependency injection and mocking.
All these subject won't just help you during interviews, they will make you a better developer.
A: We usually require the following knowledge on new developers:
Low level (programming) questions:
http://www.interview-questions-java.com/
Antipatterns:
http://en.wikipedia.org/wiki/Anti-pattern
Design:
http://en.wikipedia.org/wiki/Design_Patterns
A: On some of the interviews I have been to, there is also the java.io package covered, sometimes with absurd questions on what kind of exceptions would some rarely used method declare to throw, or whether some strange looking constructor overload exists.
Concurrency is always important for higher-level positions, but I think that knowing the concepts well (and understanding them ofc) would win you more points than specific API knowledge.
Some other APIs that get mentioned at interviews are Reflection (maybe couple questions on what can be achieved with it) and also java.lang.ref.Reference and its subclasses.
A: I ask some basic questions ('whats the difference between a list and a set?', 'whats an interface?', etc) and then I go off the resume. If hibernate is on there 5 times, I expect the candidate to be able to define ORM. You would be surprised how often it happens that they can't. I am also interested in how the candidate approaches software -- do they have a passion for it? And it is very important that the candidate believes in TDD. Naturally, if its a really senior position, the questions will be more advanced (e.g. 'whats ThreadLocal and when do you use it'), but for most candidates this is not necessary.
A: Completely agree with Luke here. We can not stick to some API's to prepare for Core Java interviews. I think a complete understanding of the OOPS concept in Java is must. Have good knowledge of oops shows the interviewer that the person can learn new API's easily and quick.
Topics that should be covered are as follows:
OOPS Concept
Upcasting & DownCasting
Threading
Collection framework.
Here is a good post to get started. Core Java Interview Q & A
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4085089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to determine the facet content in a custom controls design definition? I'm putting together the design definition for a custom control and would like to vary how it displays based on whether or not a different custom control has been placed in the one of the facet areas. Is this possibe with the design definition and if so, how?
I know I can reference properties of the custom control by using "this", but I couldn't guess as to how to get to the facet content information.
Any ideas? Thanks
A: In the design definition you can add a callback node where your facet should appear. This should expose the Editable Area when you add your control to another page.
The format for the callback node would look similar to
<xp:callback id="callbackID" facetName="facetname" />
A: Dan,
Can you get the Editable Area as a javax.faces.component.UIComponent and then do .getFacets()?
BTW, hope you're well!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10245764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to perform a simple Couchbase Lite query I wanted to know how it's possible to do some simple CouchbaseLite queries.
I have a document named "test", with key-values "id": 5 and "name":"My first test".
I wanted to search following:
*
*I want to get the id (5) where name = "My first test".
*I also wanted to know if this name = "My first test" entry is already available? I only wanted to add it if it's not there.
Database db = new Database("test_db");
using (var testDoc = new MutableDocument("test"))
{
testDoc.SetInt("id", 5)
.SetString("name", "My first test");
db.Save(testDoc);
}
Thanks!
A: Assuming I understood your question right that you want to fetch documents with a specific property value only if it exists, you can do something like this
var query = QueryBuilder.Select(SelectResult.expression(Meta.id),
SelectResult.expression(Expression.property("id")))
.From(DataSource.Database(db))
.Where(Expression.Property("name").NotNullOrMissing()
.And(Expression.Property("name").EqualTo(Expression.string("My first test"))))
Alternatively, if you know the Id of the document, it would be faster to do a GetDocument with the Id. Once you have the document, do a GetString on the name property. If it returns null, you can assume it does not exist.
Refer to the documentation on Couchbase Lite query fundamentals here.There are several examples. You may also want to check out API specs on NotNullOrMissing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58919815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Lifting a function which takes implicit parameter using functor (Scalaz7) Just started learning Scalaz. Here is my code
trait Monoid[A] {
def mappend(a1: A, a2: A): A
def mzero: A
}
object Monoid {
implicit val IntMonoid: Monoid[Int] = new Monoid[Int] {
def mappend(a1: Int, a2: Int): Int = a1 + a2
def mzero: Int = 0
}
implicit val StringMonoid: Monoid[String] = new Monoid[String] {
def mappend(a1: String, a2: String): String = a1 + a2
def mzero: String = ""
}
}
trait MonoidOp[A] {
val F: Monoid[A]
val value: A
def |+|(a2: A): A = F.mappend(value, a2)
}
object MonoidOp{
implicit def toMonoidOp[A: Monoid](a: A): MonoidOp[A] = new MonoidOp[A]{
val F = implicitly[Monoid[A]]
val value = a
}
}
I have defined a function (just for the sake of it)
def addXY[A: Monoid](x: A, y: A): A = x |+| y
I want to lift it so that it could be used using Containers like Option, List, etc. But when I do this
def addXYOptioned = Functor[Option].lift(addXY)
It says error: could not find implicit value for evidence parameter of type scalaz.Monoid[A]
def addOptioned = Functor[Option].lift(addXY)
How to lift such functions?
A: Your method addXY needs a Monoid[A] but there is no Monoid[A] in scope when used in addXYOptioned, so you also need to add the Monoid constraint to addXYOptioned.
The next problem is that Functor.lift only lifts a function A => B, but we can use Apply.lift2 to lift a function (A, B) => C.
Using the Monoid from Scalaz itself :
import scalaz._, Scalaz._
def addXY[A: Monoid](x: A, y: A): A = x |+| y
def addXYOptioned[A: Monoid] = Apply[Option].lift2(addXY[A] _)
We could generalize addXYOptioned to make it possible to lift addXY into any type constructor with an Apply instance :
def addXYApply[F[_]: Apply, A: Monoid] = Apply[F].lift2(addXY[A] _)
addXYApply[List, Int].apply(List(1,2), List(3,4))
// List[Int] = List(4, 5, 5, 6)
addXYApply[Option, Int].apply(1.some, 2.some)
// Option[Int] = Some(3)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38300335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MS Chart Control Scale - Line graph show 12 months On my X Axis, I have months. The chart shows up to 11 points, i.e. Jan - Nov of the same year, but when I add 12 points (Jan - Dec), it will do an auto label thing and change the interval for every 4 months.
How can I change the graph so that it shows 12 months before it does the auto labels?
Here is the server control code I am currently using.
<asp:CHART ID="Chart1" runat="server"
BorderColor="181, 64, 1" BorderDashStyle="Solid" BorderWidth="2" Height="296px"
ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)" ImageType="Png"
Palette="None" Width="700px"
BorderlineColor="">
<legends>
<asp:Legend BackColor="Transparent"
Font="Trebuchet MS, 8pt, style=Bold"
IsTextAutoFit="False" Name="Default" Alignment="Center"
DockedToChartArea="ChartArea1" Docking="Top" IsDockedInsideChartArea="False"
Title="Legend">
</asp:Legend>
</legends>
<series>
<asp:Series BorderColor="180, 26, 59, 105" BorderWidth="2" ChartType="Line"
Color="220, 65, 140, 240" MarkerSize="6"
Name="Series1" ShadowColor="Black"
ShadowOffset="2" XValueType="DateTime" YValueType="Double"
LabelFormat="c0" LegendText="Actual"
MarkerStyle="Circle">
</asp:Series>
<asp:Series BorderColor="180, 26, 59, 105" BorderWidth="2" ChartType="Line"
Color="220, 224, 64, 10" MarkerSize="6" Name="Series2" ShadowColor="Black"
ShadowOffset="2" XValueType="DateTime" YValueType="Double"
LabelFormat="c0" LegendText="Projected"
MarkerStyle="Circle">
</asp:Series>
<asp:Series BorderColor="180, 26, 59, 105" BorderWidth="2"
ChartArea="ChartArea1" ChartType="Line"
Legend="Default" Name="Series3" LabelFormat="c0" XValueType="DateTime"
YValueType="Double" Color="0, 192, 192" MarkerSize="6"
ShadowColor="Black" ShadowOffset="2" LegendText="Actual Credit Limit"
MarkerStyle="Circle">
</asp:Series>
</series>
<chartareas>
<asp:ChartArea BackColor="#DEEDF7" BackGradientStyle="TopBottom"
BackSecondaryColor="White" BorderColor="64, 64, 64, 64" BorderDashStyle="Solid"
Name="ChartArea1" ShadowColor="Transparent">
<area3dstyle inclination="40" isclustered="False" isrightangleaxes="False"
lightstyle="Realistic" perspective="9" rotation="25" wallwidth="3" />
<axisy linecolor="64, 64, 64, 64" islabelautofit="False"
isstartedfromzero="False">
<LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" Format="c0" />
<majorgrid linecolor="64, 64, 64, 64" />
</axisy>
<axisx linecolor="64, 64, 64, 64" intervaloffsettype="Months"
intervaltype="Months" islabelautofit="False" isstartedfromzero="False">
<LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" Angle="-60"
Format="MMM yy" />
<majorgrid linecolor="64, 64, 64, 64" />
</axisx>
</asp:ChartArea>
</chartareas>
</asp:CHART>
Thanks.
A: Try to change the Chart's Width to a higher value...
<asp:Chart ID="Chart1" runat="server"
BorderColor="181, 64, 1" BorderDashStyle="Solid" BorderWidth="2" Height="296px"
ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)" ImageType="Png"
Palette="None" Width="800px"
BorderlineColor="">
Try to set the inverval property to 1 on axisx:
<axisx Interval="1" linecolor="64, 64, 64, 64" intervaloffsettype="Months"
intervaltype="Months" islabelautofit="False" isstartedfromzero="False">
To fully understand how to format chart axis, take a look at:
Formatting Axis Labels on a Chart
(source: microsoft.com)
How the Chart Calculates Axis Label Intervals?
On the category axis, the minimum and maximum value types are determined depending on the type of your category field. Any field in a dataset can be categorized into one of three category field types: Numeric, Date/Time and Strings.
Displaying All Labels on the Category Axis
On the value axis, axis intervals provide a consistent measure of the data points on the chart. However, on the category axis, this functionality can cause categories to appear without axis labels. Typically, you want all categories to be labeled. You can set the number of intervals to 1 to show all categories. For more information, see How to: Specify an Axis Interval.
A: Use Microsoft chart
chart.ChartAreas[0].AxisY.ScaleBreakStyle = true
to chart the second set of values in thier on Y Axis with thier own Y values
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2993879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do you mount a VueJS UMD build onto existing HTML? I've been attempting to take a couple of small components from our main app to use on a landing page, but haven't had much luck!
I have some existing HTML in the DOM, let's say:
<div id="app">
<h1>Demo Feature #1</h1>
<demo-component />
</div>
I have the following entry file, marketing.ts:
import Vue from "vue";
import Demo from "Demo.vue";
new Vue({
el: 'app',
components: {
'demo-component': Demo,
}
});
When the output build runs on the site, the DOM ends up looking like this:
<!--function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }-->
I expected the custom HTML tag to be replaced with my Vue component.
The docs state this should be the case:
If neither render function nor template option is present, the in-DOM HTML of the mounting DOM element will be extracted as the template. In this case, Runtime + Compiler build of Vue should be used.
Furthermore, the docs go on to state:
When using vue-loader or vueify, templates inside *.vue files are pre-compiled into JavaScript at build time. You don’t really need the compiler in the final bundle, and can therefore use the runtime-only build.
In this case, I am using the VueCLI (with Vue Loader) to build my output, which from the above I understand to be a runtime-only build.
The component works fine in the full application. The glaring thing I can see is a lack of render. When I use that, it replaces the DOM with the whole component supplied and loses what was already inside.
Is it possible to extract multiple components via a lib build and render them in an existing DOM?
Further details:
*
*Using the build command vue-cli-service build --target lib --inline-vue --dest dist/lib/marketing --name marketing src/marketing.ts --no-clean
*Using VueCLI 4.2.2
*Using TypeScript and Vue Class components
*This CodePen show's it's possible to do
A: The way I've done it is by...
1) wrapping my component in a js file
import MyWidgit from './MyWidgit.vue';
// eslint-disable-next-line import/prefer-default-export
export const mount = (el, props) =>
new window.Vue({
el,
render: h => h(Filter, {props})
});
2) using rollup to generate the code (I think it's a better fit for generating libraries)
{
input: `./src/${widgetName}/${widgetName}.js`, // Path relative to package.json
output: {
format: 'umd',
name: widgetName,
file: `./dist/${widgetName}.js`,
exports: 'named',
external: ['vue'], // requires vuejs lib to be loaded separately
globals: {
vue: 'Vue',
},
},
//... etc
}
3) add to html
<script src="/dist/vue.js"></script>
<script src="/dist/mywidgit.js"></script>
<!-- mywidgit mount target-->
<div id="widget1"></div>
<!-- init and mount -->
<script>
mywidgit.mount('#widget1', {
msg: 'all is well',
});
</script>
A: To solve this issue, I removed the --inline-vue argument from the CLI build and added Vue.JS via the CDN, ie.
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
I believe this should work from a single lib, so this is potentially an issue with the build tool.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60568885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting error while installing mongodb on Mac Warning: No available formula with the name "mongosh" (dependency of mongodb/brew/mongodb-community). Did you mean mongocli?
==> Searching for similarly named formulae...
This similarly named formula was found:
mongodb/brew/mongocli ✔
To install it, run:
brew install mongodb/brew/mongocli ✔
It was migrated from mongodb/brew to homebrew/core.
Trying to install mongoDB from Official website and encountered this error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72387960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Button onClickListener on AlertBuilder not working I have an activity and a layout to call in AlertBuilder,
I have 3 buttons in layout and some code for each one.
The problem is that when I create and show alert, onClickListener not working
I don't want use alert buttons and have to use my buttons on layout
MainActivity Code (Call Alert)
LayoutInflater inflater = (MainActivity.this).getLayoutInflater();
builder.setTitle("Login Form");
builder.setCancelable(false);
builder.setView(inflater.inflate(R.layout.activity_login_prompt, null));
builder.create();
builder.show();
LoginPromptActivity
public class LoginPromptActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_prompt);
Button bLogin = (Button)findViewById(R.id.btnLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(LoginPromptActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
Layout XML Code
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".LoginPromptActivity"
tools:showIn="@layout/activity_login_prompt">
<ImageView
android:id="@+id/imageView2"
android:layout_width="192dp"
android:layout_height="147dp"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="32dp"
android:layout_marginRight="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/login" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="32dp"
android:layout_marginRight="32dp"
android:text="Username"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView2" />
<EditText
android:id="@+id/txtUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:layout_marginTop="17dp"
android:layout_marginEnd="32dp"
android:layout_marginRight="32dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintEnd_toStartOf="@+id/textView4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView2" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="32dp"
android:layout_marginRight="32dp"
android:text="Password"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView4" />
<EditText
android:id="@+id/txtPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:ems="10"
android:inputType="textPassword"
app:layout_constraintEnd_toStartOf="@+id/textView5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtUserName" />
<Button
android:id="@+id/btnLogin"
android:layout_width="127dp"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Login"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtPassword" />
<Button
android:id="@+id/btnRegister"
android:layout_width="94dp"
android:layout_height="46dp"
android:layout_marginTop="32dp"
android:text="Register"
app:layout_constraintEnd_toStartOf="@+id/btnLogin"
app:layout_constraintTop_toBottomOf="@+id/txtPassword" />
<Button
android:id="@+id/btnCancel"
android:layout_width="126dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Exit App"
app:layout_constraintEnd_toStartOf="@+id/btnRegister"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtPassword" />
</android.support.constraint.ConstraintLayout>
A: I have read your question and I think you have face some problem to implement onclick listener
on alert dialog buttons. if we have use any custom layout for alert dialog so do not need any activity to handle this layout. According to your code sinppet you have create a alert dialog using custom layout and use a activity to handle this layout button click
Try this this code create custom alert dialog , and handle its click listener
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Login Form");
View view= getLayoutInflater().inflate(R.layout.dialog_custom, null);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setView(view);
alertDialogBuilder.create();
//alert dialog button
TextView ok_btn=view.findViewById(R.id.ok_btn);
//buttton click
ok_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Toast
.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT)
.show();
}
});
alertDialogBuilder.show();
A: private void showAlertDialog(){
@SuppressLint("InflateParams") final View promptView = LayoutInflater.from(mainActivity).inflate(R.layout.enter_pin_dialog, null);
Button accept= (Button) promptView.findViewById(R.id.accept_btn);
Button deny= (Button) promptView.findViewById(R.id.deny_btn);
deny.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// do what you want
}
});
accept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// do what you want
}
});
NotificationUtil.messageDialog(
mainActivity,
null,
null,
null,
false,
true,
promptView,
null,
null,
null,
null,
null,
null
);}
public class NotificationUtil {
private static ProgressDialog progressDialog;
private static AlertDialog cancelDialog;
private static AlertDialog messageDialog;
private static Vector<AlertDialog> dialogs= new Vector<AlertDialog>();
public static void messageDialog(Context context, String title, String message, Integer iconResId,
boolean cancelable, boolean openKeyboard, View view,
String positiveStr, DialogInterface.OnClickListener positiveListener,
String negativeStr, DialogInterface.OnClickListener negativeListener,
DialogInterface.OnShowListener showListener, DialogInterface.OnDismissListener dismissListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(cancelable);
if (iconResId != null) {
builder.setIcon(iconResId);
}
if (view != null) {
builder.setView(view);
}
if (positiveStr != null) {
builder.setPositiveButton(positiveStr, positiveListener);
}
if (negativeStr != null) {
builder.setNegativeButton(negativeStr, negativeListener);
}
messageDialog = builder.create();
dialogs.add(messageDialog);
if (openKeyboard) {
Window window = messageDialog.getWindow();
if (window != null) {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
}
if (showListener != null) {
messageDialog.setOnShowListener(showListener);
}
if (dismissListener != null) {
messageDialog.setOnDismissListener(dismissListener);
}
messageDialog.show();
ScrollView buttonsContainer = (ScrollView) messageDialog.findViewById(R.id.buttonPanel);
if (buttonsContainer != null) {
List<View> views = new ArrayList<>();
for (int i = 0; i < buttonsContainer.getChildCount(); i++) {
views.add(buttonsContainer.getChildAt(i));
}
buttonsContainer.removeAllViews();
for (int i = views.size() - 1; i >= 0; i--) {
buttonsContainer.addView(views.get(i));
}
}
}}
A: try this
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setMessage("ddddd");
alertbox.setTitle("dddd");
alertbox.setIcon(R.drawable.ic_del);
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
}
});
alertbox.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
A: Open your MainActivity.java and add OnClickListener to your button to create an alert dialog :
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create a Custom Alert Dialog
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.list_layout,null);
TextView tv = (TextView)view.findViewById(R.id.head);
ImageView iv = (ImageView)view.findViewById(R.id.iv);
builder.setView(view);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Dismiss the dialog here
dialog.dismiss();
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Add ok operation here
}
});
builder.show();
}
});
You can also add custom buttons to your alert dialog.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57781489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Concatenating user input? I want to concatenate user input with a ':' colon in-between.
My script is taking options through user input and I want to store it like:
Red:yellow:blue
I have created a loop to read user input, but not sure how to store it.
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
color += color
print ("colors ", color)
A: One simple approach to keep as close to your code as possible is to start off with an empty list called colors before entering your loop, and appending to that all the valid colors as you take inputs. Then, when you are done, you simply use the join method to take that list and make a string with the ':' separators.
colors = []
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
else:
colors.append(color)
colors = ':'.join(colors)
print ("colors ", colors)
Demo:
please enter Color of your choice(To exit press No): red
please enter Color of your choice(To exit press No): blue
please enter Color of your choice(To exit press No): green
please enter Color of your choice(To exit press No): orange
please enter Color of your choice(To exit press No): No
colors red:blue:green:orange
A: You can concatenate a ':' after every input color
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color == 'No':
break
color += color
color += ':'
print ("colors ", color)
A: you're looking for str.join(), to be used like so: ":".join(colors). Read more at https://docs.python.org/2/library/stdtypes.html#str.join
A: Using a list is neat:
colors = []
while True:
color = input("please enter Color of your choice(To exit press No): ")
if color in ('No'):
break
colors.append(color)
print("colors ", ':'.join(colors))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44629956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Redirect/Forward data from Spring MVC Controller to other page as POST? I'm working on a project which is a mix Spring MVC and coldfusion, I want to know how to redirect from the SpringMVC Controller to the cfm using a POST request.
I have this mapping defined
@RequestMapping(value = "/preprocess", method = {RequestMethod.GET})
public ModelAndView doPreprocess(HttpServletRequest request, @RequestParam Map<String, String> params, HttpSession session) {
//retrieve some parameters from db and redirect/forward here to "/postprocess.cfm"
}
After retrieve some parameters, I need to redirect/forward those parameter to other endpoint "/postprocess.cfm", this page reads the params from a form, so the request to this page needs to be a POST
Looking forward to your help. Thanks a lot!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54933140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Combine IsNumeric and Right()
Trying to return field [doc] that have no letters. Results are all over the place.
SELECT Right([doc],4) AS ex1, IsNumeric([ex1]) AS ex2
FROM stat_converted;
The query returns two fields as it should but not evaluating correctly. Results with all numbers and others that are all letters are coming back as True(-1).
I also tried building a temp table and then applying IsNumeric to that with same results.
I also built a small test DB and the logic works so I am really confused.
A: IsNumeric will match things like "2E+1" (2 times ten to the power of 1, i.e. 20) as that is a number in scientific format. "0D88" is also a number according to IsNumeric because it is the double-precision (hence the "D") version of "0E88".
You could use LIKE '####' to match exactly four digits (0-9).
If you had more complex match requirements, say a variable quantity of digits, you would be interested in Expressing basic Access query criteria as regular expressions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41492444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to get the contents in brackets in a file Python I am working with files right now and i want to get text from a bracket this is what i mean by getting text from a brackets...
{
this is text for a
this is text for a
this is text for a
this is text for a
}
[
this is text for b
this is text for b
this is text for b
this is text for b
]
The content in a is this is text for a and the content for b is is text for b
my code seems to not be printing the contents in a properly it show a&b my file.
My code:
with open('file.txt','r') as read_obj:
for line in read_obj.readlines():
var = line[line.find("{")+1:line.rfind("}")]
print(var)
A: *
*iterate over the file
*for each line check the first character
*
*if the first character is either '[' or '{' start accumulating lines
*if the first character is either ']' or '}' stop accumulating lines
a_s = []
b_s = []
capture = False
group = None
with open(path) as f:
for line in f:
if capture: group.append(line)
if line[0] in '{[':
capture = True
group = a_s if line[0] == '{' else b_s
elif line[0] in '}]':
capture = False
group = None
print(a_s)
print(b_s)
Relies on the file to be structured exactly as shown in the example.
A: This is what regular expressions are made for. Python has a built-in module named re to perform regular expression queries.
In your case, simply:
import re
fname = "foo.txt"
# Read data into a single string
with open(fname, "r") as f:
data = f.read()
# Remove newline characters from the string
data = re.sub(r"\n", "", data)
# Define pattern for type A
pattern_a = r"\{(.*?)\}"
# Print text of type A
print(re.findall(pattern_a, data))
# Define pattern for type B
pattern_b = r"\[(.*?)\]"
# Print text of type B
print(re.findall(pattern_b, data))
Output:
['this is text for athis is text for athis is text for athis is text for a']
['this is text for bthis is text for bthis is text for bthis is text for b']
A: Read the file and split the content to a list.
Define a brackets list and exclude them through a loop and write the rest to a file.
file_obj = open("content.txt", 'r')
content_list = file_obj.read().splitlines()
brackets = ['[', ']', '{', '}']
for i in content_list:
if i not in brackets:
writer = open("new_content.txt", 'a')
writer.write(i+ '\n')
writer.close()
A: f1=open('D:\\Tests 1\\t1.txt','r')
for line in f1.readlines():
flag=0
if line.find('{\n') or line.find('[\n'):
flag=1
elif line.find('}\n') or line.find(']\n'):
flag=0
if flag==1:
print(line.split('\n')[0])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66833782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Returning value from query based on results I have this query I'm trying to build to display specific information for a stored table. I'm needing the query to also display the Enemy Guild Name but I'm having trouble getting the query to take the Enemy Guild ID and link it to the name.
SELECT g.wPos as wPos, g.szGuildName as szGuildName, g.dwGuildExpWeek as dwGuildExpWeek, g.dwEnemyGuildID as dwEnemyGuildID, gm.wPower as wPower, gd.szName as szName
FROM guild as g
LEFT JOIN guild_member AS gm ON gm.dwGuildID = g.dwGuildID AND gm.wPower = '1'
LEFT JOIN gamedata AS gd ON gd.dwID = gm.dwRoleID
WHERE g.wPos = '1'
The output of the query right now results in the following:
Query Results Currently
What I need it to do now is take the dwEnemyGuildID it finds and then use that ID to search for the szGuildName while also displaying the other data it finds.
A: Use the concept of SELF JOIN, in which we will join same table again if we have a field which is a reference to the same table. Here dwEnemyGuildID is reference to the same table.
A trivial example of the same is finding Manager for an employee from employees table.
Reference: Find the employee id, name along with their manager_id and name
SELECT
g.wPos as wPos,
g.szGuildName as szGuildName,
g.dwGuildExpWeek as dwGuildExpWeek,
g.dwEnemyGuildID as dwEnemyGuildID,
enemy_g.szGuildName as szEnemyGuildName, -- pick name from self joined table
gm.wPower as wPower,
gd.szName as szName
FROM guild as g
LEFT JOIN guild_member AS gm ON gm.dwGuildID = g.dwGuildID AND gm.wPower = '1'
LEFT JOIN guild AS enemy_g ON g.dwEnemyGuildID = enemy_g.dwGuildID -- Use self join
LEFT JOIN gamedata AS gd ON gd.dwID = gm.dwRoleID
WHERE g.wPos = '1';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57764841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Auto check textfield length and Hit a method UITextfield Hello I need to enter mobile number with validation that mobile textfield range should be 10.
And when textfield value ==10, i need to call a function when mobile textfield.text length becomes 10.
My below code work fine but i need to press 1 more character (means 11) to call it.
Please how i resolve it.
#define MAX_LENGTH 10
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField==user_mobile_txtField)
{
if (textField.text.length >= MAX_LENGTH && range.length == 0)
{
if (textField.text.length==MAX_LENGTH)
{
NSLog(@“Want to call Call method HERE ");
}
return NO; // return NO to not change text
}
}
return YES;
}
A: shouldChangeCharactersInRange is called just before actual text has changed. If you want to perform an action after actual text has changed, you can try the approach below:
...
//start observing
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textHasChanged:) name:UITextFieldTextDidChangeNotification object:{your UITextField}];
...
- (void)textHasChanged:(NSNotification *)notification {
UITextField *textField = [notification object];
//check if textField.text.length >= 10
//do stuff...
}
A: You can get what the string will be after the characters are changed with the method stringByReplacingCharactersInRange:withString:
#define MAX_LENGTH 10
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == user_mobile_txtField) {
NSString *fullString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (fullString.length >= MAX_LENGTH && range.length == 0) {
if (fullString.length == MAX_LENGTH) {
NSLog(@“Want to call Call method HERE ");
}
return NO; // return NO to not change text
}
}
return YES;
}
A: Please try with below code -
#define MAX_LENGTH 10
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField==user_mobile_txtField)
{
if (textField.text.length >= MAX_LENGTH )
{
if (textField.text.length==MAX_LENGTH)
{
NSLog(@“Want to call Call method HERE ");
}
return NO; // return NO to not change text
}
}
return YES;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30593816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java/Jsp XML Dom looks like I need help again! :-/
Im trying to read this XML file with Java/Jsp:
<?xml version="1.0" encoding="iso-8859-1" ?>
<universal_campaign>
<campaign_details>
<campaign_id></campaign_id>
<campaign_title>Test Campaign</campaign_title>
<campaign_sdate>2010-01-21</campaign_sdate>
<campaign_edate>2010-01-25</campaign_edate>
<campaign_priority>Normal</campaign_priority>
</campaign_details>
<campaign_schedule>
<schedule_sdate>2010-01-25</schedule_sdate>
<schedule_edate>2010-01-30</schedule_edate>
<schedule_priority>Normal</schedule_priority>
<schedule_content>
<content_name>Wallpaper_A</content_name>
<content_filename>WP_A.jpg</content_filename>
</schedule_content>
<schedule_content>
<content_name>Screensaver</content_name>
<content_filename>SCS.gif</content_filename>
</schedule_content>
<schedule_zone>universal.001 test 001</schedule_zone>
<schedule_zone>universal.001 test 002</schedule_zone>
<schedule_zone>universal.001 test 003</schedule_zone>
</campaign_schedule>
</universal_campaign>
Here is my Java/Jsp code:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(fileName);
NodeList nl, nl2;
NodeList campaign_details = doc.getElementsByTagName("universal_campaign");
String res = "";
for(int i = 0;i<campaign_details.getLength();i++){
nl = campaign_details.item(i).getChildNodes();
for(int j = 0; j<nl.getLength();j++){
nl2 = nl.item(j).getChildNodes();
for(int k = 0; k<nl2.getLength();k++){
res += nl2.item(k).getNodeName()+": "+nl2.item(k).getNodeValue()+"<br />";
}
}
}
But when I output the String res, I get:
#text:
campaign_id: null
#text:
campaign_title: null
#text:
campaign_sdate: null
#text:
campaign_edate: null
#text:
campaign_priority: null
#text:
#text:
schedule_sdate: null
#text:
schedule_edate: null
#text:
schedule_priority: null
#text:
schedule_content: null
#text:
schedule_content: null
#text:
schedule_zone: null
#text:
schedule_zone: null
#text:
schedule_zone: null
#text:
And I don't get it... how can the getNodeName() return the name of the node, but the getNodeValue() returns null....?
Please help me, I have done many search and failed attempts before posting here, but nothing worked.... :-/
A: Use getTextContent() or, even better, use a better XML API (jdom springs to mind).
A: The fact is that the node you're getting is not the text node itself. It's an Element and getNodeValue will return null (see table here). You'll have to use getTextContent instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2362732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When to catch java.lang.Error? In what situations should one catch java.lang.Error on an application?
A: Very rarely.
I'd say only at the top level of a thread in order to ATTEMPT to issue a message with the reason for a thread dying.
If you are in a framework that does this sort of thing for you, leave it to the framework.
A: Almost never. Errors are designed to be issues that applications generally can't do anything about. The only exception might be to handle the presentation of the error but even that might not go as planned depending on the error.
A: An Error usually shouldn't be caught, as it indicates an abnormal condition that should never occur.
From the Java API Specification for the Error class:
An Error is a subclass of Throwable
that indicates serious problems that a
reasonable application should not try
to catch. Most such errors are
abnormal conditions. [...]
A method is not required to declare in
its throws clause any subclasses of
Error that might be thrown during the
execution of the method but not
caught, since these errors are
abnormal conditions that should never
occur.
As the specification mentions, an Error is only thrown in circumstances that are
Chances are, when an Error occurs, there is very little the application can do, and in some circumstances, the Java Virtual Machine itself may be in an unstable state (such as VirtualMachineError)
Although an Error is a subclass of Throwable which means that it can be caught by a try-catch clause, but it probably isn't really needed, as the application will be in an abnormal state when an Error is thrown by the JVM.
There's also a short section on this topic in Section 11.5 The Exception Hierarchy of the Java Language Specification, 2nd Edition.
A: If you are crazy enough to be creating a new unit test framework, your test runner will probably need to catch java.lang.AssertionError thrown by any test cases.
Otherwise, see other answers.
A: Never. You can never be sure that the application is able to execute the next line of code. If you get an OutOfMemoryError, you have no guarantee that you will be able to do anything reliably. Catch RuntimeException and checked Exceptions, but never Errors.
http://pmd.sourceforge.net/rules/strictexception.html
A: And there are a couple of other cases where if you catch an Error, you have to rethrow it. For example ThreadDeath should never be caught, it can cause big problem is you catch it in a contained environment (eg. an application server) :
An application should catch instances of this class only if it must clean up
after being terminated asynchronously. If ThreadDeath is caught by a method,
it is important that it be rethrown so that the thread actually dies.
A: Very, very rarely.
I did it only for one very very specific known cases.
For example, java.lang.UnsatisfiedLinkError could be throw if two independence ClassLoader load same DLL. (I agree that I should move the JAR to a shared classloader)
But most common case is that you needed logging in order to know what happened when user come to complain. You want a message or a popup to user, rather then silently dead.
Even programmer in C/C++, they pop an error and tell something people don't understand before it exit (e.g. memory failure).
A: In an Android application I am catching a java.lang.VerifyError. A library that I am using won't work in devices with an old version of the OS and the library code will throw such an error. I could of course avoid the error by checking the version of OS at runtime, but:
*
*The oldest supported SDK may change in future for the specific library
*The try-catch error block is part of a bigger falling back mechanism. Some specific devices, although they are supposed to support the library, throw exceptions. I catch VerifyError and all Exceptions to use a fall back solution.
A: it's quite handy to catch java.lang.AssertionError in a test environment...
A: Ideally we should not handle/catch errors. But there may be cases where we need to do, based on requirement of framework or application. Say i have a XML Parser daemon which implements DOM Parser which consumes more Memory. If there is a requirement like Parser thread should not be died when it gets OutOfMemoryError, instead it should handle it and send a message/mail to administrator of application/framework.
A: Generally you should always catch java.lang.Error and write it to a log or display it to the user. I work in support and see daily that programmers cannot tell what has happened in a program.
If you have a daemon thread then you must prevent it being terminated. In other cases your application will work correctly.
You should only catch java.lang.Error at the highest level.
If you look at the list of errors you will see that most can be handled. For example a ZipError occurs on reading corrupt zip files.
The most common errors are OutOfMemoryError and NoClassDefFoundError, which are both in most cases runtime problems.
For example:
int length = Integer.parseInt(xyz);
byte[] buffer = new byte[length];
can produce an OutOfMemoryError but it is a runtime problem and no reason to terminate your program.
NoClassDefFoundError occur mostly if a library is not present or if you work with another Java version. If it is an optional part of your program then you should not terminate your program.
I can give many more examples of why it is a good idea to catch Throwable at the top level and produce a helpful error message.
A: In multithreaded environment, you most often want to catch it! When you catch it, log it, and terminate whole application! If you don't do that, some thread that might be doing some crucial part would be dead, and rest of the application will think that everything is normal. Out of that, many unwanted situations can happen.
One smallest problem is that you wouldn't be able to easily find root of the problem, if other threads start throwing some exceptions because of one thread not working.
For example, usually loop should be:
try {
while (shouldRun()) {
doSomething();
}
}
catch (Throwable t) {
log(t);
stop();
System.exit(1);
}
Even in some cases, you would want to handle different Errors differently, for example, on OutOfMemoryError you would be able to close application regularly (even maybe free some memory, and continue), on some others, there is not much you can do.
A: Generally, never.
However, sometimes you need to catch specific errors.
If you're writing framework-ish code (loading 3rd party classes), it might be wise to catch LinkageError (no class def found, unsatisfied link, incompatible class change).
I've also seen some stupid 3rd-party code throwing subclasses of Error, so you'll have to handle those as well.
By the way, I'm not sure it isn't possible to recover from OutOfMemoryError.
A: ideally we should never catch Error in our Java application as it is an abnormal condition. The application would be in abnormal state and could result in carshing or giving some seriously wrong result.
A: It might be appropriate to catch error within unit tests that check an assertion is made. If someone disables assertions or otherwise deletes the assertion you would want to know
A: There is an Error when the JVM is no more working as expected, or is on the verge to. If you catch an error, there is no guarantee that the catch block will run, and even less that it will run till the end.
It will also depend on the running computer, the current memory state, so there is no way to test, try and do your best. You will only have an hasardous result.
You will also downgrade the readability of your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/352780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "122"
}
|
Q: CSS - Conditional for Exact Mobile Aspect Ratio I'm trying to have the mobile browser (iOS Safari) load a webpage with a different fullscreen exact-pixel-dimension image (.bg tag) based on the aspect ratio of the iOS device.
For some reason, every time, I try loading the page on an iPhone X (which has a rather long screen 2436x1125, so definitely greater than a 19/9 ratio in the third conditional below), it defaults to the middle option, i.e. the 16/9 option...
Each image is exact to the aspect ratio, so should fill up the screen completely, though for some reason currently the middle conditional (being for 16/9 and not 19/9) is cropping the sides on my long iPhone X. (right click/inspect to see the border)
body, html {
height: 100%; margin:0;padding:0;
width:100%;
}
.bg {
/* The image used */
background-image: url("640p.png");
/* Full height */
height: 100%; width:100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
@media (min-aspect-ratio: 1136/640) {
.bg {
background-image: url("640p.png"); height: 100%; width:100%;
}
}
@media (min-aspect-ratio: 16/9) and (max-aspect-ratio: 2/1) {
.bg {
background-image: url("1080p.png"); height: 100%; width:100%;
}
}
@media (min-aspect-ratio: 19/9) {
.bg {
background-image: url("1125p.png"); height: 100%; width:100%;
}
}
<html><body>
<div class="bg"></div>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51797358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Iterating through JSON with nested structure I have a JSON with the following structure:
data": {
"password": {
"en": "Password",
"ar": "Password",
"zh": "Password",
...
},
"confirmPassword": {
"en": "Confirm password",
"ar": "Confirm password",
...
},
"addressInputStrings": {
"en": {
"search": "Address",
"placeholder": "Start typing your address",
"addressNotListed": "My address is not listed",
"country": "Country of residence",
"street": "Street",
...
}
"fileUploadStrings"
{
"en":
{
"required": "Please upload a document.",
"fileUploadSuccessful": "File uploaded successfully: ",
"uploadError": {
"multipartContentTypeError": "The request couldn't be processed (Error 1)",
...
Basically "data" is the root, and it has a number of properties, each has a list of language codes. The value is usually a string. Sometimes there is a second level of nesting, and sometimes even a third one.
I need to iterate through the JSON and get the following output
[key] (tab) [value of "en"]
if the value of "en" is not a string but another object, then
[key].[nested key (in "en")] (tab) [value]
if there is another level of nesting, then
[key].[nested key (in "en")].[nested nested key] (tab) [value]
So for the example the output would look like this:
password (tab) Passsword
confirmPassword (tab) Confirm password
addressInputStrings.search (tab) Address
addressInputStrings.addressInputStrings.placeholder (tab) Start typing your address
addressInputStrings.addressNotListed (tab) My address is not listed
addressInputStrings.country (tab) Country of residence
addressInputStrings.street (tab) Street
fileUploadStrings.required (tab) Please upload a document
fileUploadStrings.fileUploadSuccessful (tab) File uploaded successfully:
fileUploadStrings.uploadError.multipartContentTypeErrorThe (tab) request couldn't be processed (Error 1)
I thought this would be easy using Newtonsoft.Json, but it's like the library is actively fighting me. When I try to iterate children on a JObject I get Jproperties instead of JObjects, where I expect to get the first child, I get the whole collection again, I keep getting exceptions left and right, and let's not forget almost nothing wants to evaluate in the Watch window when I'm paused in debugger, so no experimentation is possible there. The only option is to modify, build, debug, get an error, repeat.
Could I get a quick and dirty solution? Thank you.
A: It sounds like the root of the problem here is that you are misunderstanding the design of Json.Net's LINQ-to-JSON API. A JObject can never directly contain another JObject. A JObject only ever contains JProperty objects. Each JProperty has a name and a value. The value of a JProperty in turn can be another JObject (or it can be a JArray or JValue). Please see this answer to JContainer, JObject, JToken and Linq confusion for more information on the relationships in the JToken hierarchy.
After understanding the hierarchy, the key to getting the output you want is the Descendants() extension method. This will allow you to do a recursive traversal with a simple loop. To get your output you are basically looking for the Path and Value for each leaf JProperty in the entire JSON. You can identify a leaf by checking whether the Value is a JValue.
So, putting it all together, here is how you would do it (I'm assuming C# here since you did not specify a language in your question):
var root = JObject.Parse(json);
var leafProperties = root.Descendants()
.OfType<JProperty>()
.Where(p => p.Value is JValue);
foreach (var prop in leafProperties)
{
Console.WriteLine($"{prop.Path}\t{prop.Value}");
}
Fiddle: https://dotnetfiddle.net/l5Oqfb
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62023201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Remove 'u' from json data using Python I have a Python code which basically extracts the data from Amazon SQS, I need to index this JSON data to Elasticsearch. Currently my code looks like:
import os
import json
import uuid
import time
import boto.sqs
import boto
from boto.sqs.connection import SQSConnection
from boto.sqs.message import Message
from boto.sqs.message import RawMessage
from ConfigParser import SafeConfigParser
import ast
parser = SafeConfigParser()
parser.read('/home/ubuntu/config.ini')
#get details via config file
region = parser.get('default', 'aws_region')
access_key = parser.get('default', 'aws_access_key')
secret_key = parser.get('default', 'aws_secret_key')
queue_name = parser.get('default', 'sqs_queue_name')
sqs = boto.sqs.connect_to_region(region,aws_access_key_id=access_key,aws_secret_access_key=secret_key)
q = sqs.get_queue(queue_name) #SQS queue name
m = q.read(visibility_timeout=15)
if m == None:
print "No message!"
else:
a = m.get_body()
print a
print type(a)
new_list = json.loads(a)
print new_list
print type(new_list)
This produces a result as :
{
"facter": {
"blockdevice_xvda_size": 8589934592,
"blockdevices": "xvda,xvdb",
"fqdn": "ip-1-12-5-9.us-west-2.compute.internal",
"hardwaremodel": "x86_64",
"hostname": "ip-1-12-5-9",
"instanceid": "i-a54d7c",
"ipaddress": "1.12.5.9",
"is_virtual": "true",
"kernelrelease": "3.13.0-48-generic",
"lsbdistcodename": "trusty",
"lsbdistdescription": "Ubuntu 14.04.2 LTS",
"macaddress": "2:00:a:66:61:4f",
"memoryfree": "3.56 GB",
"memorytotal": "3.68 GB",
"netmask": "255.255.255.12",
"operatingsystem": "Ubuntu",
"operatingsystemrelease": "14.04",
"processor0": "Intel(R) Xeon(R) CPU E5-2670 v2 @ 2.50GHz",
"processorcount": "1",
"timezone": "UTC",
"uniqueid": "660a4f41",
"uptime": "23:36 hours"
}
}
<type 'unicode'>
{u'facter': {u'kernelrelease': u'3.13.0-48-generic', u'memoryfree': u'3.56 GB', u'memorytotal': u'3.68 GB', u'processorcount': u'1', u'timezone': u'UTC', u'operatingsystem': u'Ubuntu', u'uptime': u'23:36 hours', u'hostname': u'ip-1-12-5-9', u'is_virtual': u'true', u'blockdevices': u'xvda,xvdb', u'hardwaremodel': u'x86_64', u'netmask': u'255.255.255.192', u'blockdevice_xvda_size': 8589934592, u'uniqueid': u'660a4f41', u'ipaddress': u'10.102.65.79', u'lsbdistdescription': u'Ubuntu 14.04.2 LTS', u'macaddress': u'2:00:a:66:41:4f', u'operatingsystemrelease': u'14.04', u'processor0': u'Intel(R) Xeon(R) CPU E5-2670 v2 @ 2.50GHz', u'instanceid': u'i-a54d7c', u'fqdn': u'ip-1-12-5-9.us-west-2.compute.internal', u'lsbdistcodename': u'trusty'}}
<type 'dict'>
As you can see that its a dictionary having unicode. I need to extract "instanceid" from this dictionary and use it index it in ES. I am stuck on how to extract the index id. I tried:
ast.literal_eval(json.dumps())
What exactly am I doing wrong?
A: Since new_list is a dict you should be able to just extract that with a simple
instanceid = new_list['facter']['instanceid']
The u you see before your strings are just telling you that the strings are unicode strings, and not a "C-string".
In your case it doesn't matter, since there are no unicode characters in any of the dictionary keys.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33498675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "An error was encountered with the requested page" in jmeter even capture variables by using regular expression extractor I have used jmeter to record login flow of application , when i re run it there are some requests failing so i fetch dynamic values from earlier responses and supplies those values to subsequent requests
I am facing some issues there is State token in requests but format of this is changing dynamically so because of that when i rerun some time requests are passing some time failing
Here those are
Fail case
{"stateToken":"00UaBoY\x2D81AIL32Nz9qmUJrIarSv3OgfUdd8FHGSkb"}
{"stateToken":"00C8O4pt\x2DcSPEzHrt69zqmEGta9KbjdwywEVdkICku"}
{"stateToken":"00JgMsy7\x2DzXDP0gxaeWv4dj8EguFTWtnLxV\x2DBKTkIq"}
Working case
{"stateToken":"00fswJVHKpW7dNhNVK0bRclBBrsuMLHBBevJ8IS1Wz"}
{"stateToken":"00ZVZXpSJn7v3lxNTrEqy1mAGydgroO5apvoTlWH2u"}
My regular expression for capture state token is stateToken":"(.+?)"
what is issue here ?
the second issue is saml,relay state are not working even regax working fine in regax tester , i am getting "An error was encountered with the requested page". in debug sampler those 2 variables are getting and passed ( screenshot is attached )
Anyone have ideas related above 2 issues please give some ideas to sort out this
A: Your failing requeststokens have\x`.
You will have to encode the value and send the request.
*
*In HTTP Request
Check the filed URL encode?
*Encoding the value with function
A: It sounds like a bug in your application, I don't think it's JMeter issue, presumably it's due to presence of these \x2D characters (may be incorrect work of unicode escape)
I don't know what does your application expect instead of this \x2D try to inspect the JavaScript code of the application to see what it does do the tokens, when you figure this out you can replicate this token conversion logic in JSR223 PreProcessor and Groovy language
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69784422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Populate array with resource images I'm trying to make a Blackjack game in VB. What I'd like to do is populate an array with each of the cards so that I can randomly generate integers and use those integers to pull an index from the array, basically randomly selecting a card.
My problem is that I can't seem to get the images in the resources folder to go into the array. I'd like to use a For/Next loop to populate the array, as I would rather not manually assign all 52 cards to the array. I'm trying to do it like this:
Dim CardArray(51) As Image
Dim LoopIndexInteger As Integer
For LoopIndexInteger = 0 To 51
CardArray(LoopIndexInteger) = My.Resources.ResourceManager.GetObject(LoopIndexInteger)
Next
Where am I going wrong?
A: GetObject takes a resource name, not an index.
You need to construct the name of one of your resources.
The simplest way to do that is to name the resources Card0 through Card51 and call GetObject("Card" & CInt(LoopIndexInteger))
EDIT: You can also loop over My.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, false, true), but it may not be in order.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8024290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I return value of a column based on the min value of one column and max value of another column? Supposing I have a df like the following,
column1 | column2 | column3 |column4 | column5
A | B | 5 | 4234 | 123
A | B | 2 | 432 | 3243
A | B | 10 | 123 | 43
A | B | 1 | 123 | 45
A | B | 1 | 124 | 23243
A | B | 1 | 125 | 234
A | B | 1 | 126 | 23
Note: column4 is always unique
Desired df,
column1 | column2 | column3 |column4 | column5 |column6
A | B | 5 | 4234 | 123 |
A | B | 2 | 432 | 3243 |
A | B | 10 | 123 | 43 |
A | B | 1 | 123 | 45 |
A | B | 1 | 124 | 23243 |
A | B | 1 | 125 | 234 |
A | B | 1 | 126 | 23 | 23
I want to be able to groupby on the basis of column1 and column2, find the min value of column3 (in this case -> 1) followed by finding the max value of column4 (in this case -> 126) and return its corresponding column6 value (in this case -> 23).
Step 1 -> find the min value for a given [['column1', 'column2']] that is 1
column1 | column2 | column3 |column4 | column5 |column6
A | B | 5 | | 123 |
A | B | 2 | | 3243 |
A | B | 10 | | 43 |
A | B | **1** | 123 | 45 |
A | B | **1** | 124 | 23243 |
A | B | **1** | 125 | 234 |
A | B | **1** | 126 | 23 | 23
Step 2
find the max value of column 4 for a given [['column1', 'column2', 'column3']]
column1 | column2 | column3 |column4 | column5 |column6
A | B | 5 | | 123 |
A | B | 2 | | 3243 |
A | B | 10 | | 43 |
A | B | 1 | 123 | 45 |
A | B | 1 | 124 | 23243 |
A | B | 1 | 125 | 234 |
A | B | 1 | **126** | 23 | 23
Step 3 return the corresponding value of column5 that is 23
How can I achieve this?
A: You can try as follows
import pandas as pd
df = pd.DataFrame({
"column1":["A", "A", "A", "A", "A", "A", "A"],
"column2":["B", "B", "B", "B", "B", "B", "B"],
"column3":[5, 2, 10, 1, 1, 1, 1],
"column4":[4234, 432, 123, 123, 124, 125, 126],
"column5":[123, 3243, 43, 45, 23243, 234, 23]
})
df
column1 column2 column3 column4 column5
0 A B 5 4234 123
1 A B 2 432 3243
2 A B 10 123 43
3 A B 1 123 45
4 A B 1 124 23243
5 A B 1 125 234
6 A B 1 126 23
row_index = df.loc[df["column3"]==(df.groupby(["column1", "column2"])["column3"].min()).min()]["column4"].idxmax()
val_index = df["column5"].iloc[(df.loc[df["column3"]==(df.groupby(["column1", "column2"])["column3"].min()).min()]["column4"].idxmax())]
df.loc[row_index, "column6"] = val_index
df
column1 column2 column3 column4 column5 column6
0 A B 5 4234 123 NaN
1 A B 2 432 3243 NaN
2 A B 10 123 43 NaN
3 A B 1 123 45 NaN
4 A B 1 124 23243 NaN
5 A B 1 125 234 NaN
6 A B 1 126 23 23.0
If you want it in one line
df.loc[df.loc[df["column3"]==(df.groupby(["column1", "column2"])["column3"].min()).min()]["column4"].idxmax(), "column6"] = df["column5"].iloc[(df.loc[df["column3"]==(df.groupby(["column1", "column2"])["column3"].min()).min()]["column4"].idxmax())]
Another option
df.loc[(df[df['column4'] == df.loc[df['column3'] == df['column3'].min(), 'column4'].max()]["column5"]).index, "column6"] = df[df['column4'] == df.loc[df['column3'] == df['column3'].min(), 'column4'].max()]["column5"]
A: *
*find the rows with the min of column3 df.loc[df["column3"].eq(df["column3"].min())]
*of these rows find rows with max of column4
*rename and join back together
import io
import pandas as pd
df = pd.read_csv(io.StringIO("""column1 | column2 | column3 |column4 | column5
A | B | 5 | 4234 | 123
A | B | 2 | 432 | 3243
A | B | 10 | 123 | 43
A | B | 1 | 123 | 45
A | B | 1 | 124 | 23243
A | B | 1 | 125 | 234
A | B | 1 | 126 | 23 """), sep="|").pipe(lambda d: d.rename(columns={c:c.strip() for c in d.columns}))
df.groupby(["column1", "column2"], as_index=False).apply(
lambda df: df.join(
df.loc[df["column3"].eq(df["column3"].min())]
.loc[lambda d: d["column4"].eq(d["column4"].max()), "column5"]
.rename("column6")
)
)
column1
column2
column3
column4
column5
column6
0
A
B
5
4234
123
nan
1
A
B
2
432
3243
nan
2
A
B
10
123
43
nan
3
A
B
1
123
45
nan
4
A
B
1
124
23243
nan
5
A
B
1
125
234
nan
6
A
B
1
126
23
23
A: Another way is to groupby 2 times:
minval=df.groupby(['column1','column2'])['column3'].min().tolist()
maxval=df.loc[df['column3'].isin(minval)].groupby(['column1','column2'])['column4'].max().tolist()
df['column6']=df['column5'].where(df['column4'].isin(maxval))
output of df:
column1 column2 column3 column4 column5 column6
0 A B 5 4234 123 NaN
1 A B 2 432 3243 NaN
2 A B 10 123 43 NaN
3 A B 1 123 45 NaN
4 A B 1 124 23243 NaN
5 A B 1 125 234 NaN
6 A B 1 126 23 23.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68769578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery check dropdown selected value contains particular characters I would like to check the selected value in the dropdown on page load. If selected option has a text 'abc' then it disables another text field. If option 1 or 2 is selected in below example then it will disable a text. my code below disables the text field regardless of the selected value.
<select id="marks" name="studentmarks">
<option value="1">abc-test</option>
<option value="2">abc-test2</option>
<option value="3">cde-test3</option>
</select>
I have tried with this one but it sometimes disables even the selected option doesn't have the text 'abc'
$( window ).load(function() {
($('select[name="studentmarks"]').find("option:contains('abc')")){
$( "#score" ).prop( "disabled", true );
}
});
A: You can try like this, hope it help.
<!DOCTYPE html>
<html>
<head></head>
<body>
<select id="marks" name="studentmarks">
<option value="1">abc-test</option>
<option value="2">abc-test2</option>
<option value="3">cde-test3</option>
</select>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
jQuery(function($){
$('select[name="studentmarks"]').on('change', function(){
var selected_option = $('#marks option:selected');
console.log(selected_option.text());
if (selected_option.text().indexOf("abc") >= 0){
alert('abc');
}
else{
alert('None abc');
}
});
});
</script>
</html>
A: One possible approach is below:
jQuery(function($) {
// here we select the select element via its 'id',
// and chain the on() method, to use the anonymous
// function as the event-handler for the 'change'
// event:
$('#marks').on('change', function() {
// here we select the element with the id of 'score': We update that property using an
// assessment:
$('#score')
// we update its 'disabled' property via the prop()
// method (the first argument is the name of the
// property we wish to update, when used as a setter,
// as it is here) and we use $(this) to get the current
// element upon which the event was fired:
.prop('disabled', $(this)
// we find the option that was/is selected:
.find('option:selected')
// we retrieve its text (instead of its value),
// since your checks revolve around the text:
.text()
// text() returns a String, which we use along with
// String.prototype.startsWith() - which returns a
// Boolean true/false - based on the argument provided.
// if the string does start with 'abc' the assessment
// then returns true and the '#score' element is disabled,
// if the string does not start with 'abc' the
// assessment returns false, and the disabled property
// is set to false, so the element is enabled:
.startsWith('abc'));
// here we trigger the change event, so that the '#score'
// element is enabled/disabled appropriately on page-load:
}).change();
});
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
label {
display: block;
}
input[disabled] {
background: repeating-linear-gradient(45deg, transparent, transparent 5px, #ccca 5px, #ccca 10px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<label>Student marks:
<select id="marks" name="studentmarks">
<option value="1">abc-test</option>
<option value="2">abc-test2</option>
<option value="3">cde-test3</option>
</select>
</label>
<label>Score:
<input id="score" type="text">
</label>
</body>
JS Fiddle demo.
This is, of course, also possible in plain – though relatively modern – native JavaScript:
// listening for the DOMContentLoaded event to fire on the window, in order
// to delay running the contained JavaScript until after the page's content
// is available:
window.addEventListener('DOMContentLoaded', () => {
// using document.querySelector() to find the first element matching
// the supplied selector (this returns one element or null, so in
// production do sanity-check and prepare for error-handling):
const select = document.querySelector('#marks'),
// we create a new Event, in order that we can use it later:
changeEvent = new Event('change');
// we use EventTarget.addEventListener() to bind the anonymous function
// as the event-handler for the 'change' event:
select.addEventListener('change', function(event) {
// here we cache variables to be used, first we find the 'score'
// element:
const score = document.querySelector('#score'),
// we retrieve the element upon which the event was bound:
changed = event.currentTarget,
// we find the selected option, using spread syntax to
// convert the changed.options NodeList into an Array:
selectedOption = [...changed.options]
// we use Array.prototype.filter() to filter that Array:
.filter(
// using an Arrow function passing in the current <option>
// of the Array of <option> elements over which we're
// iterating into the function. We test each <option> to
// see if its 'selected' property is true (though
// truthy values will also pass with the way this is written):
(opt) => opt.selected
// we use Array.prototype.shift() to retrieve the first Array-
// element from the Array:
).shift(),
// we retrieve that <option> element's text:
optionText = selectedOption.text;
// here we set the disabled property of the 'score' element,
// again using String.prototype.startsWith() to obtain a
// Boolean value indicating whether string does start with
// 'abc' (true) or does not start with 'abc' (false):
score.disabled = optionText.startsWith('abc');
});
// here we use EventTarget.dispatchEvent() to trigger the created
// change Event on the <select> element in order to have the
// 'score' element appropriately disabled, or enabled, according
// to its initial state:
select.dispatchEvent(changeEvent);
});
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
label {
display: block;
}
input[disabled] {
background: repeating-linear-gradient(45deg, transparent, transparent 5px, #ccca 5px, #ccca 10px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<label>Student marks:
<select id="marks" name="studentmarks">
<option value="1">abc-test</option>
<option value="2">abc-test2</option>
<option value="3">cde-test3</option>
</select>
</label>
<label>Score:
<input id="score" type="text">
</label>
</body>
JS Fiddle demo.
References:
*
*JavaScript:
*Arrow functions.
*Array.prototype.filter().
*Array.prototype.shift().
*EventTarget.addEventListener().
*EventTarget.dispatchEvent().
*HTMLOptionElement.
*Spread syntax.
*String.prototype.startsWith().
*jQuery:
*find().
*on().
*prop().
*text().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66701079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CustomCell Crash I am using CustomCell tableview, download data and binding it.When i tap multiple time am getting this error.
[NSCFString numberOfSectionsInTableView:]: unrecognized selector sent to instance 0x1bd170
Sat Jan 22 12:03:26 unknown Fridge[535] <Error>: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString numberOfSectionsInTableView:]: unrecognized selector sent to instance 0x1bd170'
*** Call stack at first throw:
(
0 CoreFoundation 0x314d0987 __exceptionPreprocess + 114
1 libobjc.A.dylib 0x319a149d objc_exception_throw + 24
2 CoreFoundation 0x314d2133 -[NSObject(NSObject) doesNotRecognizeSelector:] + 102
3 CoreFoundation 0x31479aa9 ___forwarding___ + 508
4 CoreFoundation 0x31479860 _CF_forwarding_prep_0 + 48
5 UIKit 0x339023fb -[UITableViewRowData(UITableViewRowDataPrivate) _updateNumSections] + 66
6 UIKit 0x3390235b -[UITableViewRowData invalidateAllSections] + 50
7 UIKit 0x33902111 -[UITableView(_UITableViewPrivate) _updateRowData] + 64
8 UIKit 0x33902069 -[UITableView noteNumberOfRowsChanged] + 64
9 UIKit 0x33901bff -[UITableView reloadData] + 582
10 UIKit 0x33904a0b -[UITableView _reloadDataIfNeeded] + 50
11 UIKit 0x33904e63 -[UITableView layoutSubviews] + 18
12 UIKit 0x338b10cf -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 26
13 CoreFoundation 0x3146ebbf -[NSObject(NSObject) performSelector:withObject:] + 22
14 QuartzCore 0x30a6c685 -[CALayer layoutSublayers] + 120
15 QuartzCore 0x30a6c43d CALayerLayoutIfNeeded + 184
16 QuartzCore 0x30a6656d _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 212
17 QuartzCore 0x30a66383 _ZN2CA11Transaction6commitEv + 190
18 QuartzCore 0x30a89f9d _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 52
19 CoreFoundation 0x31460c59 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 16
20 CoreFoundation 0x31460acd __CFRunLoopDoObservers + 412
21 CoreFoundation 0x314580cb __CFRunLoopRun + 854
22 CoreFoundation 0x31457c87 CFRunLoopRunSpecific + 230
23 CoreFoundation 0x31457b8f CFRunLoopRunInMode + 58
24 GraphicsServices 0x35d664ab GSEventRunModal + 114
25 GraphicsServices 0x35d66557 GSEventRun + 62
26 UIKit 0x338d5329 -[UIApplication _run] + 412
27 UIKit 0x338d2e93 UIApplicationMain + 670
28 Fridge 0x00002a7f main + 70
29 Fridge 0x00002a34 start + 40
)
Sat Jan 22 12:03:26 unknown UIKitApplication:com.sdi.Fridge[0xa6da][535] <Notice>: terminate called after throwing an instance of 'NSException'
**Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CALayer numberOfSectionsInTableView:]: unrecognized selector sent to instance 0x184250'**
Thanks
A: Thanks for the detail view of your problem but the only important part is this
-[NSCFString numberOfSectionsInTableView:]: unrecognized selector
It tells that you are calling the method numberOfSectionsInTableView: on a NSCFString
which is seem to be wrong
so check where is that method called in your code
And also the rest is not require in your case.
Edit:
did you release your custom cell in the delegate method tableview. if yes than use autorelease instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4766520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SQL query to get all unique rows with uid I want to see which user has received the most highfives using a SQL query. My table looks like following, id | uid | ip. Now, I want to count the amount of rows a uid has, but it has to be unique with the ip. So nobody can give multiple highfives to a person.
I searched around online, and I couldn't find anything about this. If anyone could help me with this, I would be grateful.
A: you can try like below
select ip, count(distinct uid) from table t
group by ip
A: SELECT uid,COUNT(ip)NoOfVotes FROM
(SELECT uid,ip,Serial=ROW_NUMBER() OVER(PARTITION BY ip,uid ORDER BY uid) FROM
dbo.tbl_user)A
WHERE Serial=1
GROUP BY uid
I think this will give you perfect vote counting. Using Row Number actively remove duplicates from same ip,same uid. Voting to multiple uid from same ip is allowed in this query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53995185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Recycler swipe left and swipe right perform different actions I have the following recycler view code that that allows the user to swipe right (deleting card from view and also deleting data from SQLite db) and also allowing the user to move tags to rearrange. It works. I'm happy.
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
//awesome code when user grabs recycler card to reorder
}
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
//awesome code to run when user drops card and completes reorder
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//awesome code when swiping right to remove recycler card and delete SQLite data
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
Now, I want to add the ability to swipe LEFT and perform something different from swiping RIGHT. All the solutions I've found so far would require a rewrite of my code. Any suggestions to add SWIPE LEFT to my existing code?
A: On onSwiped method, add-
if (direction == ItemTouchHelper.RIGHT) {
//whatever code you want the swipe to perform
}
then another one for left swipe-
if (direction == ItemTouchHelper.LEFT) {
//whatever code you want the swipe to perform
}
A: Make use of the direction argument to onSwiped(). See the documentation. You can make adjustments depending upon whether you are swiping right or left.
A: For me, direction returns START/END not LEFT/RIGHT, so this is what i have to do.
if(direction == ItemTouchHelper.START) {
// DO Action for Left
} else if(direction == ItemTouchHelper.END) {
// DO Action for Right
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42875299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: SQL 2008 HierarchyID - Select X descendants down How can I query a table which has a column of data type HIERARCHYID and get a list of descendants X levels deep under an employee?
Here is the current structure:
CREATE TABLE [dbo].[Employees](
[NodeId] [hierarchyid] NOT NULL,
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](120) NULL,
[MiddleInitial] [varchar](1) NULL,
[LastName] [varchar](120) NULL,
[DepartmentId] [int] NULL,
[Title] [varchar](120) NULL,
[PhoneNumber] [varchar](20) NULL,
[IM] [varchar](120) NULL,
[Photo] [varbinary](max) NULL,
[Bio] [varchar](400) NULL,
[Active] [bit] NULL,
[ManagerId] [int] NULL
)
A: I wanted to add a little to the above. In addition to selecting a branch of a tree, you often want descendants of only a certain depth. To accomplish this, many tables using add an additional computed column for "depth" ( something like [Depth] AS (myHierarchy.GetLevel]() ). With this extra column you can run queries like the following to limit by depth.
SELECT @MaxDepth = 3,
SELECT @theParent = Hierarchy,
@theParentDepth = Depth
FROM myTreeTable T
WHERE T.RowID = @RowID
SELECT myHierarchy
FROM myTreeTable T
WHERE T.myHierarchy.IsDescendantOf(@theParent) = 1 AND
T.Depth < (@theParentDepth + @MaxDepth)
Note, you may want to index the computed column (probably combined with or including some other columns) if you are relying on it heavily.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2768652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can i get the call-sid from response of callback in twilios AddOn's "IBM Watson" We enable the Twilios AddOn "IBM Watson Speech to Text" for recording transcribe.and we set our server webhook while enabling the addon. Now twilio calling webhook once call is completely done. after completing call twilio give response in that webhook In Nodejs.For handling that call response we need "Call Sid".In webhook response we cannot get "callSid".So how we can identify that response is for this particular call...?
anyone help me to how can find call-sid in response?
Callback response is
{
"status": "successful",
"message": null,
"code": null,
"results": {
"ibm_watson_speechtotext": {
"request_sid": "**************",
"status": "successful",
"message": null,
"code": null,
"payload": [{
"content_type": "application/json",
"url": "*************/Data"
}],
"links": {
"add_on_result": "***********/Accounts/********/Recordings/**********/AddOnResults/******",
"payloads": "https://api.twilio.com/2010-04-01/Accounts/******/Recordings/*******/AddOnResults/******/Payloads",
"recording": "https://api.twilio.com/2010-04-01/Accounts/******/Recordings/*******"
}
}
}
}
Thank you for help
A: When you get the Add-on result it comes as part of the Twilio voice webhook, with all the normal request parameters as well as an extra AddOns parameter which contains the JSON that you have shared above.
Webhook requests from Twilio are in the format application/x-www-form-urlencoded and then within the AddOns parameter the data is a JSON string. In a (Ruby-like) pseudo code, you can access the call sid and the add on data like this:
post "/webhook" do
call_sid = params["CallSid"]
add_on_json = params["AddOns"]
add_on_data = JSON.parse(add_on_json)
# return TwiML
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71792315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unable to load a file at WEB-INF location There is a json file in my war in the following location
WEB-INF/classes/META-INF/jsonFolder/file.json
I am trying to access file using the path and following method to load my file.
public static File deserializeJSONFile() throws IOException {
File file = null;
OutputStream outStream = null;
String jsonPath = "jsonFolder/file.json";
try (InputStream inputStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(jsonPath)) {
in = inputStream;
if (in != null) {
byte[] bufferArray = new byte[in.available()];
in.read(bufferArray);
file = new File("tempJsonFile.json");
outStream = new FileOutputStream(file);
outStream.write(bufferArray);
}
} finally {
if (outStream != null) {
outStream.close();
}
}
if (null == in) {
String errorMessage = "JSON file: " + jsonPath + " could not be loaded";
FileNotFoundException fileNotFoundException = new FileNotFoundException(errorMessage);
logger.error(errorMessage, fileNotFoundException);
throw fileNotFoundException;
}
return file ;
}
with which all my unit tests pass. On deployment of my app, I see the file not found exception for jsonFolder/file.json. When I traced the actual location as where it is searching, it is looking at,
C:\Program Files\eclipse-mars\jsonFolder\file.json
which is incorrect. I tried different classloader methods but it did not help. One rule is I should not modify pom.xml to make this work. How can I load the file?
A:
There is a json file in my war in the following location
WEB-INF->classes->META-INF->jsonFolder->file.json
So its name as a resource is META-INF/jsonFolder/file.json. Not what you have in your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46244413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: my smart contract is not responding and error saying web3 is not defined [error saying web3 is not defined][1]<script>
var myContract;
async function CheckMetamaskConnection() {
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(window.ethereum);
try {
// Request account access if needed
await ethereum.enable();
// Acccounts now exposed
return true;
} catch (error) {
// User denied account access...
return false;
}
}
// Legacy dapp browsers...
else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Acccounts always exposed
return true;
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
return false;
}
}
$(document).ready(async function () {
var IsMetamask = await CheckMetamaskConnection();
if (IsMetamask) {
myContract = await web3.eth.contract(SmartContractABI).at(SmartContractAddress);
getCandidate(1);
getCandidate(2);
await myContract.eventVote({
fromBlock:0
}, function(err, event){
console.log("event :", event);
getCandidate(event.args._candidateid.toNumber());
});
console.log("myContract :", myContract);
console.log("Metamask detected!")
} else {
console.log("Metamask not detected");
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Metamask not detected!',
onClose() {
location.reload();
}
});
}
});
async function getCandidate(cad){
await myContract.candidates(cad, function(err, result){
if (!err) {
console.log("result : ", result);
document.getElementById("cad" + cad).innerHTML = result[1];
document.getElementById("cad"+cad+'count').innerHTML = result[2].toNumber();
}
});
}
async function Vote(cad){
await myContract.vote(cad, function(err, result){
if(!err){
console.log("We are winning!");
} else{
console.log("Can not connect to the smart contract");
}
})
}
</script>`
i have node.js and metamask in my system(windows 10)
i cloned you project from github and runned it by following command
npm install
node index.js
the UI deployed perfectly in localhost:3000 but when i try to vote the transaction is not working!!!
then i saw content on smart contract is not rendering!!!
then i checked metamask , which was connected and have 1 ether on ropsten network!!!
then i try ganache (local blockchain provider) and still the transaction is not working!!!
then i paste the smart contract in remix and get the ABI and smart contract address and still not working!!!
then i goto developer tool of browser and saw below error!!!!...i have no idea of this error!!!!...how can i solve this???
A: The error can be happening because the loading of Web3. Please, try this function:
async loadWeb3(){
if(window.ethereum){
window.web3 = new Web3(window.ethereum)
await window.ethereum.request({ method: 'eth_requestAccounts' })
}
else if(window.web3){
window.web3 = new Web3(window.ethereum)
}
else{
window.alert("Non-Ethereum browser detected. You should consider trying MetaMask!")
}
}
Also, do not forget to add the import on your javascript class:
import Web3 from 'web3'
and install the import with the npm:
npm i web3 --save
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65932405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error while executing command: conda activate command on Linux EC2 instance I am building a build server on AWS as part of my pipeline. I am using a buildspec file, which runs the following commands after my code is copied over to the linux instance, using the image (aws/codebuild/amazonlinux2-x86_64-standard:2.0):
- echo 'Install Conda to run python'
- echo 'Download conda from web'
- wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh
- echo 'Install miniconda'
- sh ~/miniconda.sh -b -p $HOME/miniconda
- eval "$(~/miniconda/bin/conda shell.bash hook)"
- echo 'cd to outbound and list'
- cd outbound
- echo 'create conda environment'
- conda env create -f environment_droplet.yml
- conda env list
- bash
- conda init bash
- echo "conda activate calme" >> ~/.bash_profile
- echo ". ~/miniconda/etc/profile.d/conda.sh" >> ~/.bash_profile
- echo "export PATH=~/miniconda/bin:$PATH" >> ~/.bash_profile
- . ~/.bash_profile
- exec bash
- conda init bash
- conda activate calme
However, the last command 'conda activate is not successful and results in the error:
[Container] 2020/08/30 20:38:14 Running command conda init bash
no change /root/miniconda/condabin/conda
no change /root/miniconda/bin/conda
no change /root/miniconda/bin/conda-env
no change /root/miniconda/bin/activate
no change /root/miniconda/bin/deactivate
no change /root/miniconda/etc/profile.d/conda.sh
no change /root/miniconda/etc/fish/conf.d/conda.fish
no change /root/miniconda/shell/condabin/Conda.psm1
no change /root/miniconda/shell/condabin/conda-hook.ps1
no change /root/miniconda/lib/python3.8/site-packages/xontrib/conda.xsh
no change /root/miniconda/etc/profile.d/conda.csh
no change /root/.bashrc
No action taken.
[Container] 2020/08/30 20:38:14 Running command conda activate calme
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run
$ conda init <SHELL_NAME>
Currently supported shells are:
- bash
- fish
- tcsh
- xonsh
- zsh
- powershell
See 'conda init --help' for more information and options.
IMPORTANT: You may need to close and restart your shell after running 'conda init'.
[Container] 2020/08/30 20:38:14 Command did not exit successfully conda activate calme exit status 1
[Container] 2020/08/30 20:38:14 Phase complete: PRE_BUILD State: FAILED
[Container] 2020/08/30 20:38:14 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: conda activate calme. Reason: exit status 1
As you can see, from my buildspec snippet, I am reloading the .bash_profile, applying conda init bash and creating a new bash instance too. I believed all the above commands would help reset the existing terminal, so conda activate is a recognised command - but that has not been the case.
I do not have this problem when creating a standalone EC2 instance, as I can restart the terminal / close the connection and reconnect. However, I need to be able to activate conda via the buildspec and the ec2 instance created for the build of the project. Any help is appreciated
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63662111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need to fetch email from mail server immediately I would like to "misuse" my email a little for a printing work. I have the whole setup ready but lack how to get my emails from my mailserver immediately as soon they arrive.
In short I will get an email with a pdf attachment and need to print the attachement. It works well with procmail, uudeview and a script to print pdf files. However I need to get download the email immediately which does not work yet.
I was looking in both fetchmail and getmail. As far I understood fetchmail only works with a cronjob or daemon. I don't think that a cronjob should be run every 1 second.
I would be very grateful to learn if this can be achieved with getmail or if other programs are availbale to do this.
A: Perhaps update your .forward file to immediately forward the mail to procmail? Or setup a rule to forward the mail to a system you control where you can do the processing immediately?
The .procmailrc setup on the incoming host would look like:
"|IFS=' '&&p=/usr/local/bin/procmail&&test -f $p&&exec $p -f-||exit 75#some_string"
You could also use something like AWS SNS and Lambda to process the mail events.
If you don't have those options, polling frequently would be your best bet. You can setup a script to poll every few seconds in a loop without generating much load on the server. Typically your cron job would check if the script is running, and if not, relaunch it, otherwise do nothing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55544486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: In Django, whitenoise do not show static files? I am trying to show static files while debug=false.I am using whitenoise library but still website don't show the static files and media files. My settings.py file like this:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
Urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('games.urls')),
path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
path('sentry-debug/', trigger_error),
path('ajax_calls/search/', autocompleteModel),
path('accounts/', include('allauth.urls')),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
A: did you collect your static folder
python manage.py collectstatic
and in your main projects urls.py
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
A: To use WhiteNoise with django :
*
*Make sure staticfiles is configured correctly
In the project settings.py file set
STATIC_ROOT = BASE_DIR / 'staticfiles'
This staticfiles folder will be the folder where collectstatic will pull out all your static files.
*Enable WhiteNoise
Always in settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
NB : The WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware.
That is all, but if you want more performance you should enable caching and compression support like this :
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
If you want to apply compression but don’t want the caching behaviour then you can use:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
Follow these steps and all will be ok. WhiteNoise Documentation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69077368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to rename a column in pandas if column name has space. For example : Nom restaurant i am trying to rename my column name, but however it does not change because of space. my column name is Nom restaurant i already have tried
df.rename(columns = {'Nom restaurant':'Names', 'x_coor':'X_coor','y_coor':'Y_coor','Weight':'Weights'}, inplace =True)
Actually my goal is change only mentioned column name, but after many try i failed, and using this piece of code. All column names changed except first one. The problem is about space in first column name.
Output of df.head
Nom restaurant X_coor Y_coor
0 ARBUSTES 48.828431 2.309284
1 CAULAINCOURT 48.889552 2.339419
2 MARCHE DE L'EUROPE 48.877284 2.313452
3 LA QUINTINIE 48.839301 2.30718
4 AU MAIRE 48.864445 2.357714
Output of df.columns
Index(['Nom restaurant ', 'X_coor', 'Y_coor'], dtype='object')
A: You need to do
df = df.rename(columns = {'Nom restaurant ':'Names', 'x_coor':'X_coor','y_coor':'Y_coor','Weight':'Weights'})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59543215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What is the difference between these two programs which compute triangular numbers? Both of these codes compile, but only the second one does what I want it to.
First Code:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main()
{
int TriNumber = 0;
int n;
for(n = 5; n <= 50; n += 5)
TriNumber = ((n + 1) * n) / 2;
printf("The trianglular number of %d is %d\n", n, TriNumber);
}
Which outputs:
The trianglular number of 55 is 1275
The below program does what I want it to: it prints the triangular number for every fifth integer between 5 and 50.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main()
{
int TriNumber = 0;
int n;
for(n = 5; n <= 50; n += 5)
printf("The trianglular number of %d is %d\n", n, TriNumber = (((n + 1) * n) / 2));
}
Which gives my desired output:
The trianglular number of 5 is 15
The trianglular number of 10 is 55
The trianglular number of 15 is 120
The trianglular number of 20 is 210
The trianglular number of 25 is 325
The trianglular number of 30 is 465
The trianglular number of 35 is 630
The trianglular number of 40 is 820
The trianglular number of 45 is 1035
The trianglular number of 50 is 1275
I don't understand why putting TriNumber = ((n + 1) * n) / 2; on its own line in the first code and within the printf function in the second code would have such different results.
A: A for loop (or any other control structure, for that matter) without curly braces operates on one statement only. So the first snippet would loop over the TriNumber calculation, but only call printf once the loop is done. It's equivalent to writing
for(n = 5; n <= 50; n += 5) {
TriNumber = ((n + 1) * n) / 2;
}
printf("The trianglular number of %d is %d\n", n, TriNumber);
In order to get it to work as you expected, you could add the curly braces yourself, around both statements:
for(n = 5; n <= 50; n += 5) {
TriNumber = ((n + 1) * n) / 2;
printf("The trianglular number of %d is %d\n", n, TriNumber);
}
A: ● In your first case, the for loop computes the TriNumber till the condition satisfies and then moves onto the next statement; i.e, the printf:
for(n = 5; n <= 50; n += 5)
TriNumber = ((n + 1) * n) / 2;
printf("The trianglular number of %d is %d\n", n, TriNumber);
This is similar to (for better understanding):
for(n = 5; n <= 50; n += 5)
{
TriNumber = ((n + 1) * n) / 2;
}
printf("The triangular number of %d is %d\n", n, TriNumber);
That's why you get a single statement output stating:
The triangular number of 55 is 1275
● While in your second case, the for loop computes the TriNumber and prints it everytime as far as the loop condition is satisfied, since the printf here is the very next statement of the for loop that gets executed.
for(n = 5; n <= 50; n += 5)
printf("The trianglular number of %d is %d\n", n, TriNumber = (((n + 1) * n) / 2));
which is similar to the below code even without the braces {}:
for(n = 5; n <= 50; n += 5)
{
printf("The trianglular number of %d is %d\n", n, TriNumber = (((n + 1) * n) / 2));
}
This is valid for not only for loop but all other control structure like while, if;etc that operates on the very next statement without the {} braces as said by Mureinik.
A: In the first case you print after last loop iteration and as result n get extra increment by 5 and you see 55. In the second case you print right from last iteration and loop counter is not extra increased yet and you see 50.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38708029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Firebase Auth: A user (email) logged using signInWithEmailAndPassword, won't work with signInWithRedirect I'm building a Web application that uses Google Identity Platform to authenticate users.
All users belong to an Azure AD Domain, which is connected to Google Identity Platform through the use of an OIDC Provider, as per documentation.
Code wise, the authentication is performed using Firebase JS SDK (9.6.11).
When the application starts, there is no OIDC Provider to the Azure AD Domain (mydomain.com).
This configuration is created within the web application.
As there is no OIDC Provider to the Azure AD Domain, no user can yet login.
As such, in order to configure the Azure AD settings in the Web application, a temporary user is created in Goggle Identity Platform, so the User can login into the Web application:
Once the user is created, the user **is now able to login, **, using the password set on Google Identity.
Once the Azure AD Settings are configured, the Web application:
*
*DELETES the temporary user from Google Identity,
*Creates an OIDC Provider on Google Identity, connected to the configured Azure AD Domain (see image as an example of the OIDC Provider settings that the app would create):
The above provider is used to login users from Azure AD (mydomain.com), using the signInWithRedirect function, as per the documentation.
import { getAuth, signInWithRedirect, getRedirectResult } from "firebase/auth";
const auth = getAuth();
const provider = new OAuthProvider("MyDomainTenantID");
provider.setCustomParameters({
login_hint: user,
});
signInWithRedirect(auth, provider);
getRedirectResult(auth)
.then((result) => {
// User is signed in.
});
After configuring the Azure AD OIDC provider, all the Azure AD users (mydomain.com) are now able to log in into the Web application, EXCEPT the user that was used as the temporary user.
In the above example, [email protected], is not able to Log In into the Web application through the same Azure AD OIDC provider.
Please note, that the user no longer exists on Google Identity, as it was removed, so it can be logged in through the Azure AD OIDC provider, and recreated by the JIT process on a successful login.
Analyzing the Console, the call to https://www.googleapis.com/identitytoolkit/v3/relyingparty/createAuthUri fails with a 400 Error: Firebase: Error (auth/operation-not-allowed)
The POST Request body:
{
"providerId": "MyDomainTenantID",
"continueUri": "https://xxx.firebaseapp.com/__/auth/handler",
"customParameter": {
"login_hint": "[email protected]"
},
"tenantId": "GoogleIdentityTenantId"
}
As mentioned, ALL users from the same Azure AD are able to login, EXCEPT the one that was initially used as an Email/Password user.
According to Firebase documentation, the auth/operation-not-allowed error occurs when:
The provided sign-in provider is disabled for your Firebase project. Enable it from the Sign-in Method section of the Firebase console.
BUT, this is not the case:
*
*The OIDC provider connected to Azure AD is enabled
*All the users from the Azure AD Domain (except [email protected]), can successfully login.
I followed all the guidelines from Firebase, and i can't understand why that specific user is not being able to login.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71969888",
"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.