id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23533100
|
DC Cassandra
*
*Cassandra node 1
DC Solr
*
*Solr node 1 <-- new node (actually, a replacement for an old node; we followed the steps for "replacing a dead node")
*Solr node 2
*Solr node 3
*Solr node 4
*Solr node 5
Our Cassandra data is approximately 962gb. Replication factor is 1 for both DCs. Is it normal for the new node to be in "Active - Joining" state for several days? Is there a way to know the progress?
Last week, there was a time when we had to kill and restart the DSE process because it began throwing "too many open files" exception. Right now, the system log is full of messages about completed compaction/flushing tasks (no errors so far).
EDIT:
The node is still in "Active - Joining" state as of this moment. It's been exactly a week since we restarted the DSE process in that node. I started monitoring the size of the solr.data directory yesterday and so far I haven't seen an increase. The system.log is still filled with compacting/flushing messages.
One thing that bothers me is that in OpsCenter Nodes screen (ring/list view), the node is shown under the "Cassandra" DC even though the node is a Solr node. In nodetool status, nodetool ring, and dsetool ring, the node is listed under the correct DC.
EDIT:
We decided to restart the bootstrap process from scratch by deleting the data and commitlog directories. Unfortunately, during the subsequent bootstrap attempt:
*
*The stream from node 3 to node 1 (the new node) failed with an exception: ERROR [STREAM-OUT-/] 2014-04-01 01:14:40,887 CassandraDaemon.java (line 196) Exception in thread Thread[STREAM-OUT-/,5,main]
*The stream from node 4 to node 1 never started. The last relevant line in node 4's system.log is: StreamResultFuture.java (line 116) Received streaming plan for Bootstrap. It should have been followed by: Prepare completed. Receiving 0 files(0 bytes), sending x files(y bytes)
How can I force those streams to be retried?
| |
doc_23533101
|
X
1
1
0
0
0
1
1
0
Given that sequence of numbers I need extract the last number of a sequence of "ones" until appear a 0. That is what I want:
X Seq
1 1
1 2
1 3
0 1
0 2
0 3
1 1
1 2
0 1
1 1
1 2
1 3
0 1
I need create a new dataset with the numbers in bold, that is:
Seq1
3
2
3
Thanks for any advice.
A: Use a proc summary with notsorted option here:
data math;
input x;
datalines;
1
1
1
0
0
0
1
1
0
1
0
1
1
1
1
0
1
;
run;
proc summary data=math;
by x notsorted;
class x;
output Out=z;
run;
data z (drop=_type_ x);
set z (rename=(_FREQ_=COUNT));
where _type_=1 and x=1;/*if you are looking for other number then 1, replace it here*/
run;
proc print data=z noobs;
run;
result is:
A: You can create group variables using a lag and then keep the last observation of each group you have created:
data temp;
input x $;
datalines;
1
1
1
0
0
0
1
1
0
1
1
1
0
;
run;
data temp2;
set temp;
retain flag;
if lag(x) > x then flag = _n_;
if x = 0 then delete;
run;
data temp3 (keep = seq1);
set temp2;
seq1 + 1;
by flag;
if first.flag then seq1 = 1;
if last.flag then save = 1;
if missing(save) then delete;
run;
A: Here's a solution using only one data step with a retain statement.
data have;
input x @@;
output;
datalines;
1 1 1 0 0 0 1 1 0 1 0 1 1 1 1 0 1
;
data want(keep = count);
set have end = last;
retain x_previous . count .;
if x = 0 then do;
if x_previous = 1 then do;
output;
count = 0;
end;
end;
else if x = 1 then count + 1;
if last = 1 and count > 0 then output;
x_previous = x;
run;
Results
count
-----
3
2
1
4
1
A: One more option - use the NOTSORTED BY group option.
Data want;
Set have;
By x NOTSORTED;
Retain count;
If first.x then count=1;
Else count+1;
If last.x then output;
Keep count;
Run;
| |
doc_23533102
|
I want to open a specific folderlocation depending on which radiobuttons are checked in the groupboxes.
So let's say Option 1 and Option B open then Desktop and Option 2 and Option A some Folder on the Desktop.
I know how to run it with a single radiobutton but have some difficulties in how to make it work with 2 Groupboxes.
A: If you would have shown code would be better to understand your terminologies. For your case you could use nested for and if like
//Some path which ever you want
string[] paths = { Environment.GetFolderPath(Environment.SpecialFolder.Desktop), Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "C:\\"};
string[] Folders = { "SomeFolder", "AnyFolder", "YesThisFolder" };
string calcFolderPath="";
for(int i=0;i<=1;i++) //this is for group
{
for(int j=0;j<=2;j++) //this is for option / radio button
{
//You have to check if the group option is checked or not
if(group[i].option[j].checked) //This might not work
{
if(i==0)
{
calcFolderPath = path[j];
}
else
{
calcFolderPath = calcFolderPath + Folders[j];
}
}
}
}
This is just an idea. This program might not work as it is because it is not been tested.
This program depicts that the first outer loop would check run for 2 times that is to check the number of groups we have. The inner loop is the number of radio button we have in the groups. Then we are checking if the group's option button is checked or not. If it is checked than we are checking if it is group1 than it is taking the path and if group2 than it is taking the folder name.
Hope this helps
Edit
After your comment it would be somthing like
string path = "";
string foldersName = "";
string completepath = "";
private void optionButton1_CheckedChanged(object sender, EventArgs e)
{
if (optionButtonA.Checked == true)
{
path = "C:\\Users\\z003cypv\\Desktop";
}
completepath = CalcCompletePath();
}
private void optionButton2_CheckedChanged(object sender, EventArgs e)
{
if (optionButtonA.Checked == true)
{
path = "C:\\Users\\z003cypv\\Documents";
}
completepath = CalcCompletePath();
}
private void optionButton3_CheckedChanged(object sender, EventArgs e)
{
if (optionButtonA.Checked == true)
{
path = "C:\\Users\\z003cypv\\Pictures";
}
completepath = CalcCompletePath();
}
Then for folders
private void optionButtonA_CheckedChanged(object sender, EventArgs e)
{
if (optionButtonA.Checked == true)
{
foldersName = "SomeName";
}
completepath = CalcCompletePath();
}
private void optionButtonB_CheckedChanged(object sender, EventArgs e)
{
if (optionButtonA.Checked == true)
{
foldersName = "NameFolder";
}
completepath = CalcCompletePath();
}
private void optionButtonC_CheckedChanged(object sender, EventArgs e)
{
if (optionButtonA.Checked == true)
{
foldersName = "SomeFolderName";
}
completepath = CalcCompletePath();
}
public string CalcCompletePath();
{
return path + foldersName;
}
But this is a very inefficient way of doing the things. I would still prefer the first option.
| |
doc_23533103
|
export default class AssignmentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
questions: [],
questionId: this.props.questionId,
pictures: [],
};
this.handleTextSubmit = this.handleTextSubmit.bind(this);
this.assignUserToAssignment = this.assignUserToAssignment.bind(this);
this.handleImageSubmit = this.handleImageSubmit.bind(this);
this.onImageDrop = this.onImageDrop.bind(this);
this.handleImageSubmit = this.handleImageSubmit.bind(this);
}
async componentDidMount() {
const questionsRef = firebase.database().ref('Works').orderByChild('firebaseKey').equalTo(this.props.questionId);
await questionsRef.on('value', snapshot => {
let questions = snapshot.val();
let newState = [];
for (let question in questions) {
newState.push({
id: question,
category: questions[question].category,
level: questions[question].level,
pointAmount: questions[question].pointAmount,
pointBoost: questions[question].pointBoost,
photoURL: questions[question].photoURL,
workText: questions[question].workText,
});
}
try {
this.setState({
questions: newState
});
} catch (e) {
console.log('assignment', e)
}
});
await this.assignUserToAssignment();
}
async assignUserToAssignment() {
var currentUser = firebase.auth().currentUser;
var currentAssignment = firebase.database().ref('Works').child(this.props.questionId);
await currentAssignment.child('available').set(false).catch(e => console.log(e));
await currentAssignment.child('state').set('Taken').catch(e => console.log(e));
await currentAssignment.child('solverID').set(currentUser.uid).catch(e => console.log(e));
await firebase.database().ref('Users').child(currentUser.uid).child('assignedWork').set(this.props.questionId).catch(e => console.log(e));
}
async handleTextSubmit(e) {
e.preventDefault();
var textAnswer = document.getElementById('textAnswer').value;
var currentAssignment = firebase.database().ref('Works').child(this.props.questionId);
if (textAnswer.length > 0) {
let pushRef = currentAssignment.child('answers').push();
pushRef.set({
textAnswer: textAnswer,
date: Time.generate(),
seen: false,
firebaseKey: pushRef.getKey(),
workKey: this.props.questionId
}).catch(e => console.log('push->set', e))
}
}
async onImageDrop(files) {
await this.setState({
uploadedFile: files[0]
});
this.handleImageSubmit(files[0]);
}
async handleImageSubmit(file) {
// Create the file metadata
var metadata = {
contentType: 'image/jpeg'
};
var uploadTask = firebase.storage().ref().child('images/' + Uuid.generate()).put(file, metadata);
var outerThis = this;
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
function (snapshot) {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
default:
console.log('test1');
break;
}
}, function (error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
default:
console.log('test2');
break;
}
}, function () {
uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
console.log('File available at', downloadURL);
var currentAssignment = firebase.database().ref('Works').child(outerThis.props.questionId);
let pushRef = currentAssignment.child('answers').push();
try {
pushRef.set({
downloadURL: downloadURL,
date: Time.generate(),
seen: false,
firebaseKey: pushRef.getKey(),
workKey: outerThis.props.questionId
}).catch(e => console.log('push->set', e));
outerThis.state.setState({
pictures: outerThis.state.pictures.concat(downloadURL),
})
} catch (e) {
console.log('tutej', e)
}
});
});
}
render() {
return (
this.state.questions.map(question => {
return (
<section key={question.id} className='display-question'>
<div className='wrapper show-grid'>
<h3>Kategoria: {question.category}</h3>
<p>Poziom: {question.level}</p>
<p>Punkty: {question.pointAmount + question.pointBoost}</p>
<Col xs={12} md={6}>
<img alt='' style={{width: '100%'}}
src={question.photoURL}/>{/*Need 100% for the ratio*/}
<p>{question.workText}</p>
</Col>
<Col xs={12} md={6}>
<form encType="multipart/form-data" onSubmit={this.handleTextSubmit}>
<textarea name="textAnswer" id="textAnswer" style={{
width: '100%',
height: '50vh',
background: 'white',
color: 'black',
}}/>
<Button type='submit' style={{display: 'block'}}>Wyslij odpowiedz tekstowa</Button>
<Dropzone
multiple={false}
accept="image/*"
onDrop={this.onImageDrop.bind(this)}>
<p>Wyslij zdjecie w odpowiedzi</p>
</Dropzone>
<CancelAnswerButton questionId={question.id}/>
<FinishAnswerButton questionId={question.id}/>
</form>
</Col>
</div>
</section>
)
})
)
}
}
And this part:
this.setState({
questions: newState
});
Is throwing an error saying: InvalidCharacterError: String contains an invalid character, which I do not understand, since the syntax seems to be in order to me.
I all started going south after I took out these two elements:
CancelAnswerButton:
export default class CancelAnswerButton extends React.Component {
constructor(props) {
super(props);
}
async handleCanceling(e) {
try {
e.preventDefault();
var currentAssignment = firebase.database().ref('Works').child(this.props.questionId);
var currentUser = firebase.auth().currentUser;
await currentAssignment.child('available').set(true).catch(e => console.log(e));
await currentAssignment.child('state').set('Waiting').catch(e => console.log(e));
await currentAssignment.child('solverID').remove().catch(e => console.log(e));
await firebase.database().ref('Users').child(currentUser.uid).child('assignedWork').remove().catch(e => console.log(e));
return <AssignmentsComponent/>
// TODO Delete reputation points
}
catch (e) {
console.log('handle', e)
}
}
render() {
try {
return (
<Button onClick={this.handleCanceling} style={{display: 'block'}}>Anuluj
rozwiazywanie
zadan (Odejmujemy
za to pkt z rangi koleszko)</Button>
)
}
catch (e) {
console.log('render', e)
}
}
}
FinishAnswerButton:
export default class FinishAnswerButton extends React.Component {
constructor(props) {
super(props);
}
async handleFinishAssignment() {
var currentUser = firebase.auth().currentUser;
await firebase.database().ref('Users').child(currentUser.uid).child('assignedWork').remove().catch(e => console.log(e));
var currentAssignment = firebase.database().ref('Works').child(this.props.questionId);
await currentAssignment.child('state').set('Completed').catch(e => console.log(e));
await currentAssignment.child('finishTime').set(Time.generate()).catch(e => console.log('finishTime', e));
return <AssignmentsComponent/>
}
render() {
return (
<Button onClick={this.handleFinishAssignment}>Zakoncz rozwiazywanie zadania (Upewnij
sie ze uczen ma wszystko czego potrzebuje!)</Button>
)
}
}
But they both look ok. So what am I missing?
I was trying to make the code more modular, and am still learning React, so there are probably a lot of issues.
Example of the question object:
question = {
category: "Fizyka",
id: "-LF2OGgGXD-xPpSa64CX",
level: "Liceum",
photoURL: "https://firebasestorage.googleapis.com/v0/b/uczsieapp.appspot.com/o/images%2Faf941460-05e8-4943-8ea0-b24359e22cdf?alt=media&token=7141bf45-55c4-467c-a533-a268d95fe6cf",
pointAmount: 32,
pointBoost: 0,
}
A: Killing and restarting the yarn start process fixed the issue. No idea why. If someone knows or has an idea please feel free to leave an answer/comment
| |
doc_23533104
|
Thanks in advance
UPDATE
Thanks everyone! I wish I could check off all of your responses as good answers.
After a bit of testing, I have come up with the following function that handles pretty much every use case.
function getAccount() {
try {
if (_gaq) {
for (i = 0; i < _gaq.length; i++) {
if (_gaq[i][0] == "_setAccount") {
return _gaq[i][1]
}
}
}
if (_gat) {
if (_gat.fb) {
return _gat.fb
}
}
if (ga) {
return ga.getAll()[0].a.data.values[':trackingId']
}
} catch (e) { }
return ""
}
A: Joshua, this isn't a standard feature / get function that would be available.
You can however manually access ga object created by the tracking library.
If you for example open console for this webpage and type in:
ga.getAll()[0].a.data.values[':trackingId']
You will receive UA-5620270-1 which is probably the main Analytics Account for Stack Overflow. Similar approach should work in your case as well - and also any other attribute that's accessible:
Screen: http://fii.cz/sbdqevk
A: If you are prepared to accept a less than elegant solution you could use
function getAccount(_gaq) {
for (i = 0; i < _gaq.length; i++) {
if (_gaq[i][0] == "_setAccount") {
return _gaq[i][1];
}
}
}
_gaq is an array of arrays, the function simply loops through until it finds a subarray where the first element is _setAccount and returns the second element, which is the account number (_gaq.push(['_setAccount', 'UA-XXXXX-X']);).
As you are talking of legacy implementations, there are even older versions of the code so you might need more checks. The oldest version I could find on an active page was:
<script type="text/javascript">
_uacct = "UA-XXXXXXXX-X";
urchinTracker();
</script>
It's quite easy to get the Account Id from there. There is also the synchronous version of the code (sorry, can't find an example right now).
And for the current version look at Petrs answer.
A: According to documentation first you get all the trackers set on page
// returns an array with all the trackers
const trackers = ga.getAll();
And then, for each tracker, you can obtain the tracking id for each one getting the property
// returns the 'trackingId' propperty
const trackingId = tracker.get('trackingId'));
If you want to shorten it up, you could do
const trackingIds = ga.getAll().map(tracker => tracker.get('trackingId'));
Warning:
Remember to run this always after the ga ready.
Don't — use ga object methods outside a readyCallback as the methods
may not be available yet.
var trackers = ga.getAll();
Do — use ga object methods inside a
readyCallback as they're guaranteed to be available.
ga(function() {
var trackers = ga.getAll();
});
A: I just did it using an alternative method, as follows:
var _gaq = _gaq || [];
_gaq.push(function() {
var trackers, i;
trackers = _gat._getTrackers();
for (i = trackers.length - 1; i >= 0; i--) {
var account = trackers[i]._getAccount();
console.log("tracker account", account);
}
});
| |
doc_23533105
|
This is image which i want to change size of grid layout cells (horizontal + vertical) to bigger. How can i do this ?
Thanks in advance.
Here is my code:
let options_hour = {
series: {
lines: {
show: true,
lineWidth: 1.2
}
},
grid: {
backgroundColor: "#ffffff",
borderWidth: {
top: 1,
right: 1,
bottom: 1,
left: 1
},
highlightColor: "#FF0000"
},
xaxis: {
mode: "time",
timezone: "browser",
show: true,
ticks: 9,
tickColor: "#000000",
min: initialize_hour - 3600000 * 6,
max: initialize_hour - 600000,
ticks: [
initialize_hour - 3600000 * 6,
initialize_hour - 3600000 * 5,
initialize_hour - 3600000 * 4,
initialize_hour - 3600000 * 3,
initialize_hour - 3600000 * 2,
initialize_hour - 3600000 * 1,
initialize_hour - 600000
],
font: {
size: 9,
color: "#980000"
},
timeformat: "%H:%M"
},
yaxis: {
font: {
size: 9,
color: "#980000"
},
min: 0,
ticks: [
[0, '0'],
[2.25, 'NNW'],
[4.5, 'NW'],
[6.75, 'WNW'],
[9, 'W'],
[11.25, 'WSW'],
[13.5, 'SW'],
[15.75, 'SSW'],
[18, 'S'],
[20.25, 'SSE'],
[22.5, 'SE'],
[24.75, 'ESE'],
[27, 'E'],
[29.25, 'ENE'],
[31.5, 'NE'],
[33.75, 'NNE'],
[36, 'N']
],
tickColor: "#000000"
}
};
| |
doc_23533106
|
I have this code in my react register page to make the POST request:
export default function RegisterPage(props) {
const { register, handleSubmit, watch } = useForm();
const refForm = useRef(null);
const [profImage, setProfImage] = useState(null)
const onSubmit = (data) => {
console.log(data);
const formData = new FormData(refForm.current);
API.post('usuarios', formData, {
headers:{
'Content-Type': 'multipart/form-data'
}
}).then(res => {
localStorage.setItem('token', res.data.token);
localStorage.setItem('userID', res.data.usuario._id);
})
};
my API.js file:
export const API = axios.create({
baseURL: process.env.REACT_APP_BACK_URL,
timeout: 6000,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Authorization': 'Bearer ' + localStorage.getItem('token')
},
});
the route in /usuarios:
console.log(req.body);
console.log(req.file);
const nombreCompleto = req.body.nombreCompleto
const foto = IMAGES_URL_BASE + "/" + req.file.filename
const email = req.body.email
const password = req.body.password
const contact = req.body.contact
bcrypt.hash(password, saltRounds, function (err, hash) {
const usuario = new Usuarios()
usuario.nombreCompleto = nombreCompleto;
usuario.foto = foto;
usuario.email = email;
usuario.password = hash;
usuario.contact = contact;
usuario.save()
.then((newUsuario) => {
const accessToken = jwt.sign(
{ userID: newUsuario._id, nombreCompleto: newUsuario.nombreCompleto },
process.env.JWT_SECRET);
return res.json({ logged: true, token: accessToken, usuario: newUsuario })
})
.catch((error) => {
res.status(500).send(error);
})
});
});
I appreaciate any help! thanks in advance
| |
doc_23533107
| ||
doc_23533108
|
Now I've read lots of posts saying PHP traits are evil, because they break OO design, you can't test them as easily as you would a class, etc.
I'm wondering if using traits to split a very big class into more readable parts would be a good idea.
The class is already big, and will likely end up thousands of lines long without re-factorization.
Even though methods can be grouped by concern, they constantly need to call one another, which makes me wonder whether it is optimal to split the class into different classes.
To illustrate, here is a simplified example I've come up with.
The big class:
/**
* Class to refactorize
*/
class Tourist
{
public function gotoRestaurant()
{
}
public function gotoInternetCafe()
{
}
public function checkEmails()
{
}
public function meetGirlfriend()
{
if (Girlfriend::location() === 'restaurant')
{
$this->gotoRestaurant();
}
else
{
$this->checkEmails();
}
}
public function checkEmailsAndMeetGirlfriend()
{
$this->checkEmails();
$this->meetGirlfriend();
}
}
Here is how I'd do it if re-factorizing with classes:
/**
* Solution 1: using classes
*/
class ChoreDoer
{
public function __construct(Tourist $t)
{
$this->tourist = $t;
}
public function checkEmails()
{
$mover = new Mover($this->tourist);
$mover->gotoInternetCafe();
}
public function meetGirlfriend()
{
if (Girlfriend::location() === 'restaurant')
{
$mover = new Mover($this->tourist);
$mover->gotoRestaurant();
}
else
{
$this->checkEmails();
}
}
}
class Mover
{
public function __construct(Tourist $t)
{
$this->tourist = $t;
}
public function gotoRestaurant()
{
}
public function gotoInternetCafe()
{
}
}
class Tourist
{
public function checkEmailsAndMeetGirlfriend()
{
$cd = new ChoreDoer($this)
$cd->checkEmails();
$cd->meetGirlfriend();
}
}
I've got a feeling constantly calling new Mover(), new ChoreDoer(), and the new classes that will appear is going to become painful to read and write.
So what about using traits here to group functionality?
/**
* Solution 2: using traits
*/
trait TouristMovements
{
public function gotoRestaurant()
{
}
public function gotoInternetCafe()
{
}
}
trait TouristChores
{
public function meetGirlfriend()
{
if (Girlfriend::location() === 'restaurant')
{
$this->gotoRestaurant();
}
else
{
$this->checkEmails();
}
}
public function checkEmails()
{
$this->gotoInternetCafe();
}
}
class Tourist
{
use TouristMovements, TouristChores;
public function checkEmailsAndMeetGirlfriend()
{
$this->checkEmails();
$this->meetGirlfriend();
}
}
Here each trait can focus on its purpose, the code is easy to read and methods can inter-operate freely.
But since I never intend to use the TouristsMovements trait in any class other than Tourist, I have a feeling my use of them is not really what traits were designed for.
Would you go with solution 1? solution 2? something else?
A: As an alternative, you could do something like this, using your 'Solution 1':
class ChoreDoer
{
private $mover;
public function __construct(Tourist $t)
{
$this->tourist = $t;
}
public function checkEmails()
{
$this->getMover()->gotoInternetCafe();
}
public function meetGirlfriend()
{
if (Girlfriend::location() === 'restaurant')
{
$this->getMover()->gotoRestaurant();
}else
{
$this->checkEmails();
}
}
/**
* lazy-load mover object
*/
private function getMover()
{
if($this->mover == null)
{
$this->mover = new Mover($this->tourist);
}
return $this->mover;
}
}
If you don't fancy using the getter, you could instead name your property something like
private $_mover;
And use a magic __get to call your getter for you:
function __get($property)
{
$method = 'get'.ucfirst($property);
if(method_exists($method))
{
return $this->$method();
}
}
Although this will not perform quite as well, it makes it easy to just call
$this->mover->gotoInternetCafe();
And is nice and clean.
A: I'm curious as to what the OP ended up doing.
Currently in the same situation. I have a huge class with lots of methods doing different things.
At first I thought of splitting them into their own standalone classes but that required a lot of replacing $this->xxx() calls with $actualobj->xxx(). Good side of this method is I don't need to load/include all classes at once as I can simply autoload what's needed.
Second solution was to use traits in which case the whole thing will still be loaded into memory but at least the code is more organized, readable and easier to debug being separated into their own files/classes.
I decided to do it in 2 phases where I do traits first so as just to separate and cleanup the code then change each trait to standalone classes and replace necessary $this->xxx() calls with $actualobj->xxx() calls down the road.
| |
doc_23533109
|
I can see how the macros get, post etc. are created in https://github.com/phoenixframework/phoenix/blob/master/lib/phoenix/router.ex#L320-L334. However, probably because of the nested macro architecture that is being used, I was not able to implement a custom HTTP verb, say bla using a router definition like that:
Phoenix.Router.Scope.route Ical.Router, :match, :bla, "/bla", PageController, :bla, []
While not causing an compiler error, a 404 is produced when performing an BLA /bla HTTP/1.1 request.
It does not even work when trying to simulate the GET behaviour with
Phoenix.Router.Scope.route Ical.Router, :match, :get, "/bla", PageController, :bla, []
Any hints on this would be very much appreciated!
A: Alright, I found a way to implement this using the application's config files.
The simple implementation and the future of this case can be seen in this pull request: https://github.com/phoenixframework/phoenix/pull/1234.
| |
doc_23533110
|
const express = require('express');
const puppeteer = require('puppeteer');
const app = express();
(async () => {
const width = 1600, height = 1040;
const option = { headless: true, slowMo: true, args: [`--window-size=${width},${height}`] };
const browser = await puppeteer.launch(option);
const page = await browser.newPage();
const vp = {width: width, height: height};
await page.setViewport(vp);
const navigationPromise = page.waitForNavigation();
// 네이버 스토어팜
await page.goto('https://shopping.naver.com/home/p/index.nhn');
await navigationPromise;
await page.waitFor(2000);
const textBoxId = 'co_srh_input';
await page.type('.' + textBoxId, '양말', {delay: 100});
await page.keyboard.press('Enter');
await page.waitFor(5000);
await page.waitForSelector('ul.goods_list');
await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});
const result = await page.evaluate(() => {
const data = [];
$('ul.goods_list > li._itemSection').each(function () {
const title = $.trim($(this).find('div.info > a.tit').text());
const price = $(this).find('div.info > .price .num').text();
const image = $(this).find('div.img_area img').attr('src');
data.push({ title, price, image })
});
return data;
});
console.log(result);
await browser.close();
})();
app.listen(3000, () => console.log("Express!!!"));
I have a question. If I want to get information from number of pages, What should I do?
for example ( 1 page, 2 page , 3page .... )
A: use attribute footerTemplate with displayHeaderFooter for show pages originally using puppeteer API
await page.pdf({
path: 'hacks.pdf',
format: 'A4',
displayHeaderFooter: true,
footerTemplate: '<div><div class='pageNumber'></div> <div>/</div><div class='totalPages'></div></div>'
});
https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#pagepdfoptions
// footerTemplate HTML template for the print footer.
// Should be valid HTML markup with following CSS classes used to inject printing values into them:
// - date formatted print date
// - title document title
// - url document location
// - pageNumber current page number
// - totalPages total pages in the document
A: This is a difficult one due to the nature of how many pages are displayed, by default, on that site. But bear with me: I'll show you what you can achieve at the very least with this one.
Firstly, the site you provided lists 10 pages at a time underneath the list of items which you can cycle through. I'm sorry to say that I don't understand the language it is in so I don't know if there is an option somewhere to display more pages. So when you enter your search text, it displays as follows:
However when you click on the last number (the number 10), the list of pages updates to as follows:
This makes finding the number of overall pages much more difficult since there's no option to "jump" to the very last page (and subsequently there's also no option to jump back to the very first one either). I'll show you another example later of a site which does this.
What I'd recommend you do in your case is to use some simple maths to determine exactly how many pages are going to be listed. It's going to get far too complicated to keep telling puppeteer, for example, to "keep clicking the last available page number until you reach the end" or such-like. But we can determine how many pages are there just by executing a few simple steps.
Firstly, you need to get the total number of items returned in the search list via this element:
You can do that by executing this code, below:
const totalItems = await page.$eval('._productSet_total', (items) => {
// Remove the characters before the total number, leaving only the number in isolation
const child = items.querySelector('em');
items.removeChild(child);
// Now remove all commas from the total number
let finalItems = items.textContent.trim();
while(finalItems.indexOf(',') > -1) {
finalItems = finalItems.replace(',', '').trim();
}
return finalItems;
});
console.log(totalItems); // Outputs 4337903 (or something similar)
So now you've that total number. The next step is to determine how many items are going to be displayed on each page. You can do that by counting the number of items displayed on the current page - as follows:
const itemsPerPage = await page.$$eval('.goods_list li', (items) => {
return items.length;
});
console.log(itemsPerPage); // Outputs 180 on my machine
So now you've the total number of items found and the number of items to be displayed on each page. The next part is your simple maths to determine how many pages it will take to list all of those items:
const pages = totalItems / itemsPerPage;
console.log(Math.ceil(pages));
And that's it! This was a rather difficult example due to the poor design of the site itself (really it should have a route straight to the first and / or last pages at all times).
For example, if you click on the puppeteer tag in Stack Overflow (this very wonderful site), it will bring you to: https://stackoverflow.com/questions/tagged/puppeteer
Now scroll to the bottom of the page, you'll see something like this:
This is ideal for determining how many pages are listed in one single, simple step, as follows:
const lastPage = await page.$$eval('div[class*="pager"] > a > span[class*="page-numbers"]', (spans) => {
return spans[spans.length - 2].textContent;
});
console.log(lastPage); // Outputs 78
Hopefully something in here helps you with your puppeteer learning journey!
A: if (!this.browser) {
this.browser = await puppeteer.launch(this.OPT)
const pages: puppeteer.Page[] = await this.browser.pages()
// close chromium by catching 'targetdestryed'
this.browser.on('targetdestroyed', async () => {
if (this.browser) {
const pages: puppeteer.Page[] = await this.browser.pages()
if (pages.length === 0) {
process.exit(0)
}
}
})
}
Above is the code I wrote in Typescript.
You can get Array of Page(=Tab) from browser.pages()
And Puppeteer absolutely has 1 tab first time.
| |
doc_23533111
|
My Question is :
Can I ONLY use here document in interactive command like cat, ex and so on , but can not use it in non-interactive command like ping and some other command?
A: ping doesn't get its parameters from standard input, it only gets them from the command line arguments. If you want to turn input into arguments, you can use the xargs command:
xargs ping <<EOF
www.baidu.com
EOF
| |
doc_23533112
|
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int checkf(FILE *file, char*id){
char row[255];
int line_num = 1;
int find_result = 0;
char temp[255];
while (fgets(temp, 255, file) != NULL){ // here i get an Empty 'temp'
// so the contition is always false
if((strstr(temp, id)) != NULL) {
rewind(file);
for (int i=1; i<(line_num-1); i++) {
fgets(row, 255, file);
}
for (int i=0; i<4; i++) {
fgets(row, 255, file);
choppy(row);
printf("%s",row);
if (i!=3) {
printf(" ");
}
}
find_result++;
}
line_num++;
}
return find_result;
}
void add(FILE *file, char fileName[20]){
int check;
char name[100], id[100] ;
scanf("%s",name);
scanf("%s",id);
check = checkf(file,id);
if(check==0){
fputs("\n",file);
fputs(name,file);
}
}
int main(int argc, char * argv[]) {
// insert code here...
FILE *file;
FILE *file_app;
file_app= fopen(argv[argc-1], "a");
file= fopen(argv[argc-1],"r");
//check the there is a file
if (file== NULL)
{
printf("Can't open file");
return 1;
}
else
{
int cmd= strcmp(argv[1],"add");
if (cmd==0) add(file_app,argv[2]);
fclose(file);
printf("\n");
return 0;
}
}
So in conclusion, I think that when I the function checkf() is called from function add(), the file pointer gets lost. But, when I use checks() directly it works. Any ideas?
| |
doc_23533113
|
I build the combined jar using:
gradlew --no-daemon assemble
Then, I test my cli application using:
java -jar build/libs/stackoverflow-cli-0.1-all.jar search -q "merge maps" -t java
The output is what I expected, so that's good. However, I then want to create the native binary using graalvm. So I run this command:
native-image --no-server -cp build/libs/stackoverflow-cli-0.1-all.jar
It immediately fails with the following error:
Warning: Ignoring server-mode native-image argument --no-server.
Error: Please specify class containing the main entry point method. (see --help)
I thought this was weird. The next thing I tried was to specify the main class as the error suggested:
native-image --no-server -cp build/libs/stackoverflow-cli-0.1-all.jar com.eddie.StackoverflowCliCommand
That gives me a different error:
Warning: Ignoring server-mode native-image argument --no-server.
[com.ivansinsurance.stackoverflowclicommand:1544] classlist: 3,060.25 ms, 0.96 GB
[com.ivansinsurance.stackoverflowclicommand:1544] setup: 809.46 ms, 0.96 GB
Error: Default native-compiler executable 'cl.exe' not found via environment variable PATH
Error: Use -H:+ReportExceptionStackTraces to print stacktrace of underlying exception
Error: Image build request failed with exit status 1
I don't know what this error means. Here is the version of java I'm using:
openjdk version "11.0.7" 2020-04-14
OpenJDK Runtime Environment GraalVM CE 20.1.0 (build 11.0.7+10-jvmci-20.1-b02)
OpenJDK 64-Bit Server VM GraalVM CE 20.1.0 (build 11.0.7+10-jvmci-20.1-b02, mixed mode, sharing)
Any help is greatly appreciated!
A: *
*I installed Visual Studio 2019.
*Then I launched x64 Native Tools Command Prompt for VS 2019
*Then I ran:
'native-image --no-server -cp build/libs/stackoverflow-cli-0.1-all.jar com.eddie.StackoverflowCliCommand'
and that worked!
| |
doc_23533114
|
A: As node node-thrift-hive and node-hive both module are abandoned, not commit still 4 to 5 year old, I have same issue and I am using Node 0.12 and below is my solutions.
Step -1: You have to setup Hiveserver2 , my hive version is 1.2 and hadoop version 2.7
https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2
If you don't want to follow Step-1 then upgrade your node js to 4.5 > and use jshs2 npm
In my case I don't want to upgrade my node version so I try to connect via JDBC drivers JDBC npm
Step-2: Use Below code to connect hive and fetch the data
var JDBC = require('jdbc');
var jinst = require('jdbc/lib/jinst');
// isJvmCreated will be true after the first java call. When this happens, the
// options and classpath cannot be adjusted.
if (!jinst.isJvmCreated()) {
// Add all java options required by your project here. You get one chance to
// setup the options before the first java call.
jinst.addOption("-Xrs");
// Add all jar files required by your project here. You get one chance to
// setup the classpath before the first java call.
jinst.setupClasspath(['./drivers/hsqldb.jar',
'./drivers/derby.jar',
'./drivers/derbyclient.jar',
'./drivers/derbytools.jar',
'./lib/drivers/hive-jdbc-1.2.1.jar',
'./lib/drivers/hive-exec-1.2.1.jar',
'./lib/drivers/hive-common-1.2.1.jar',
'./lib/drivers/hive-metastore-1.2.1.jar',
'./lib/drivers/hive-service-1.2.1.jar',
'./lib/drivers/httpclient-4.3.jar',
'./lib/drivers/httpcore-4.3.jar',
'./lib/drivers/libthrift-0.9.1.jar',
'./lib/drivers/libfb303-0.9.0.jar',
'./lib/drivers/hadoop-common-2.7.1.jar',
'./lib/drivers/slf4j-api-1.7.21.jar',
'./lib/drivers/org-apache-commons-logging.jar'
]);
}
var config = {
url: 'jdbc:hive2://127.0.0.1:10000',
user : 'demo',
password: '',
minpoolsize: 2,
maxpoolsize: 3
};
var testpool = null;
var testconn = null;
var hsqldb = new JDBC(config);
hsqldb.initialize(function(err) {
if (err) {
console.log(err);
}
});
hsqldb.reserve(function(err, connObj) {
console.log("Using connection: " + connObj.uuid);
var conn = connObj.conn;
conn.createStatement(function(err, statement) {
statement.executeQuery("select * from test1 limit 1",function(err,resultSet){
//console.log(resultSet);
resultSet.toObjArray(function(err, results) {
console.log(results);
});
});
});
});
A: If there is no possibility to use Java and you have to connect to Hive server with SASL authentication, you can use npm lib hive-driver
Here is an example of usage:
const hive = require('hive-driver');
const { TCLIService, TCLIService_types } = hive.thrift;
const client = new hive.HiveClient(
TCLIService,
TCLIService_types
);
const utils = new hive.HiveUtils(
TCLIService_types
);
client.connect(
{
host: 'localhost',
port: 10000
},
new hive.connections.TcpConnection(),
new hive.auth.PlainTcpAuthentication({
username: 'user name',
password: 'password'
})
).then(async client => {
const session = await client.openSession({
client_protocol: TCLIService_types.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V10
});
const operation = await session.executeStatement(
'CREATE TABLE pokes ( foo INT, bar INT )'
);
await utils.waitUntilReady(operation, false, () => {});
await operation.close();
await session.close();
});
| |
doc_23533115
|
public class Foo {
public int id;
public String data;
}
And that I have Foo "class" in JavaScript:
function Foo(id, data) {
this.id = id;
this.data = data;
}
Also, assume that I have Java controller that returns instance of Foo.class as a response to a REST request. In my JavaScript (AngularJS) code the request is sent as:
$http.get(url + 'bar/get-foo/')
.success(function (response) {
var foo = new Foo(response.id, response.data);
logger.info("SUCCESS: /get-foo");
})
.error(function (error_message) {
logger.error(error_message)
});
And it works. But is there a way to avoid passing every property from response to Foo constructor (some sort of expecting the Foo object, or casting it into a Foo object)?
I tried using Object.create(Foo, response) but I get TypeError: Property description must be an object: true
Of course there's always a possibility of refactoring the JavaScript side Foo constructor into:
function Foo(foo) {
this.id = foo.id;
this.data = foo.data;
}
But, that would require refactor of large portion of the codebase.
Thanks for your time. I appreciate it!
PS: For those who wonder why do I need this: It's not a problem with small classes like Foo, but some responses are instances of a much larger classes (with over a dozen of fields), which are not under my control.
EDIT: I accepted Chichozell's answer simply because it requires the least amount of work. Robin's and jonnyknowsbest's answers also work, (and will work for pure JavaScript, unlike Chichozell's answer, which is AngularJS specific). Haven't tried Laurentiu L.'s answer, but looks like it should also work.
Anyway this is A solution (not THE solution):
.success(function (response) {
var foo = new Foo();
angular.extend(foo, response); // angular.merge() for "deep-copy"
//...
}
Big thanks to everyone who answered/commented/edited in this thread.
A: You can do something like this to "deserialise" the JSON you receive back as the response to an initialised object:
function JSONToObj(jsondata) {
var json = JSON.parse(jsondata);
var name = null;
for(var i in json) { //Use first property as name
name = i;
break;
}
if (name == null)
return null;
var obj = new window[name]();
for(var i in json[name])
obj[i] = json[name][i];
return obj;
}
This assumes that the constructor exists in the global scope and that the response is JSON-formatted as such:
{
"Foo": {
"id": "the id",
"data": "the data"
}
}
A: You could also do something like this jsFiddle to achieve the structure you describe. The createObject function couold look something like the following code snippet.
function createObject(response, toCreate){
var newObject = new toCreate();
for(var attr in response){
if(newObject.hasOwnProperty(attr)){
newObject[attr] = response[attr];
}
}
return newObject;
}
Where you have createObject which takes a js object with the same attributes as your function as the response parameter, and a function (the object you want to create) as the toCreate parameter.
See the jsFiddle console log output, and you see that it works.
You could also, as seen in the jsFiddle, remove the check for hasOwnProperty to set the all attributes from the response regardless if the javascript function has them defined.
A: If you want to keep your Java thinking on javascript, try using angular.extend(), which will "copy" the properties of an object to another
this = angular.extend(this, response)
In the foo function, or directly on the controler:
Foo = angular.extend(Foo, response)
A: You can make it pretty generic if you want to. And there wouldn't be too much refactoring to do, and this solution would ease your future changes to both classes.
You may change your Foo javascript object to an Angular JS service and inject it wherever you need it. This way you can have your data available globally. It's better than that local variable foo.
yourApp.factory('Foo',
function () {
//set a default or just initialize it
var fooObject= {};
return {
getId: function () { return fooObject.id; },
getData: function() { return fooObject.data;},
setId: function(newId){fooObject.id = newId},
setData: function(newData){fooObject.data=newData;},
initializeFromObject : function(response){
for (var prop in response){
fooObject[prop] = response[prop];
}
}
};
}
);
You can also make the creation of new services safer with methods like hasAllProperties (by iterating through the object's properties, whether it is an array or object). ; hasNullValues and so on.
Hope this helps and you see it's value.
| |
doc_23533116
|
If I pass a single URL to NSSharingServicePicker, it works as expected and shows a list of services to share the item to. This is the code that works:
@IBAction func shareButtonClicked(_ sender: Any) {
var selectedItems = [fileURL1, fileURL2, fileURL3]
let item = selectedItems[0]
let picker = NSSharingServicePicker(items: [item])
picker.show(relativeTo: .zero, of: sender as! NSView, preferredEdge: .maxX)
}
However, I want to pass on the entire array like the following but this fails. For example, I want to pass 3 images to share to an email:
@IBAction func shareButtonClicked(_ sender: Any) {
var selectedItems = [fileURL1, fileURL2, fileURL3]
let picker = NSSharingServicePicker(items: [selectedItems])
picker.show(relativeTo: .zero, of: sender as! NSView, preferredEdge: .maxX)
}
The error I get trying the above is:
2021-05-27 11:48:23.397566-0600 testapp[9664:13409352] [Framework] Object does not conform to NSPasteboardWriting protocol: (
"file:///Volumes/drivea/My_Files/My_Photos/20191201_180741.jpg",
"file:///Volumes/drivea/My_Files/My_Photos/IMG_002.HEIC",
"file:///Volumes/drivea/My_Files/My_Photos/IMG_3097.JPG"
)
Am I missing something simple here? How can I pass several URLs to NSSharingServicePicker?
I am struggling with how to make the Object (I assume that refers to an array of URLs??) to conform to NSPasteboardWriting protocol.
| |
doc_23533117
|
I have investigated this issue but didn't get the specific answer please help me to solve this issue?
| |
doc_23533118
|
My App has fairly light backend API requirements, but does have some fairly active frontside calls. Doubt I'll brush up against the limit unless a store has a ton of simultaneous visitors, but it would be good for me to know either way.
A: According to the Shopify Support Forum, there is no limit on API calls via the Ajax API:
There are no limits for Ajax calls per shop per 10 minutes. Ajax requests like HTTP requests experience no bounds in Shopify: your shop can handle any traffic. More traffic means more HTTP requests and also — possibly, if you use Ajax — more Ajax requests. It's all good. Bring it on.
| |
doc_23533119
|
Here are a pictures of the behaviour
Fist expand event:
Second expand event:
Third expand event:
Here is the code that i'm using:
The model:
Ext.define('app.model.modeloCapa', {
extend: 'Ext.data.Model',
fields: ['nombre','url'],
proxy: {
type: 'ajax',
url: "data/jsonprovisional.json",
reader: {
type : 'json',
root : 'Result',
}
}});
The store:
Ext.define('app.store.capa', {
extend: 'Ext.data.TreeStore',
requires: 'app.model.modeloCapa',
model: 'app.model.modeloCapa'});
The view:
initComponent: function() {
var anchoPanatallaRes = window.screen.width;
var altoPantallaRes = window.screen.height;
var anchoTOC = 330;
var altoTOC = 473;
if (anchoPanatallaRes <= 1024) {
anchoTOC = 282;
altoTOC = 373;
}
var treeStore = Ext.getStore('capa');
function addUrl(value, p, record) {
return value ? Ext.String.format(
'<a href="'+value+'"target="_blank"'+'>Ver metadato'+'</a>'
):'';
}
var tree = Ext.create('Ext.tree.Panel', {
title: '',
reserveScrollbar: true,
loadMask: true,
useArrows: true,
rootVisible: false,
store: 'capa',
allowDeselect : true,
border : true,
animate: true,
listeners: {
checkchange: function(node, checked, eOpts) {
console.log('nodo seleccionado:', node, checked, eOpts);
},
select: function( record, index, eOpts ){
console.log('Elemento seleccionado:', record, index, eOpts);
},
beforedeselect: function( record, index, eOpts ){
console.log("Elemento deseleccionado :", record);
}
},
columns: [{
xtype: 'treecolumn',
text: 'Capa',
flex: 5,
sortable: true,
dataIndex: 'nombre'
},{
text: 'Metadato',
flex: 2,
dataIndex: 'url',
renderer: addUrl
}],
tbar: [{
labelWidth: 100,
xtype: 'triggerfield',
fieldLabel: 'Nombre capa:',
triggerCls: 'x-form-clear-trigger',
onTriggerClick: function() {
this.reset();
treeStore.clearFilter();
this.focus();
},
enableKeyEvents: true,
listeners: {
keyup: function() {
var field = tree.down('textfield'),
v;
try {
v = new RegExp(field.getValue(), 'i');
treeStore.filter({
filterFn: function(node) {
var children = node.childNodes,
len = children && children.length,
//Visibilidad de los hijos
visible = node.isLeaf() ? v.test(node.get('nombre')) : false, i;
//Visibilidad de los padres
for (i = 0; i < len && !(visible = children[i].get('visible')); i++);
return visible;
},
id: 'campoFiltroCapa'
});
} catch (e) {
field.markInvalid('Expresión no valida');
}
},
buffer: 250
}
}, {
xtype : 'button',
text: 'Click',
id : 'btnApagarCapas',
action: 'apagarCapas',
tooltip : 'Apagar todas las capas',
padding:0,
listeners : {
click : function(boton) {
console.log("BOTON PRESIONADO!!");
}
}
}]
});
Ext.apply(this, {
title: 'TABLA CONTENIDO',
id: 'ventanaCapas',
constrain: true,
header : {
titlePosition : 2,
titleAlign : 'center'
},
closable : false,
width : anchoTOC,
height : altoTOC,
x : 20,
y : 270,
layout : 'fit',
animCollapse : true,
collapsible : true,
collapseDirection : Ext.Component.DIRECTION_LEFT,
listeners : {
collapse : function(p) {
}
},
items: [tree],
});
this.callParent(arguments);
}
And teh JSON file that i'm using:
{"Result": [{
"nombre": "Componente Biótico y Abiótico",
"id": 1,
"Result":[{
"nombre": "Recursos hídricos",
"id": 2,
"Result": [{
"id": 268,
"titulo": "HIDROGEOLOGIA_ATLAS",
"url": "http://srsigaremap:8080/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.demo.MapPreviewPage",
"nombre": "HIDROGEOLOGIA_ATLAS",
"metadato": "",
"wfs": false,
"leaf": true,
"checked": false
}]
},{
"nombre": "Fauna",
"id": 3,
"Result": [{
"id": 269,
"titulo": "AVES_ATLAS_ATLAS",
"url": "http://srsigaremap:8080/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.demo.MapPreviewPage",
"nombre": "AVES_ATLAS_ATLAS",
"metadato": "",
"wfs": false,
"leaf": true,
"checked": false
}]
},{
"nombre": "Ecosistemas",
"id": 4,
"Result": [{
"id": 270,
"titulo": "ECOSISTEMAS_MARINOS_ATLAS",
"url": "http://srsigaremap:8080/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.demo.MapPreviewPage",
"nombre": "ECOSISTEMAS_MARINOS_ATLAS",
"metadato": "",
"wfs": false,
"leaf": true,
"checked": false
}]
}]},{
"nombre": "ARE",
"id": 5,
"Result":[{
"nombre": "Minero Energético",
"id": 2,
"Result": [{
"id": 271,
"titulo": "GASODUCTO_ATLAS",
"url": "http://srsigaremap:8080/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.demo.MapPreviewPage",
"nombre": "GASODUCTO_ATLAS",
"metadato": "",
"wfs": false,
"leaf": true,
"checked": false
},{
"id": 272,
"titulo": "TITULOS_MINEROS_ATLAS",
"url": "http://srsigaremap:8080/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.demo.MapPreviewPage",
"nombre": "TITULOS_MINEROS_ATLAS",
"metadato": "",
"wfs": false,
"leaf": true,
"checked": false
}]
}]},{
"nombre":"Agrología",
"id":13,
"Result":[{
"nombre": "Cobertura y uso",
"id": 2,
"Result": [{
"id": 271,
"titulo": "COBERTURA_VEGETAL_GUAJIRA_ATLAS",
"url": "http://srsigaremap:8080/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.demo.MapPreviewPage",
"nombre": "COBERTURA_VEGETAL_GUAJIRA_ATLAS",
"metadato": "",
"wfs": false,
"leaf": true,
"checked": false
}]
}]}]}
A: TreePanel works fine only if all your nodes have a unique 'id' property.
In your JSON file, we can see that "Recursos hídricos" node, "Minero Energético" and "Cobertura y uso" have the same id :
"nombre": "Recursos hídricos",
"id": 2
"nombre": "Minero Energético",
"id": 2
"nombre": "Cobertura y uso",
"id": 2
That's why "Recursos hídricos" disapear when you click on your "ARE" node. Make sure to set a unique ID to all your nodes (no matter the level they are) and your problem will be solved.
| |
doc_23533120
|
My POST method looks like this:
exports.create = async (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) {
return res
.status(400)
.json({ errors: [{ msg: 'Image could not be uploaded' }] });
}
const {
title,
description,
photo,
tags,
git,
demo,
projectType,
} = fields;
//get links object
const projectFields = {};
projectFields.creator = req.user._id;
if (title) projectFields.title = title;
if (title) projectFields.description = description;
if (photo) projectFields.photo = photo;
if (projectType) projectFields.projectType = projectType;
if (tags) {
projectFields.tags = tags.split(',').map((tag) => tag.trim());
}
//get links object
projectFields.links = {};
if (git) projectFields.links.git = git;
if (demo) projectFields.links.demo = demo;
//1kb = 1000
//1mb = 1000000kb
//name 'photo' mus match client side. use photo
if (files.photo) {
if (files.photo.size > 1000000) {
return res.status(400).json({
errors: [{ msg: 'Image could not be uploaded. File to big.' }],
});
}
//this relates to data in schema product
project.photo.data = fs.readFileSync(files.photo.path);
project.photo.contentType = files.photo.type;
}
});
I want to use async/await so I am using try{}catch(err){} for my project.save(). I am initializing all my fields where I have also nested links. Unfortunately this is not working as I thought it will work. Right now my POST is returning 500. I am sitting on this and right now I am at the point that this can get a bit messy and not even close to any solution.
| |
doc_23533121
|
*
*Take the top n (or m < n if they have fewer than n viewed tags) tags
*Take the top n tags where n is a percentage of the total tags viewed
*Take the top n tags with m views where n and m are percentages of total tags viewed and total page views
*Take all of the tags, regardless of views
The goal is to identify what is most interesting to the user and show them other things that they might be interested in, with respect to the tags that are assigned to the content.
A: You could look at machine learning algorithms to find algorithms with which to evaluate the effectiveness of your choice.
Like for instance: http://en.wikipedia.org/wiki/Supervised_learning#Approaches_and_algorithms Stuff like nearest neighbour and bayes could help you improve your suggestions.
This is however overkill for just suggesting "Would you like to look at this too?", but it's an interesting approach to providing better tie-ins. It would, however require some method to figure out whether or not your users value your suggestions (e.g. "I like this!"-links or log-analysis based on time spent on links, etc.)
A: A simple solution is to try several reports and check which report is more informative. The nature of your site and your data may mean that some reports are unexpectedly useful and some are not. If a report get a 'flat' area chart for example - look for something else.
Even better give the consumers of the reports a choice and an ability to provide feedback. Tune the reports based on what they will be really looking for.
P.S. I would go fro the "Take the top n tags with m views where n and m are percentages of total tags viewed and total page views" report first
| |
doc_23533122
| ||
doc_23533123
|
A: Create a .htaccess in lib directory and write the following code in the file :
RewriteRule ^(.+)\.php$ $1
And in httpd write the following :
RewriteEngine on
RewriteRule "^([^\.]+)$" "$1.php" [PT]
| |
doc_23533124
|
Year WeekNumber Category Units in
2019 1 A 10
2019 1 B 20
2019 2 A 15
2019 2 B 10
2019 3 A 15
In week 3, there is no 'units in' for category B, but I would still like to show the running total for this category.
I've written the following code which works for category A but for week 3, it doesn't show category B running total.
sum(units in) over
(partition by category order by year, weeknumber)
Expected results
Year WeekNumber Category Running Total
2019 1 A 10
2019 1 B 20
2019 2 A 25
2019 2 B 30
2019 3 A 40
2019 3 B 30
Any suggestions?
Thanks
afk
A: I think you want a cross join to generate all results and then a left join to bring in data. Then use window functions:
select yw.year, yw.weeknumber, c.category, t.units_in,
sum(t.units_in) over (partition by c.category order by yw.year, yw.weeknumber) as running_units_in
from (select distinct category from t) c cross join
(select distinct year, weeknumber from t) yw left join
t
on t.category = c.category and t.year = yw.year and t.weeknumber = yw.weeknumber;
Note: You may have better sources of weeks and categories than using select distinct.
| |
doc_23533125
|
Please help me to implement AVCapturePhotoOutput in Objective-C.
Here is my sample code:
_avCaptureOutput = [[AVCapturePhotoOutput alloc]init];
_avSettings = [AVCapturePhotoSettings photoSettings];
AVCaptureSession* captureSession = [[AVCaptureSession alloc] init];
[captureSession startRunning];
AVCaptureConnection *connection = [self.movieOutput connectionWithMediaType:AVMediaTypeVideo];
if (connection.active)
{
//connection is active
NSLog(@"Connection is active");
id previewPixelType = _avSettings.availablePreviewPhotoPixelFormatTypes.firstObject;
NSDictionary *format = @{(NSString*)kCVPixelBufferPixelFormatTypeKey:previewPixelType,(NSString*)kCVPixelBufferWidthKey:@160,(NSString*)kCVPixelBufferHeightKey:@160};
_avSettings.previewPhotoFormat = format;
[_avCaptureOutput capturePhotoWithSettings:_avSettings delegate:self];
}
else
{
NSLog(@"Connection is not active");
//connection is not active
//try to change self.captureSession.sessionPreset,
//or change videoDevice.activeFormat
}
A: _avCaptureOutput = [[AVCapturePhotoOutput alloc]init];
_avSettings = [AVCapturePhotoSettings photoSettings];
AVCaptureSession* captureSession = [[AVCaptureSession alloc] init];
[captureSession startRunning];
[self.avCaptureOutput capturePhotoWithSettings:self.avSettings delegate:self];
self must implement the AVCapturePhotoCaptureDelegate
#pragma mark - AVCapturePhotoCaptureDelegate
-(void)captureOutput:(AVCapturePhotoOutput *)captureOutput didFinishProcessingPhotoSampleBuffer:(CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(AVCaptureBracketedStillImageSettings *)bracketSettings error:(NSError *)error
{
if (error) {
NSLog(@"error : %@", error.localizedDescription);
}
if (photoSampleBuffer) {
NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
UIImage *image = [UIImage imageWithData:data];
}
}
Now, you get the image, and do whatever you want.
Note: Since iOS 11, -captureOutput:didFinishProcessingPhotoSampleBuffer:... is deprecated, need to use -captureOutput:didFinishProcessingPhoto:error: instead:
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(nullable NSError *)error
{
NSData *imageData = [photo fileDataRepresentation];
UIImage *image = [UIImage imageWithData:data];
...
}
| |
doc_23533126
|
# my decorator factory
def execute_in(directory): # <-- I want this to be a variable's value which can change
def decorator(function):
def wrapper(*args, **kwargs):
os.chdir(directory)
print(directory) # currently is printing None which is my problem
value = function(*args, **kwargs)
os.chdir(home_dir)
return value
return wrapper
return decorator
and
# a function that runs after assigning General.archive_dir a value
@execute_in(General.archive_dir)
def get_data():
print(General.archive_dir) # will print the correct directory name
with open('data.csv', 'r') as f:
rows = [row for row in csv.reader(f, delimiter=',')]
return rows
My problem is that the decorator factory is using the value of the variable General.archive_dir instantiated at program start when its value is None. I want it to use the value of General.archive_dir at the time the decorated function is called. How can I do this?
I apologize if this question is unclear. If you can, please let me know how I can clarify it if needed.
A: One solution is calling @execute_in with a lambda.
directory inside wrapper would become a function that, when called, returns the current value.
archive_dir = None
# decorator factory
def execute_in(directory_path_getter):
def decorator(function):
def wrapper(*args, **kwargs):
print('from wrapper:', directory_path_getter()) # Notice the function call
value = function(*args, **kwargs)
return value
return wrapper
return decorator
@execute_in(lambda: archive_dir)
def get_data():
...
archive_dir = 'some directory'
print(get_data())
Prints:
from wrapper: some directory
from get_data: some directory
['some data']
A: If a decorator isn't strictly required, a context manager can also fulfill the task of temporarily changing directories.
import os
from contextlib import contextmanager
@contextmanager
def execute_in(directory):
orig_dir = os.getcwd()
os.chdir(directory)
try:
yield
finally:
os.chdir(orig_dir)
Using a context manager would allow for changing directories many times in one method, and can be nested.
settings = {
'archive_dir': './dir'
}
def get_data():
print(os.getcwd())
with execute_in(settings['archive_dir']):
print(' ' + os.getcwd())
with execute_in('bin'):
print(' ' + os.getcwd())
print(' ' + os.getcwd())
print(os.getcwd())
And when we run it
>>> get_data()
/home/they4kman/.PyCharm2019.2/config/scratches
/home/they4kman/.PyCharm2019.2/config/scratches/dir
/home/they4kman/.PyCharm2019.2/config/scratches/dir/bin
/home/they4kman/.PyCharm2019.2/config/scratches/dir
/home/they4kman/.PyCharm2019.2/config/scratches
| |
doc_23533127
|
{
"head": {
"heading": ["header1", "header2", "header3"]
},
"body": {
"elements": [{
"header1": {
"value": "value1"
},
"header2": {
"value": "value2"
}
"header3": {
"value": "value3"
}
},
{
"header1": {
"value": "value1"
},
"header2": {
"value": "value2"
}
"header3": {
"value": "value3"
}
}
]
}
I can't predict the number of values in headings. So, I initially parsed the values in headings and stored in an array. Later while printing the body elements. I wrote the following code
// data has the parsed json file
var heading = [];
data.head.heading.forEach(function(head) {
heading.push(head);
});
data.body.elements.forEach( function(elem) {
for (var head in the heading) {
var header = heading[head];
alert(elem.header.value); //not accessing value inside header
}
});
On using values.header.value it needs to access value inside header1, header2 and header3 of each elem but it is returning an error
TypeError: elem.header is undefined
It is taking the value as the header instead of value inside the variable header. Is there any way to make it access the values inside the variable header? thanks in advance
A: You need to access the object using bracket notation as the value of header needs to be used as the key, not the literal word 'header`, eg.
elem[header].value
Also, your first loop is entirely redundant, as you're just copying an array you already have access to. Try this:
data.body.elements.forEach(function(elem) {
for (var head in data.head.heading) {
var header = data.head.heading[head];
console.log(elem[header].value);
}
});
Finally, note that this can be made even more succinct by using another nested forEach() call to iterate data.head.heading:
var data = {
"head": {
"heading": ["header1", "header2", "header3"]
},
"body": {
"elements": [{
"header1": { "value": "value1" },
"header2": { "value": "value2" },
"header3": { "value": "value3" }
},
{
"header1": { "value": "value1" },
"header2": { "value": "value2" },
"header3": { "value": "value3" }
}]
}
}
data.body.elements.forEach(function(elem) {
data.head.heading.forEach(function(header) {
console.log(elem[header].value);
});
});
| |
doc_23533128
|
I already manage to do it with my own camera (host), but I didn't find a solution to do it with the clients webcam.
this is my main code right now:
from flask import Flask, render_template, Response
from camera import VideoCamera
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
def gen(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/video_feed')
def video_feed():
return Response(gen(VideoCamera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, threaded=True, use_reloader=False)
The VideoCamera class, capture my webcam (cv2.videocapture(0)) reading teh frames (with the ge_frame() func) process it and then return the image with encoding to jpeg to bytes.
The html part:
<html lang="en">
<head>
<title>Face Detector</title>
</head>
<body>
<h1>Face Recognition</h1>
<img
src="http://localhost:5000/video_feed"
alt="loading video stream..."
/>
</body>
</html>
How can I do it with the clients webcam?
| |
doc_23533129
|
<div class="cl1">
<div class="cl2">Text1</div>
<div class="cl1">Text2</div>
<div class="cl2">Text3</div>
<div class="cl1">Text4</div>
<div class="cl1">Text5</div>
</div>
For example, in this code, it should select child divs 2, 4 and 5. But I do not want write selector .cl1 .cl1{dislay: none;} since I have dozens of classes like this and I do not want to create identical selectors for each one.
| |
doc_23533130
|
* list in columns (display: grid vs. column-count: 3). Either I get wrong order or weird shape of child
* OK, so what I need is to render nested ul / li into 3 columns.
I want to do this with pure CSS (and no JS) and I have 2 semi-working examples.
Example 1 via display: grid https://jsfiddle.net/slick/1rtucfmL/2/
So for parent ul you simply specify display: grid with grid-template-columns: 1fr 1fr 1fr and you have 3 columns. When you hover on item, then child ul renders nicely.
This example however has issue where items are rendered horizontally (don't want that):
a b c
d e f
g h i
rather than vertically (this is what I need):
a d g
b e h
c f i
Someone asked this before and the solution is to define qty. of rows. I can't do this because I have dynamic quantity of rows and I don't want to hardcode any values.
So I went to the second example…
Example 2 via column-count: 3 https://jsfiddle.net/slick/g5p2j8bo/2/
This renders column items as I want, from A to Z vertically. However the issue is that when you hover on item, the child ul is shown in a very bizarre way (sometimes it's broken into columns as well, I don't want this).
If only I could fix this child positioning then example 2 would suit my needs.
I have no idea why this happens. I tried to set column-count: 1 because I thought that maybe it inherits 3 from parent but that didn't help.
Any hints? Thanks!
A: Something that can help is avoid breaks, so your css code should be like this
ul#root li>ul {
top: -12px;
left: 190px;
position: absolute;
break-inside: avoid; // added
page-break-inside: avoid; // added
will-change: transform; // added
visibility: hidden;
z-index: 1;
background: #ffffff;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.25);
list-style: none;
width: 190px;
padding: 10px 0;
font-size: 14px;
line-height: 16px;
letter-spacing: .02em;
}
Couldn't add snippet because body limit, but here is a fiddle.
A: Use MSclavi's solution, along with display: inline-block.
JSfiddle
ul#root li>ul {
top: -12px;
left: 190px;
position: absolute;
display: inline-block;
break-inside: avoid;
page-break-inside: avoid;
will-change: transform;
visibility: hidden;
z-index: 1;
background: #ffffff;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.25);
list-style: none;
width: 190px;
padding: 10px 0;
font-size: 14px;
line-height: 16px;
letter-spacing: .02em;
}
This is one of the most frustrating problems that I've encountered in CSS3, but!
Try using flex columns with a static height.
ul#root {
list-style-type: none;
display: flex;
flex-direction: column;
flex-wrap: wrap;
height: 16em; /* Static heights! Oh no! */
}
JSfiddle
| |
doc_23533131
|
This code is part of a much longer code including a for loop t=1:T, therefore the following code runs for every t.
I have F firms, which produce Yd. In every period t they buy a certain amount K of machine tools, whose productivity is given by A; therefore, the productive capacity of the machine tools bought in t equals AK=A.*K. Firms' total productive capacity equals sum(AK). Since sum(AK) might be greater than what they want to produce Yd, firms have to determine which fraction they will utilize (omega) of each machine "v" they own, considering that they start using the most productive machine tools first (those with the highest A). Thus, starting from the most productive machines, if the productive capacity from a certain machine is lower than Yd, omega of that machine will be set to 1, if the productive capacity has already reached Yd, omega of that machine will be set to 0, otherwise omega will be set to the fraction required. How can I code that?
This is what I did but it is definitely too slow:
T=100;
F=50;
A=rand(T,F); %initialized randomly (not as in my real code)
K=rand(T,F); %idem
AK=A.*K; %productivity of machine tools
Yd=rand(1,F); %initialized randomly
omega=zeros(T,F); %needs to be computed
OAK(:,:)=zeros(T,F); %needs to be computed
for f=1:F
[A_sorted_value,A_sorted_index]=sort(A(:,f)); %sort machines according to their productivity level
while sum(A_sorted_value)>0 && sum(OAK(1:t,f))<Yd(f) %apply rule as long as there are machines available and desired production has not been achieved
v=A_sorted_index(end); %pick the best machine of capital, i.e. highest productivity A
if AK(v,f)+sum(OAK(1:t,f))<=Yd(f) %assign omega=1 if existing capacity is below desired production
omega(v,f)=1;
OAK(v,f)=omega(v,f).*AK(v,f); %update existing capacity
elseif AK(v,f)+sum(OAK(1:t,f))>Yd(f) && Yd(f)>sum(OAK(1:t,f)) %assign omega so that machine v can fill desired production
omega(v,f)=(Yd(f)-sum(OAK(1:t,f)))/AK(v,f);
OAK(v,f)=omega(v,f).*AK(v,f);
end
A_sorted_index(end)=[]; %remove machine v from the list and pick the next one if condition "while" is satisfied
A_sorted_value(end)=[]; %otherwise go to the next firm
end
end
I hope it is clear and thanks in advance!
A: It appears that you are running some kind of simulation. This means (if results depend on previous iterations), your t and f loop can't be optimized away. So the only optimization target available would be the inner while loop. I'd recommend you consider whether or not you can pre-calculate or vectorize anything (check your math on paper).
But since I can't really help you with that, here are some things which might help.
One low hanging fruit I can offer immediately, is you can use the sort function to sort the entire matrix in some set direction, so you can move that outside the f loop.
% Sort the entire A array, column-wise.
[AVals, AIdxs] = sort(A,1);
for f = 1:F
A_sorted_value = AVal(:,f);
A_sorted_index = AIdx(:,f);
...
end
Next, I recommend that you use a for loop instead of your while loop.
Since you already know that you will be iterating through the entire sorted A list, or until another condition (sum(OAK(1:t,f))<Yd(f)) is met, this can be done with a for loop. Combined with the above recommendation, you might get something like this:
% Sort A in descending order instead, so first element in the array is now highest in value
[AVal, AIdx] = sort(A,1,'descend');
for f = 1:F
A_sorted_value = AVal(:,f); % Appears to be unused?
A_sorted_index = AIdx(:,f);
% Iterate through entire A_sorted_index array, eliminates rewriting of A_sorted_index
for i = 1:length(A_sorted_index)
v = A_sorted_index(i);
% Loop Exit Conditions
if (sum(OAK(1:t,f))<Yd(f)) || (sum(A_sorted_value(1:i)) <= 0)
break
end
% Your code below
%assign omega=1 if existing capacity is below desired production
if AK(v,f)+sum(OAK(1:t,f)) <= Yd(f)
omega(v,f)=1;
%update existing capacity
OAK(v,f)=omega(v,f).*AK(v,f);
%assign omega so that machine v can fill desired production
elseif AK(v,f)+sum(OAK(1:t,f))>Yd(f) && Yd(f)>sum(OAK(1:t,f))
omega(v,f) = (Yd(f)-sum(OAK(1:t,f)))/AK(v,f);
OAK(v,f) = omega(v,f).*AK(v,f);
end
end
end
Now, A_sorted_value appears to be unused. I can't assume that the value of elements in A are non-zero, positive numbers. So I had to include the check condition sum(A_sorted_value(1:i)) <= 0. But if you do have only non-zero, positive A elements, you can remove that snippet to speed the loop up even more.
I profiled this code against the old one, at T=200, F=100, ran in a loop 50 times.
new = 6.835 secs
old = 65.634 secs
Which is approximately a 90% time reduction.
A large amount of the time reduced came from removing these lines of codes, which were quite wasteful.
A_sorted_index(end)=[];
A_sorted_value(end)=[];
I'm sure there are still plenty more room for optimization, but this is good enough for me.
Do verify that the code I provided is correct.
A: Here is a version that appears to be faster, by storing some results used multiple times. You should be able to implement these changes in addition to momocha's suggestions.
For a big speed increase, you should either transpose all your matrices so that f accesses arrays by their columns rather than rows, or interchange the order of your F and T for loops. Accessing a single column of a matrix at a time is more efficient than working on a single row, so always loop over columns first, then the rows in that column.
% precompute sorted array
[A_sorted,A_sorted_I]=sort(A);
for f = 1:F
% get sorted vectors from percomputed array
A_sorted_value = A_sorted(:,f);
A_sorted_index = A_sorted_I(:,f);
% use nnz() instead of sum() (this may not make a difference)
while nnz(A_sorted_value)>0 && sum(OAK(1:t,f))<Yd(f)
% precompute a few things that are used several times
v = A_sorted_index(end);
ak_ = AK(v,f);
sOAK = sum(OAK(1:t,f));
if ak_+sOAK<=Yd(f)
omega(v,f)=1;
OAK(v,f)=ak_; % don't multiply by omega(v,f), we know it's one, this saves memory lookup
else % doesn't need to be an else if, condition will always be true
ex = Yd(f)-sOAK;
omega(v,f)=ex/ak_;
OAK(v,f)=ex;
end
% this is a faster way to de-allocate
A_sorted_index=A_sorted_index(1:end-1);
A_sorted_value=A_sorted_value(1:end-1);
end
end
| |
doc_23533132
|
["http://getbootstrap.com/javascript/#tabs", "http://paulgraham.com/re.html"]
Once I save it to the db message.link will be saved as:
"[\"http://getbootstrap.com/javascript/#tabs\", \"http://paulgraham.com/re.html\"]"
When I fetch the data from db later on how can I get the array from the message.link string like this?
["http://getbootstrap.com/javascript/#tabs", "http://paulgraham.com/re.html"]
To display the links from all message objects, how should I extract the links? Let's say message(1).link has one link, message(2) has three links, and I'd like to display all the four links as separated elements of @message_links or whatever instance variable.
UPDATE
Method works but can't display the :created_at and do the pagination properly since @message_links2 will be an array of links.
@message_links = @conversation.messages.with_link.order(created_at: :desc).paginate(page: params[:page], per_page: 12)
@message_links2 = @message_links.map(&:link).flatten
A: This is where you want a serialized column. Then you won't need to do the conversion yourself. see: Using Rails serialize to save hash to database
| |
doc_23533133
|
In some situations i have to run them in parallel. when i run 5 tasks in parallel using async.parallel, one core is captured for 10 seconds. According to those stats we can assume that if one core is busy at 100% usage for 10 seconds, a server with 12 cores is going to server 12 concurrent requests from users.
My question is should we be using node.js for this purpose? or is there a better way or a recommended way to handle this kind of a situation. thanks
A: This seems unrelated to node.js. You would have this problem regardless of programming language. Your problems are more related to your design. It seems to me you need some form of caching mechanism, so future requests don't need to take 10 seconds each. You could also do the computing ahead of time and store the results in a database.
| |
doc_23533134
|
Here is the example of what I'm trying to implement:
This is my first array:
var data =[salt.1200, salt.1100, salt.1000, salt.0900, salt.0800, salt.0700, current.1200, current.1100, current.1000, current.0900, current.0800, current.0700];
And from this array I would like to build two different arrays, one for salt and one from current.
I have tried to use a for loop with a jQuery grep function on it and split, but that didn't worked.
var plotsArray = [];
for (var i=0; i<data.length; i++){
plotsArray = jQuery.grep(data, function(a){
return (a.split(".") == 'salt')
});
}
console.log('plotsArray: '+plotsArray);
Also, I been trying to do is to read the first part of the string until the dot and then build an array base on that result. Using for example array filter, but I haven't figure it out how to read just until the dot.
I will appreciate any guidance on how to solve this.
Regards,
A: I would do something more along the lines off this.
var plotsArray = [];
for (var i=0; i<data.length; i++){
if(data[i].indexOf('salt') >= 0){
plotsArray.push(data[i]);
}
console.log('plotsArray: '+plotsArray);
A: Make change here -
return (a.split(".")[0] == 'salt')
and your code will work.
Working fiddle - http://jsfiddle.net/Lh8Pt/
A: I reckon your test should either be:
return a.split(".")[0] == "salt";
or
return a.indexOf("salt") == 0;
The latter might be better because it will not error out in the occasion that one of the array values doesn't contain a dot.
A: Using you code I would do:
var plotsArray = [];
plotsArray.push($.grep(data, function(n,i){
return n.split(".")[0] !== "salt";
}));
And please be sure that the data array contains strings.
A: var saltArray = [];
var currentArray = [];
for(var i=0;i<data.length;i++){
if(data[i].split('.')[0]=='salt'){
saltArray.push(data[i]);
}else{
currentArray.push(data[i]);
}
}
A: Using filter/map methods you could do something like:
var current = [],
salt = data.filter(
function(a){
var x = a.split('.');
if (/current/i.test(x[0])) { this.push(x[1]); }
// ^ = current
return /salt/i.test(x[0])
}, current
// ^ context
).map(
function(b){
return b.split('.')[1]}
);
MDN about Array.filter
A: Try this: http://jsfiddle.net/afEGC/
var data = ['salt.1200', 'salt.1100', 'salt.1000', 'salt.0900', 'salt.0800', 'salt.0700', 'current.1200', 'current.1100', 'current.1000', 'current.0900', 'current.0800', 'current.0700'];
var asplit = new Array();
asplit['salt'] = new Array();
asplit['current'] = new Array();
jQuery.each(data,
function(index,value)
{
var split_value = value.split('.');
asplit[split_value[0]].push(split_value[1]);
});
console.log('salt: ' + asplit['salt']);
console.log('current: ' + asplit['current']);
| |
doc_23533135
|
FILE* fp = NULL;
fp = fopen("audioFile.wav", "rb");
char type[4];
DWORD size, chunkSize;
short formatType, channels;
DWORD sampleRate, avgBytesPerSec;
short bytesPerSample, bitsPerSample;
DWORD dataSize;
fread(type, sizeof(char), 4, fp);
if (type[0] != 'R' || type[1] != 'I' || type[2] != 'F' || type[3] != 'F')
fatalError("OpenAL Error: No RIFF");
fread(&size, sizeof(DWORD), 1, fp);
fread(type, sizeof(char), 4, fp);
if (type[0] != 'W' || type[1] != 'A' || type[2] != 'V' || type[3] != 'E')
fatalError("OpenAL Error: Not a WAVE file");
fread(type, sizeof(char), 4, fp);
if (type[0] != 'f' || type[1] != 'm' || type[2] != 't' || type[3] != ' ')
fatalError("OpenAL Error: Not a fmt");
fread(&chunkSize, sizeof(DWORD), 1, fp);
fread(&formatType, sizeof(short), 1, fp);
fread(&channels, sizeof(short), 1, fp);
fread(&sampleRate, sizeof(DWORD), 1, fp);
fread(&avgBytesPerSec, sizeof(DWORD), 1, fp);
fread(&bytesPerSample, sizeof(short), 1, fp);
fread(&bitsPerSample, sizeof(short), 1, fp);
fread(type, sizeof(char), 4, fp);
if (type[0] != 'd' || type[1] != 'a' || type[2] != 't' || type[3] != 'a')
fatalError("OpenAL Error: Missing DATA");
fread(&dataSize, sizeof(DWORD), 1, fp);
ALCdevice* device;
ALCcontext* context;
device = alcOpenDevice(NULL);
if (!device)
fatalError("OpenAL Error: No sound device detected");
context = alcCreateContext(device, NULL);
alcMakeContextCurrent(context);
if (!context)
fatalError("OpenAL Error: No sound context");
unsigned char* buf = new unsigned char[dataSize];
fread(buf, sizeof(BYTE), dataSize, fp);
ALuint source;
ALuint buffer;
ALuint frequency = sampleRate;
ALenum format = 0;
alGenBuffers(1, &buffer);
alGenSources(1, &source);
if (bitsPerSample == 8)
{
if (channels == 1)
format = AL_FORMAT_MONO8;
else if (channels == 2)
format = AL_FORMAT_STEREO8;
}
else if (bitsPerSample == 16)
{
if (channels == 1)
format = AL_FORMAT_MONO16;
else if (channels == 2)
format = AL_FORMAT_STEREO16;
}
alBufferData(buffer, format, buf, dataSize, frequency);
ALfloat SourcePos[] = { 0.0f, 0.0f, 0.0f };
ALfloat SourceVel[] = { 0.0f, 0.0f, 0.0f };
ALfloat ListenerPos[] = { 0.0f, 0.0f, 0.0f };
ALfloat ListenerVel[] = { 0.0f, 0.0f, 0.0f };
ALfloat ListenerOri[] = { 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f };
// Listener
alListenerfv(AL_POSITION, ListenerPos);
alListenerfv(AL_VELOCITY, ListenerVel);
alListenerfv(AL_ORIENTATION, ListenerOri);
// Source
alSourcei(source, AL_BUFFER, buffer);
alSourcef(source, AL_PITCH, 1.0f);
alSourcef(source, AL_GAIN, 1.0f);
alSourcefv(source, AL_POSITION, SourcePos);
alSourcefv(source, AL_VELOCITY, SourceVel);
alSourcei(source, AL_LOOPING, AL_FALSE);
alSourcePlay(source);
fclose(fp);
delete[] buf;
alDeleteSources(1, &source);
alDeleteBuffers(1, &buffer);
alcMakeContextCurrent(NULL);
alcDestroyContext(context);
alcCloseDevice(device);
| |
doc_23533136
|
I've been so far successful in setting up the project and the executable is being generated. However, to flash the board I need an ".hex". file.
I've followed the Nordic nRF5SDK examples for gcc to get some clues about the compiling and linking stages and pass them to the CMake routines.
However, I cannot generate any ".out" file to proper extract the ".hex" file.
I've played with the compiling flags and linker flags but without success.
I've setted up the init flags in the toolchain file as well as the compilers, the hex is being generated with a custom command:
(...)
add_executable(main main.c)
target_link_libraries(main sdk_lib)
add_custom_command(
TARGET
main
POST_BUILD
COMMAND
${ARM_OBJCOPY} -O ihex ${CMAKE_CURRENT_BINARY_DIR}/main${CMAKE_EXECUTABLE_SUFFIX} ${CMAKE_SOURCE_DIR}/main.hex
)
(...)
The issue is that I am using the binary file for extracting the hex, instead of a proper ".out" file.
How can I generate it without using another custom command parallel to the main build?
P.S.: Here is the current state of the project https://github.com/NunoRVicente/cmake-arm-toolchain
A: why is it a trouble? So I figured out where the problem starts.
Basically the elf file is not being well generated, so naturally the .hex has problems as well.
The issue here now is to understand why the elf is broken, and it is overtaking my knowledge.
I've building the sdk_lib as STATIC with the SDK code and included the directories where the header files are. I've added the executable and linked the main with sdk_lib.
When I analyse the compilation process, the OBJ files are all being generated and at the end thinks are linked. But there is something odd that I can't understand.
[95%] Building C object CMakeFiles/main.dir/main.c.obj
/opt/gcc-arm-none-eabi-8-2019-q3-update/bin/arm-none-eabi-gcc -DBOARD_PCA10040 -DBSP_DEFINES_ONLY -DCONFIG_GPIO_AS_PINRESET -DFLOAT_ABI_HARD -DNRF52 -DNRF52832_XXAA -DNRF52_PAN_74 -D__HEAP_SIZE=8192 -D__STACK_SIZE=8192 -I/opt/nRF5_SDK_15.3.0_59ac345/components -I/opt/nRF5_SDK_15.3.0_59ac345/modules/nrfx/mdk -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/strerror -I/opt/nRF5_SDK_15.3.0_59ac345/components/toolchain/cmsis/include -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/util -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/balloc -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/ringbuf -I/opt/nRF5_SDK_15.3.0_59ac345/modules/nrfx/hal -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/bsp -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/log -I/opt/nRF5_SDK_15.3.0_59ac345/modules/nrfx -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/experimental_section_vars -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/delay -I/opt/nRF5_SDK_15.3.0_59ac345/integration/nrfx -I/opt/nRF5_SDK_15.3.0_59ac345/components/drivers_nrf/nrf_soc_nosd -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/atomic -I/opt/nRF5_SDK_15.3.0_59ac345/components/boards -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/memobj -I/opt/nRF5_SDK_15.3.0_59ac345/external/fprintf -I/opt/nRF5_SDK_15.3.0_59ac345/components/libraries/log/src -I/opt/nRF5_SDK_15.3.0_59ac345/examples/peripheral/blinky/pca10040/blank/config -O0 -g0 -mcpu=cortex-m4 -mthumb -mabi=aapcs -Wall -Wextra -mfloat-abi=hard -mfpu=fpv4-sp-d16 -ffunction-sections -fdata-sections -fno-strict-aliasing -fno-builtin -fshort-enums -g -o CMakeFiles/main.dir/main.c.obj -c /home/ricardo/Git/cmake-arm-toolchain/main.c
[100%] Linking C executable main
/home/ricardo/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/192.6603.37/bin/cmake/linux/bin/cmake -E cmake_link_script CMakeFiles/main.dir/link.txt --verbose=1
/opt/gcc-arm-none-eabi-8-2019-q3-update/bin/arm-none-eabi-gcc -O0 -g0 -mcpu=cortex-m4 -mthumb -mabi=aapcs -Wall -Wextra -mfloat-abi=hard -mfpu=fpv4-sp-d16 -ffunction-sections -fdata-sections -fno-strict-aliasing -fno-builtin -fshort-enums -g -O0 -g0 -mcpu=cortex-m4 -mthumb -mabi=aapcs -mfloat-abi=hard -mfpu=fpv4-sp-d16 -Wl,--gc-sections --specs=nano.specs --specs=nosys.specs -L/opt/nRF5_SDK_15.3.0_59ac345/modules/nrfx/mdk -T/home/ricardo/Git/cmake-arm-toolchain/linker.ld -lc -lnosys -lm CMakeFiles/main.dir/main.c.obj -o main libsdk_lib.a
/opt/gcc-arm-none-eabi-8-2019-q3-update/bin/../lib/gcc/arm-none-eabi/8.3.1/../../../../arm-none-eabi/bin/ld: warning: cannot find entry symbol Reset_Handler; defaulting to 0000000000000000
make[3]: Leaving directory '/home/ricardo/Git/cmake-arm-toolchain/cmake-build-debug'
[100%] Built target main
The linker that is being invoked is not the arm-none-eabi-ld but another one in the toolchain folder. So I am starting to think if the linking process is being performed correctly and all the object files are being build in one elf file.
I am a bit lost in this process right now.
| |
doc_23533137
|
DirectoryEntry entry...
entry.Properties["groupType"].Value;
is an int32, whose range is -2,147,483,647 to 2,147,483,648 (or -0x7FFFFFFF to 0x80000000)
So anytime there is the GROUP_TYPE_SECURITY_ENABLED and any other arbitraty flag set, the numeric value exceeds the the range of an int32 and an overflow happens.
Does anyone know how to avoid this overflow in order to read the correct value?
A: Referencing @fourpastmidnight's answer and these articles object-group-attribute-grouptype and msdn Group-Type attribute, I was able to find a solution that does not require casting to uint or parsing through an if ... else if statement.
Seeing the negative values from the first link and from @wodzu's comment on the return value of -2147483646, I tried inverting the SECURITY_ENALBED value to -0x80000000.
[System.Flags]
public enum GroupType
{
BUILTIN_LOCAL_GROUP = 0x00000001,
ACCOUNT_GROUP = 0x00000002,
RESOURCE_GROUP = 0x00000004,
UNIVERSAL_GROUP = 0x00000008,
APP_BASIC_GROUP = 0x00000010,
APP_QUERY_GROUP = 0x00000020,
SECURITY_ENABLED = -0x80000000
}
Now when getting the value and casting as GroupType
var groupType = (GroupType)this.Entry.Properties["groupType"].Value
You can then use .ToString() on the GroupType value which will return a comma separated string of each flag.
Or you can use the .HasFlag method to check if it is a Security Group
bool IsSecurityGroup = groupType.HasFlag(GroupType.SECURITY_ENABLED);
A: I think you need to use UInt32 as the type of your enumeration GroupType as follows:
[Flags]
public enum GroupType : uint
{
BUILTIN_LOCAL_GROUP = 0x00000001,
ACCOUNT_GROUP = 0x00000002,
RESOURCE_GROUP = 0x00000004,
UNIVERSAL_GROUP = 0x00000008,
APP_BASIC_GROUP = 0x00000010,
APP_QUERY_GROUP = 0x00000020,
SECURITY_ENABLED = 0x80000000
}
Let me know if that solves your problem.
EDIT: OK, I wasn't sure if Entry was an object you created, or part of the Active Directory API. Having said that, I quick created the following variables in a project I'm currently working on and compiled as follows:
// I only made it static so I could get my compiler to compile this in something I'm currently
// working on. It's not necessary for it to be static.
static int SECURITY_ENABLED = 0x80000000;
int newValue = SECURITY_ENABLED | 1;
I did not get any compile-time errors. In fact, re-looking at the value 0x80000000, it's well with in the range of an Int32.
Re-looking at your code above, on what line exactly, are you getting the error? I see this suspicios code:
if (groupTypes.Count == 1)
{
var firstFlag = (int) groupTypes[0];
// What is this checking, exactly?
// Is this where the error is occurring?
var longFlag = -(((long) flag) - firstFlag);
if ((longFlag == 0x80000000)) // Extra parentheses here...just a formatting thing
groupTypes.Add(GroupType.SECURITY_ENABLED);
}
Perhaps this code could be simplified?
public List<GroupType> GetGroupType()
{
var groupTypes = new List<GroupType>();
var flag = (GroupType) this.Entry.Properties["groupType"].Value;
if (flag & GroupType.ACCOUNT_GROUP > 0)
groupTypes.Add(GroupType.ACCOUNT_GROUP;
else if (flag & GroupType.APP_BASIC_GROUP > 0)
groupTypes.Add(GroupType.APP_BASIC_GROUP);
// ... Other else if ad nauseum ...
else if (flag & GroupType.SERUCITY_ENABLED > 0)
groupTypes.Add(GroupType.SECURITY_ENABLED);
return groupTypes;
}
If you really need an ArrayList() for whatever reason, you could then just do return groupTypes.ToArray<int>();
HTH.
A: A little Python to decode groupType AD attribute value
*
*prepare a dictionary with all the defined combination. (ref. Microsoft
gt_decode_dict = {
"0x00000001": "SYSTEM CREATED", # Specifies a group that is created by the system.
"0x00000002": "GLOBAL", # Specifies a group with global scope.
"0x00000004": "LOCAL", # Specifies a group with domain local scope.
"0x00000008": "UNIVERSAL", # Specifies a group with universal scope.
"0x00000010": "APP_BASIC", # Specifies an APP_BASIC group for Windows Server Authorization Manager.
"0x00000020": "APP_QUERY", # Specifies an APP_QUERY group for Windows Server Authorization Manager.
"0x80000000": "SECURITY"} # Specifies a security group. If this flag is not set, then the group is a distribution group.
*define a function to decode the groupType value
def decode_gt(_group_type):
#
# Decode groupType attribute.
#
global gt_decode_dict
_delta = 0
_translatedGT = ""
if _group_type > 0:
_hex_gt = hex(_group_type)
_gt_work = int(_hex_gt[2:])
_gt_work = str(_gt_work).rjust(8, "0")
_gt_key = r'0x' + str(_gt_work)
_translatedGT += "DISTRIBUTION - "
else:
_delta = 2147483648 - abs(_group_type)
if (_delta % 2) > 0:
_translatedGT = "SECURITY - SYSTEM CREATED - "
_gt_key = r'0x' + str(_delta - 1).rjust(8, "0")
else:
_translatedGT = "SECURITY - "
_gt_key = r'0x' + str(_delta).rjust(8, "0")
if _gt_key in gt_decode_dict.keys():
_translatedGT += gt_decode_dict[_gt_key]
else:
notification(" Invalid groupType key: " + str(_gt_key) + ". Values dec: " + str(_group_type) + " delta:" + str(_delta) + ", for group " + _group_dn, 4)
_translatedGT += " Error "
return _translatedGT
*call the function passing the groupType as an Integer
groupType = decode_gt(int(_groupType))
| |
doc_23533138
|
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-animate.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<div ng-controller="MainCtrl">
<input type="text" ng-model="formData.itemText" />
<button ng-click="addItem()">Add</button>
<ul>
<li ng-repeat="item in items">{{item.itemText}}</li>
</ul>
</div>
</body>
</html>
script.js
app = angular.module("app", ["ngAnimate"])
app.controller("MainCtrl", function($scope){
$scope.items = []
$scope.formData = {}
$scope.addItem = function(){
$scope.items.push($scope.formData)
$scope.formData = {}
}
})
plnkr
http://plnkr.co/edit/kqOLpxy2HjPhxnjXHu2L?p=preview
A: The documentation explains how you can achieve it in different ways.
Simple example:
.highlight {
transition: all linear 300ms;
}
.highlight.ng-enter {
opacity: 0;
color: firebrick;
}
.highlight.ng-enter.ng-enter-active {
opacity: 1;
}
And:
<li ng-repeat="item in items" class="highlight">
Demo: http://plnkr.co/edit/vI0U8aopxoc4c4Bfx2Rh?p=preview
| |
doc_23533139
|
If I manually set up a response type "option" answer in my node the JSON-object looks like this:
{
"output": {
"generic": [
{
"title": "Välj mötestyp",
"options": [
{
"label": "Rådgivning familjerätt 30 min",
"value": {
"input": {
"text": "447472"
}
}
},
{
"label": "Rådgivning familjerätt 60 min",
"value": {
"input": {
"text": "448032"
}
}
}
],
"description": "Välj typ av möte du vill boka",
"response_type": "option",
"preference": "dropdown"
}
]
}
}
My cloud function can create this JSON with x no of options. But how can I use this data in Assistant?
The easiest would be to let the cloud function generate the complete JSON and then just output the returned JSON like this:
{
$context.output"
}
..but that's not allowed.
Generated output-object from my function:
[{"serviceId":447472,"serviceName":"Rådgivning Familjerätt 30 min"},{"serviceId":448032,"serviceName":"Rådgivning Familjerätt 60 min"}]
Any advice on how to do this?
A: I don't see a simple way of generating the entire output and options. What you could do is this:
*
*Generate the option labels and values
*Pass them into a generic output node that has predefined structures for 1, 2, 3, etc. options. Check based on the array size of your context variable which predefined response structure to fill.
I tested the following:
{
"context": {"my": [ {
"label": "First option",
"value": "one"
},
{
"label": "Second",
"value": "two" }]},
"output": {
"generic": [
{
"title": "This is a test",
"options": [{"label": "<? $my[0].label ?>",
"value": {
"input": {
"text": "my[0].value"
}
}
},{"label": "<? $my[1].label ?>", "value": {
"input": {
"text": "<? $my[1].value ?>"
}
}
}],
"response_type": "option"
}
]
}
}
It defined a context variable with the options, analogous to the options structure. In the output access the labels and values, later modifying the to proove that they are used and can be modified.
| |
doc_23533140
|
Error response from daemon: error while mounting volume '/var/lib/docker/volumes/test_data/_data': failed to mount local volume: mount /etc/hapee-2.2/certs:/var/lib/docker/volumes/test_data/_data, data: addr=10.15.50.27,nolock,soft: invalid argument
Exports file from the NFS appears to be set up correctly. I've tried deleting '/home/' from the file path as well. IP address is redacted.
/etc/hapee-2.2/certs <ipaddressofpc>(rw,sync,no_subtree_check,no_root_squash)
I keep suspecting the docker-compose.yml, but I'm not sure what the issue with it would be
version: '3.7'
services:
hapee:
image: haproxy:2.2
container_name: test
restart: always
ports:
- "80:80"
- "443:443"
- "8888:8888"
volumes:
- data:/etc/hapee-2.2/certs
logging:
options:
max-size: 100m
max-file: "3"
volumes:
data:
driver_opts:
type: "nfs"
o: "addr=10.15.50.27,nolock,soft,ro"
device: "/etc/hapee-2.2/certs"
Alternatively, does anyone know another method of mounting SSL certificates to an HA Proxy container with docker compose?
Thanks!
| |
doc_23533141
|
implementation 'org.codelibs.elasticsearch.module:lang-painless:7.10.2'
implementation 'org.codelibs.elasticsearch.module:analysis-common:7.10.2'
Spinning up a node looks like
public EmbeddedElastic() throws NodeValidationException, IOException {
tempDir = Files.createTempDirectory("elastic_search_temp").toAbsolutePath().toString();
int port = getAvailableBasePort();
Map<String, String> settings = new HashMap<>();
settings.put("path.home", tempDir);
settings.put("http.port", Integer.toString(port));
settings.put("transport.tcp.port", Integer.toString(port + 1));
settings.put("transport.type", "netty4");
settings.put("http.cors.enabled", Boolean.FALSE.toString());
new PluginNode(settings).start();
client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", port, "http")));
System.out.println("Client: " + client.getClass().getName());
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// file deletion
}
});
}
private static class PluginNode extends Node {
public PluginNode(Map<String, String> preparedSettings) {
super(InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, preparedSettings,
null, () -> "node-test"),
Lists.newArrayList(Netty4Plugin.class, ParentJoinPlugin.class, CommonAnalysisPlugin.class,
PainlessPlugin.class),
false);
System.out.println("Started local elastic with PainlessPlugin loaded.");
}
}
Now I am upgrading to ES 7.16.2 and the same code doesn't work well. I presume its because of the lang-painless and analysis-common libraries. Their latest version is only 7.10.
The exception I receive after upgrading the elasticsearch client to 7.16 and spring-data-elasticsearch to 4.3.0
Failed to instantiate [org.springframework.data.elasticsearch.core.ElasticsearchOperations]: Factory method 'elasticsearchTemplate' threw exception; nested exception is java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: org/elasticsearch/common/xcontent/ToXContentObject
Before I dive deep into fixing it, I am wondering if anyone has actually made unit tests work with 7.16 ES version? I have seen that Elasticsearch Test containers is the recommended way to go
EDIT:
Thanks to Augusto's tip on checking classes in Maven Central, I found out that lang-painless depends on certain libraries from elasticsearch client which are not available in the higher versions of ES client. So its not possible to write unit tests with the same libs.
A: Elasticsearch moved this class in 7.16 from the org.elasticsearch.common.xcontent package to the org.elasticsearch.xcontent package, a breaking change between 7.15 and 7.16.
Spring Data Elasticsearch 4.3 is built against 7.15.x and so won't work with Elasticsearch 7.16 libraries.
You either need to use Elasticsearch 7.15 or wait for Spring Data Elasticsearch 4.4 (the first milestone for that should be published next week) to be released which is built against 7.16.
And, yes, you should better use testcontainers.
A: You are probably missing the dependency with this class. It could be that before it came transitevily with the ES client.
Try adding org.elasticsearch:elasticsearch-x-content:7.15.2 to your build tool. A word of caution, you might be missing other dependencies too.
Just as a tip, if you ever get a NoClassDefFoundError, one of the easiest ways to find where that class is defined is to search in maven central. Search for fc:<fully_qualified_class_name>, and it will show all the jars where the class is present.
| |
doc_23533142
|
try:
next_page = request.POST.get('next_page')
except AttributeError:
raise ImproperlyConfigured(
"No URL to redirect to. Either provide a url or define"
" a get_absolute_url method on the Model.")
However, if next_page is not provided this code results in next_page = None and the error is not raised. Where am I going wrong?
A: To check if a key is in the POST dictionary you can use a regular in
if 'next_page' not in request.POST:
raise ImproperlyConfigured(
"No URL to redirect to. Either provide a url or define"
" a get_absolute_url method on the Model.")
A: Rather than use a try except block, you could just use a normal conditional clause to check if next_page is not None.
(For clarity, I added a default value of None to the get method call if the 'next_page' key isn't found)
next_page = request.POST.get('next_page', None)
if next_page is not None:
# redirect code
else:
raise ImproperlyConfigured(
"No URL to redirect to. Either provide a url or define"
" a get_absolute_url method on the Model.")
EDIT:
Another option based on asking forgiveness rather than permission:
try:
redirect(request.POST.get('next_page'))
except KeyError:
raise ImproperlyConfigured("text")
Here you don't need to check if the next_page value is None, you rely on the redirect function throwing an error if it receives None. You then catch that, and raise your Exception.
| |
doc_23533143
|
I have the following RAML contract
types:
EpaymentItem:
type: object
properties:
Payment: string
EpaymentTypeTwo:
type: EpaymentItem
properties:
Card: string
EpaymentTypeThree:
type: EpaymentItem
properties:
Bill: string
EpaymentDTO:
type: object
properties:
payment: EpaymentItem
name: string
address: string
/Epayment:
/{paymentId}
get:
responses:
200:
body:
application/json:
type: EpaymentDTO
Now the thing i cant get to work is that whenever I'm trying to reply with either EpaymentTypeTwo or EpaymentTypeThree the json deserializer thinks its just an EpaymentItem. Unless i specify the type as the one it will be getting back it always deserializes into the baseclass.
Is there a way to make the deserializer understand that the type arriving at im is an inherited class?.
Thanks in advance!
EDIT1: Added deserializer. The serializer cant be shows since its done through a IHttpActionResult.
if (typedContent != null)
return typedContent;
IEnumerable<string> values = new List<string>();
if (RawContent != null && RawContent.Headers != null)
RawContent.Headers.TryGetValues("Content-Type", out values);
if (values.Any(hv => hv.ToLowerInvariant().Contains("xml")) &&
!values.Any(hv => hv.ToLowerInvariant().Contains("json")))
{
var task = RawContent.ReadAsStreamAsync();
var xmlStream = task.GetAwaiter().GetResult();
typedContent = (EpaymentDTO)new XmlSerializer(typeof(EpaymentDTO)).Deserialize(xmlStream);
}
else
{
var task = Formatters != null && Formatters.Any()
? RawContent.ReadAsAsync<EpaymentDTO>(Formatters).ConfigureAwait(false)
: RawContent.ReadAsAsync<EpaymentDTO>().ConfigureAwait(false);
typedContent = task.GetAwaiter().GetResult();
}
return typedContent;
| |
doc_23533144
|
Sample data:
CEF:0|Microsoft|Microsoft
Windows||Microsoft-Windows-Security-Auditing:434|An account was logged
off.|Low| eventId=260 externalId=44 msg=Network: A user or computer
logged on to this computer from the network.
categorySignificance=/Informational categoryBehavior=/Access/Stop
categoryDeviceGroup=/Operating System catdt=Operating System
categoryOutcome=/Success categoryObject=/Host/Operating|Vista
ad.EventIndex=-972 ad.WindowsParserFamily=Windows 2008 R2|2008|7|Vista
ad.WindowsVersion=Windows Server
For this we need to separate out first seven columns by pipe and consider everything after that as a single column.
DDL: (CEF STRING, Vendor STRING, Product STRING, Version STRING, Signature STRING, Name STRING, Severity STRING, Extension STRING)
So Sample data output should be mapped to columns as follows:
Col1: CEF:0
Col2: Microsoft
Col3: Microsoft Windows
Col4:
Col5: Microsoft-Windows-Security-Auditing:434
Col6: An account was logged off.
Col7: Low
Col8: eventId=260 externalId=44 msg=Network: A user or computer logged on to this computer from the network. categorySignificance=/Informational categoryBehavior=/Access/Stop categoryDeviceGroup=/Operating System catdt=Operating System categoryOutcome=/Success categoryObject=/Host/Operating|Vista ad.EventIndex=-972 ad.WindowsParserFamily=Windows 2008 R2|2008|7|Vista ad.WindowsVersion=Windows Server
What should be the input.regex?
Also is it possible to have a Map data type for the columns in (key=value) format using this Regex?
A: I have no expirience with hive, but looking at some examples the following value for input.regex shoud work:
([^\\|]*)\\|([^\\|]*)\\|([^\\|]*)\\|([^\\|]*)\\|([^\\|]*)\\|([^\\|]*)\\|([^\\|]*)\\|(.*)
You might need to configure an output.format.string. Maybe the following links help:
*
*regex for access log in hive serde
*http://mail-archives.apache.org/mod_mbox/hive-user/201112.mbox/%3C6f4a3faf-9cdc-4c22-ba7e-5258ffc7fa76@sms-zimbra-message-store-03.sms.scalar.ca%3E
| |
doc_23533145
|
#sidebar .ui-widget-content {
border: 1px solid #d2d2d2;
background: #eee;
padding: 10px 10px 15px 10px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
-o-border-radius: 5px;
-ms-border-radius: 5px;
-khtml-border-radius: 5px;
border-radius: 5px;
}
This video on Screenr (22secs) shows whats happening. 1st screen shows search content without padding after 1 refresh, it has padding. Sometimes I get no padding on the meta list but padding on the search content. What might be happening. In firebug, I see that padding 0'ed out on element.style is the cause. So it appears jQuery UI sets the padding? But why does it change randomly
A: My first suspicion is that the plugin is applying either .css() calls or adding other classes to the accordion upon instantiation or upon sliding content.
I have played with re-styling the accordion and by far the hardest UI component to alter... purley because of it's onchange calls within the plugin...
I actually dont have a solution now, but i hope that's a hint in the right direction
| |
doc_23533146
|
I'm trying to add 4 of each words in my ArrayList into the ArrayList itself. I have in my ArrayList two Strings. One is "java" and the other one is "Program". I'm trying to write a program that adds a total of 4 words of each word. Ex: I'm trying to add 4 x java and 4 x program.
Here's what I've got so far. I have no idea, what I'm doing wrong.
Any help or hints would be much appreciated.
/*
* Write a method called quadList that takes an ArrayList of strings as a parameter
* and replaces every string with four of that same string.
* For example, if the list stores the values ["java", "program"]
* before the method is called,it should store the values
* ["java ", " java ", " java ", " java ", "program", "program", "program", "program"]
* after the method finishes executing.
*/
import java.util.ArrayList;
public class Ex10_4_quadList {
public static void main(String[] args) {
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("Java");
arrList.add("Program");
System.out.println("Before: " + arrList);
quadList(arrList);
System.out.println("after " + arrList);
}
private static void quadList(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < 4; j++) {
String temp = list.get(i);
list.add(temp);
}
}
}
}
Here's the fixed code:
public class Ex10_4_quadList {
public static void main(String[] args) {
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("Java");
arrList.add("Program");
System.out.println("Before: " + arrList);
quadList(arrList);
Collections.sort(arrList);
System.out.println("after " + arrList);
}
private static void quadList(ArrayList<String> list) {
int initial = list.size();
for (int i = 0; i < initial; i++) {
for (int j = 0; j < 3; j++) {
String temp = list.get(i);
list.add(temp);
}
}
}
}
A: Ideally instead of iterating with an index you would use the foreach style of loop. However this means that you can't alter the list as you iterate. So you will need to add the members to a new list and then add all of them afterwards:
List<String> duplicates = new ArrayList<>();
for (String member: list) {
for (int i = 0; i < 4; i++) {
duplicates.add(member);
}
}
list.addAll(duplicates);
There are a number of shortcuts you can use if you are using Java 8 and, therefore, have access to streams:
list.addAll(list.stream()
.flatMap(m -> Stream.generate(() -> m).limit(4))
.collect(Collectors.toList());
This code says for each member of the list turn it into 4 copies of the item then collect all those as a list and add them to the original list.
A: Try:
private static void quadList(ArrayList<String> list) {
int listSize = list.size();
for (int i = 0; i < listSize; i++) {
for (int j = 0; j < 4; j++) {
String temp = list.get(i);
list.add(temp);
}
}
}
The problem with the code is that the list.size() is evaluated on every iteration. Since the inner loop is increasing the list size faster than the outer loop can iterate over it, the code effectively loops infinitely until JVM runs out of memory.
| |
doc_23533147
|
I've spent hours trying to fix the code but it just wouldnt work. I need to see what have i done wrong. In the previous version it was working fine. Is there any way to see the code in the previous apk? or reset changes or anything like that in android studio?
A: Android Studio has a code history feature which allows you to see previous versions of a corresponding file. Just right click on a file in the IDE's file explorer and you will see this option.
A: Right click the file in android studio, Local History -> Show History. Maybe you can see old version of file.
If not, here is the certain solution: download old apk from Play store, use Dex2jar to decompile old .dex file and see codes with JD-GUI.
Or you can use Jadx too.
A: You could try googling for an .apk decompiler and try to decompile your old .apk. You may get mixed results but if you are desperate that is one option.
But from now on, make sure to use git for source control in your apps. Android Studio makes it really easy to use git.
| |
doc_23533148
|
I know I could put static initializers in every class and have them do some sort of registration, but this is tedious and error-prone. It would be great if there was a cleaner way to do it through the AppDomain or Assembly class or something. Thanks!
A: you can find which Assemblies are loaded in the current app domain really easily - AppDomain.CurrentDomain.GetAssemblies(). Of course, it'll just give you the information about assemblies loaded in the specific time when you execute this. There are much better ways to find and clean redundant code in the solution. Personally, i like ReSharper. it has great feature called "Find code issues" (can be used for the entire solution) which will give you a list of unused symbols, which is exactly what you're looking for.
A: You could use an aspect library like PostSharp, Spring.Aop to intercept all calls to methods, properties etc. and add the type name to a set. Another way would be to use a profiler. Both approaches, unfortunately need you to keep using the application (hopefully it's a desktop application with a UI).
By the way have you tried to enable CodeAnalysis and look for Performance warnings? You will receive warnings for all methods, properties, fields that are never called.
| |
doc_23533149
|
Python pandas function to concat into one row different values into one column based on repeating values in another
What would be the best way to delimit for future searching? I just realized the Project Types are multiple words long. So instead of just Spend, and Visibility, and Culture, the Project Types would be: Spend Analytics & Manager Visibility & Team Culture. For example: My first thought was to place each string value into quotes. Is this the best practices way when I'll have to filter later?
import pandas as pd
data = {'Invoice Number':[1279581,1229422],
'Project Key':[263736, 259661],
'Project Type': ['"Manager Visibility" "Team Culture"', '"Spend Analytics" "Manager Visibility" "Team Culture"']
}
output = pd.DataFrame(data)
output
| |
doc_23533150
|
A: Actually, any API level.
That's because Kotlin is compiled into bytecode for JVM 6 platform, which is supported in all Android API levels. So, unless you use any of the newer Android API in your Kotlin code, it does not require any specific API level.
| |
doc_23533151
|
If not, whats the simplest way to implement?
I have a lot of these things to do all over the code, so the simpler the call, the best it is
An example in Ruby
a = [ 1, 2, 3 ] #=> [1, 2, 3]
a.shuffle #=> [2, 3, 1] returns new array shuffled
Thanks in advance :)
A: In Scala you can use scala.util.Random:
util.Random.shuffle((1 to 10).toSeq)
//Vector(9, 6, 8, 7, 10, 1, 2, 5, 3, 4)
util.Random.shuffle(List('A', 'B', 'C', 'D', 'E', 'F'))
//List(B, D, A, E, C, F)
Your results may vary...
| |
doc_23533152
|
I want to parse node, relations, and ways.
when I try to parse nodes I get that message.
The code looks like
package myCode;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import protpbufCode.OsmPbf;
import protpbufCode.OsmPbf.Node;
import protpbufCode.OsmPbf.PrimitiveGroup;
public class ReadingPBF
{
public static void print(PrimitiveGroup node)
{
for (Node m: node.getNodesList())
{
System.out.print("Person ID: " + m.getId() + " ");
System.out.print(" Lat: " + m.getLat()+ " ");
System.out.print(" Long: "+ m.getLon()+ " ");
System.out.println("");
}
}
public static void main (String args[])
{
try
{
PrimitiveGroup newNode = PrimitiveGroup.parseFrom(new FileInputStream(new File("isle.pbf")));
print(newNode);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println(e.getCause());
}
}
}
the OsmPbf is java class that created using the protobuf compiler.
and that what gets printed.
com.google.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
at com.google.protobuf.InvalidProtocolBufferException.invalidTag(InvalidProtocolBufferException.java:89)
at com.google.protobuf.CodedInputStream.readTag(CodedInputStream.java:158)
at protpbufCode.OsmPbf$PrimitiveGroup.<init>(OsmPbf.java:5230)
at protpbufCode.OsmPbf$PrimitiveGroup.<init>(OsmPbf.java:5219)
at protpbufCode.OsmPbf$PrimitiveGroup$1.parsePartialFrom(OsmPbf.java:5329)
at protpbufCode.OsmPbf$PrimitiveGroup$1.parsePartialFrom(OsmPbf.java:1)
at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:192)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:209)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:215)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
at protpbufCode.OsmPbf$PrimitiveGroup.parseFrom(OsmPbf.java:5627)
at myCode.ReadingPBF.main(ReadingPBF.java:33)
Protocol message contained an invalid tag (zero).
null
A: OpenStreetMap .pbf files are not simple protobufs. See the documentation here:
http://wiki.openstreetmap.org/wiki/PBF_Format
Under the section "File format", you'll see this:
The format is a repeating sequence of:
*
*int4: length of the BlobHeader message in network byte order
*serialized BlobHeader message
*serialized Blob message (size is given in the header)
That is, the file starts out with a 4-byte integer before the first protobuf message. Since this integer is probably smaller than 2^24, the first byte will of course be zero, which explains the exact exception you are seeing.
You will need to read this 4-byte value manually, then make sure to read only that many bytes and parse them as a BlobHeader, and so on.
Personally I'd recommend looking for a PBF decoder library that already handles this for you. There must be a few out there.
| |
doc_23533153
|
The action is a form and has been added to my custom module. I am trying to reach it from itself in the following manner so that on form submission, the form-data is sent back to itself (aka, the action link leads back to the same page the form is on):
<form method="POST" name="ConfigureSettings" action="#bwc/index.php?module=CustomModule&action=newAction">
Based on SugarCRM Support's Troubleshooting Cross-Site Forgery Messages, the way to add an additional action is as follows:
To add the unregistered action as an allowed action (e.g. custom
module), add the following line of code to the config_override.php
file:
$sugar_config['http_referer']['actions'] =array( 'index', 'ListView', 'DetailView', 'EditView', 'oauth', 'authorize', 'Authenticate', 'Login', 'SupportPortal', 'bad_action' );
Doing this alone does not work, and trying to save my changes or cancel editing my form will still lead to the same error:
Cross Site Request Forgery (XSRF) Attack Detected
Form authentication failure (CustomModule -> newAction). Contact your administrator.
Is there something I have to edit in the $sugar_config to relate it to my specific action? I tried changing bad_action to newAction, but to no avail.
Found a workaround here which will just log the error rather than abort the action, and it proves that my form is working correctly in which I am led back to the same page and the form has been updated.
Unfortunately, this is not a solution to my problem because this is unsafe for a production instance, and I am still not sure why I'm getting the error in the first place as I am not redirecting to a site outside of the instance.
A: Turns out that the HTML form needs to be separated from the PHP file by using a Template file and Smarty tags to replace the instances of PHP in the Template file.
Did the above, then included the {sugar_csrf_form_token} mentioned here in the Template file, and its working correctly now.
| |
doc_23533154
|
The submenu is working well, except when I have addition $_GET params which are in the url.
Like this: admin/manage/pages/id/1 <-- With this url the submenu is not showing
Link explained:
{module}/{controller}/{action}/{key}/{value}
I think I have no more information, because my setup is just basic, and the behavior strange.
Hopefully you have an idea where this is going wrong.
Bytheway: I use the default routes.
Edit: I use the following code for displaying the submenu's $this->navigation()->menu()->setMaxDepth(0); (both code suggestions from ArtWorkAD did not work)
Here's my navigation.xml:`
Website
/
<beheer>
<label>Beheer</label>
<module>admin</module>
<controller>beheer</controller>
<uri>/admin/beheer</uri>
<pages>
<paginabeheer>
<label>Pagina beheer</label>
<module>admin</module>
<controller>paginabeheer</controller>
<action>index</action>
**//THE CODE BELOW IS ADDED ON ArtWorkAD's SUGGESTION**
<pages>
<paginabeheer>
<label>Pagina beheer</label>
<module>admin</module>
<controller>paginabeheer</controller>
<action>index</action>
</paginabeheer>
</pages>
**// END ADDED CODE**
</paginabeheer>
</pages>
</beheer>
</nav>
`
A: Some people say this is a bug but I think there is a simple workaround.
Have a look at this issue :Zend_View_Helper_Navigation_Menu::renderSubMenu() should use minDepth=1 per default
So try using minDepth like this
// Navigation 1. Level
echo $this->navigation()->menu()->renderMenu(null,
array('minDepth' => 0, 'maxDepth' => 0));
// Navigation 2. Level
echo $this->navigation()->menu()->renderMenu(null,
array('minDepth' => 1, 'maxDepth' => 2, 'onlyActiveBranch' => true));
If this does not work try to add a submenu item to your submenu to see what happens, it should render you submenu now.
A: ArtWorkAD you were right! I have found what I did wrong.
Now the working code is: <?= $this->navigation()->menu()->setUlClass('navigation-submenu')->renderMenu(null,
array('minDepth' => 2, 'maxDepth' => 2)); ?>
So your answer was correct!
In my XML file it is needed that I have the extra sub-subpage. Thank you very much for your workaround!
I mark your post as answer.
| |
doc_23533155
|
Sidenote:
I'm only learning Haskell as part of a course on logic in which set theory is very important thus it would be really handy to have the notion of a set in Haskell. Having a list and removing duplicates (and possibly sorting) would result in a set as well but I'm curious if there's a particular reason why it's not built-in?
A: It exists as Data.Set. However, as you said, it can be implemented on top of list and so is not necessary to build up the language which, I think, is why it is in a module rather than being part of the definition of the language itself.
A: As other answers indicate, the question "Why is there no Set data type in Haskell?" is misguided: there is a Set data type.
If you'd like to know why Set isn't "built in" to Haskell, you could be asking one of two things.
*
*Why is Set not part of the language specification?
*Why is Set not in Prelude (the functions and data types that are imported by default)?
To answer the former, it is because the language is powerful enough to express the idea of a set without needing to bake it in. Being a language with a high emphasis on functional programming, special syntax for tuples and lists is built in, but even simple data types like Bool are defined in Prelude.
To answer the latter, well, again, with the emphasis on functional programming, most Haskellers tend to use lists. The list monad represents nondeterministic choice, and by allowing duplicates, you can sort of represent weighted choices.
Note how similar list comprehension syntax is to set notation. You can always use Set.fromList to convert a list into a "real" set, if necessary. As a begrudging shout out to Barry, this would be similar to using Python's set() method; Python has list comprehensions as well.
A: On a more philosophical level --- there can't ever be a strict correspondence between the mathematical concept of a set and a Haskell set implementation. Why not? Well, the type system, for starters. A mathematical set can have anything at all in it: {x | x is a positive integer, i < 15} is a set, but so is {1, tree, ham sandwich}. In Haskell, a Set a will need to hold some particular type. Putting Doubles and Floats into the same set won't typecheck.
As others have said, if you need to do some set-like things and don't mind the type restriction, Data.Set exists. It's not in Prelude because lists are usually more practical. But really, from a language design perspective, it doesn't make sense to think of mathematical sets as one datatype among many. Sets are more fundamental than that. You don't have sets, and numbers, and lists; you have sets of numbers, and sets of lists. The power of recursive types tends to obscure that distinction, but it's still real.
There is a place in Haskell, though, where we define arbitrary collections, and then define functions over those collections. The closest analog of the mathematical concept of sets in Haskell is the type system itself.
| |
doc_23533156
|
Syntax error : Invalid Syntax
A: That syntax error occurs because that command is supposed to be run from the command line and not the Python interpreter itself.
If you search for cmd or PowerShell and try it in that shell instead, it should work - I am guessing you are on Windows from the direction of slashes, but it will be called terminal on Linux and Mac.
If you want to execute it from a Python script you could use subprocess or os.system().
With os.system():
os.system('gsutil cp gs:\\somepath C:\\Users\\sensekar\\Desktop\\Python\\')
With subprocess:
subprocess.Popen('gsutil cp gs:\\somepath C:\\Users\\sensekar\\Desktop\\Python\\', shell=True, stdout=subprocess.PIPE)
Note that using subprocess is better practice.
Remeber also to use \\ and not escape character \.
| |
doc_23533157
|
I have seen some codes that swap the characters all at once, but that is not what I'am looking for.
For example:
var = 'abcde'
Expected output:
['bacde','acbde','abdce','abced']
How can I do this in Python?
A: You may use a below list comprehension expression to achieve this:
>>> var = 'abcde'
# v To reverse the substring
>>> [var[:i]+var[i:i+2][::-1]+var[i+2:] for i in range(len(var)-1)]
['bacde', 'acbde', 'abdce', 'abced']
A: Assuming the final entry from your expected output list is a typo, and that it should be 'abced' to keep the pattern going, then here is one way (unsure yet if it generalizes correctly based on your use case):
In [5]: x
Out[5]: 'abcde'
In [6]: [x[:i] + x[i+1] + x[i] + x[i+2:] for i in range(len(x)-1)]
Out[6]: ['bacde', 'acbde', 'abdce', 'abced']
A: A generator function will not use too much memory for longer strings:
def swap_pairs(s):
for i in range(len(s) - 1):
yield s[:i] + s[i + 1] + s[i] + s[i + 2:]
>>> swap_pairs('abcde')
<generator object swap_pairs at 0x1034d0f68>
>>> list(swap_pairs('abcde'))
['bacde', 'acbde', 'abdce', 'abced']
A: Here is a re approach:
x = 'abcde'
[re.sub(f'(.)(.)(?=.{{{i}}}$)', "\\2\\1", x) for i in reversed(range(len(x)-1))]
# ['bacde', 'acbde', 'abdce', 'abced']
And a variant that skips double characters:
x = 'abbde'
[s for s, i in (re.subn(f'(.)(?!\\1)(.)(?=.{{{i}}}$)', "\\2\\1", x) for i in reversed(range(len(x)-1))) if i]
# ['babde', 'abdbe', 'abbed']
| |
doc_23533158
|
Code:
<?php
$cfg = include('utilities.php');
mysqli_connect($cfg['host'], $cfg['user'], $cfg['password']);
mysqli_select_db($cfg['database']);
mysqli_query("INSERT INTO comment (userID, commentText, adventureID, dateTime) VALUES('$userid', '$commentInput', '$adventureid', '$date')");
?>
utilities.php :
<?php
return array(
'host' => 'host',
'user' => 'user',
'password' => 'password',
'database' => 'database'
);
?>
A: you forget to pass connection param to mysqli_query function:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "INSERT INTO comment (userID, commentText, adventureID, dateTime) VALUES('$userid', '$commentInput', '$adventureid', '$date')";
mysqli_query ($link , $query );
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode =
MYSQLI_STORE_RESULT ] )
mixed mysqli::query ( string $query [, int $resultmode =
MYSQLI_STORE_RESULT ] )
PHP Manual
| |
doc_23533159
|
[
{ "title":"SOC1 Certificate", "comment":"", "size":"286.845703125",
"name":"SOC1%20Cert.pdf", "filename":"fu_iik2rfypa3tzrxh", "ext":"pdf" },
{ "title":"SOC 2 cert", "comment":"", "size":"286.845703125",
"name":"SOC2%20Cert.pdf", "filename":"fu_97krdbic5nrdziy", "ext":"pdf" }
]
What would the PHP code be to read this and split the entry into two array records?
Thanks
A: Looks like the response contains JSON-data, so you should json_decode it to an array:
$data = json_decode('[{ "title":"SOC1 Certificate","comment":"","size":"286.845703125","name":"SOC1%20Cert.pdf","filename":"fu_iik2rfypa3tzrxh","ext":"pdf" },{ "title":"SOC 2 cert","comment":"","size":"286.845703125","name":"SOC2%20Cert.pdf","filename":"fu_97krdbic5nrdziy","ext":"pdf" }]', true);
foreach ($data as $rows) {
foreach ($rows as $column => $value) {
echo "{$column}: {$value}";
}
}
| |
doc_23533160
|
what I want to do is to check if the data of two columns exist in the other table .. if it does exist count it and at the final I want the number of records that have matching in the other table.
example :
table_1
column_1 value = "dog"
column_2 value = "apple"
table_2
column_1 value = "dog"
column_2 value = "orange"
so here the first column values exist in both table but the second column is different so I don't want to count it .. I want to count where both values exist in the same record .
ps: Both column_1 and column_2 aren't primary key
is there a solution for it using MySQL ? because I used java to solve this but take a long time for 5 million records .
A: Do an INNER JOIN on both tables:
SELECT COUNT(*)
FROM table_1 t1
INNER JOIN table_2 t2
ON t1.column_1 = t2.column_1
AND t1.column_2 = t2.column_2
A: If I'm understanding you correctly, one option is to use exists:
select *
from table1 t1
where exists (
select 1
from table2 t2
where t1.column1 = t2.column1 and
t1.column2 = t2.column2
)
This will return a list of rows from the first table that have a corresponding matching row in the second.
| |
doc_23533161
|
*
*Selects a file
*Selects what to do with the file (fopen modes: r, w, a, r+...)
*Writes to the file
this is my code so far:
//Gets future file content
printf("Write content:\n");
char content[100];
fgets(content, 100, stdin);
//Selects file
printf("Select output file: ");
char file[30];
fgets(file, 30, stdin);
//Selects mode
printf("Select mode: ");
char mode[3];
fgets(mode, 3, stdin);
FILE *fp;
fp = fopen(file, mode);
if (fp == 0) {
printf("File NOT opened\n");
}
I want the variable "file" to be used as the string/path to the file, and same goes for the "mode" variable.
When I run the program I get that the file is not opened, meaning that fp is a null pointer.
PS: It is not the whole code, but that's what's breaking it
Thanks in advance
A: Add this line
fprintf(stderr, "file='%s'\n", file);
after you read file and learn that a newline is read if the input was terminated by hitting Enter.
From man fgets() (italics by me):
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into
the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
As per Chris Dodd's comment below: The same applies to the string read into mode.
A: You need to check what the problem is with the filename and mode.
First of all, fgets() will store the newline into the buffer, which can prevent fopen() from doing what you expect.
Print out what you're trying to open:
printf("opening: '%s' with mode '%s'\n", file, mode);
Secondly, you should check the error code that fopen sets:
perror("File NOT Opened");
That way you will at least see what the error was opening the file.
| |
doc_23533162
|
use 5.012;
use utf8;
binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';
while (<>) {
chomp;
if ($_ =~ /BOLETIM DE ANÁLISE N/) {print "Boletim\n";}
if ($_ =~ /DADOS REFERENTES A AMOSTRA/) {print "Dados\n";}
}
The input file contains lines that should satisfy both the regexes, and I verified with TextWrangler that the file is indeed in UTF-8, with Unix endlines. However, the program recognizes only the second one, that do not contain accented characters.
What is weird (to me, at least) is that when I am in the debugger and run the same line
x if ($_ =~ /BOLETIM DE ANÁLISE N/) {print "Boletim\n";}
when $_ is the string 'BOLETIM DE ANÁLISE N° 274734/2011-0 ', the regex fires and "Boletim" is printed.
Why should the debugger and the program have different behaviours?
Many thanks in advance
Adriano
PS I am on Mac Os X 10.7.5 and Perl v5.12.4.
A: You aren't decoding your UTF-8 files properly.
The Unicode value for capital-A-acute is 193 or 0xC1. Your results with matching AN(.*)LISE show that you have a multi-byte representation for this character, starting with 195. The UTF-8 encoding for this character is C3 81 (or 195 129 in decimal) so you are looking at two one-byte characters instead of the single byte C1.
You can confirm this by writing
print join ' ', map sprintf('%02X', ord), split //, $1;
after the match operation. You will get C3 81.
You set STDIN and STDOUT to use the utf8 layer using binmode, but the <> operator reads from the ARGV file handle unless @ARGV is empty.
I suggest you write
binmode ARGV, ':utf8';
to also decode data read from ARGV. Then all should be well.
| |
doc_23533163
|
What is the difference between Node head=(Node)array[index] and Node head=(array[index],null).
How does Node head=(Node)array[b] work??
A: This is how you create an ArrayList in JAVA:
List<String> someList = new ArrayList<>();
Above exaple will create an ArrayList of String.
I found this line Node head=(Node)array[b];
This is just initializing the object of Node class with the value of an array named array of type Node at index b.
What is the difference between Node head=(Node)array[index] and
Node head=(array[index],null)
Node head=(array[index],null) this does not make any sense to me unless you are doing something like Node head=someFunction(array[index],null) where you are passing the value of array at index b and null as parameters and it is returning you an object of type Node.
A: the way to create Array list in java is
ArrayList name of list = ArrayList<>();
in the above example your going to create the Array list type NODe class
| |
doc_23533164
|
How do I resolve this in Bootstrap?
Demo: https://jsfiddle.net/oLderkuo/
<div class="container">
<div class="portfolio-gallery row">
<div class='gallery-item col-md-4 col-sm-6 col-xs-12'>
<span class='sub-gallery-icon'>
<a href='#' >
<img width="300" height="200" src="http://placehold.it/300x200" class="gallery-thumb-img wp-post-image" alt="" />
</a>
</span>
<span class='wp-caption-text gallery-caption'><br /> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. In semper arcu eget faucibus hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit.
</span>
</div>
<div class='gallery-item col-md-4 col-sm-6 col-xs-12'>
<span class='sub-gallery-icon'>
<a href='#' >
<img width="300" height="200" src="http://placehold.it/300x200" class="gallery-thumb-img wp-post-image" alt="" />
</a>
</span>
<span class='wp-caption-text gallery-caption'><br /> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</span>
</div>
<div class='gallery-item col-md-4 col-sm-6 col-xs-12'>
<span class='sub-gallery-icon'>
<a href='#' >
<img width="300" height="200" src="http://placehold.it/300x200" class="gallery-thumb-img wp-post-image" alt="" />
</a>
</span>
<span class='wp-caption-text gallery-caption'><br /> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit.
</span>
</div>
</div>
CSS:
/* Latest compiled and minified CSS included as External Resource*/
/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
body {
margin: 10px;
}
A: You need to wrap your text in <p> tag and set its width to img width
see the demo below:
/* Latest compiled and minified CSS included as External Resource*/
/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
body {
margin: 10px;
}
p {
width: 300px;
}
<div class="container">
<div class="portfolio-gallery row">
<div class='gallery-item col-md-4 col-sm-6 col-xs-12'>
<span class='sub-gallery-icon'>
<a href='#' >
<img width="300" height="200" src="http://placehold.it/300x200" class="gallery-thumb-img wp-post-image" alt="" />
</a>
</span>
<span class='wp-caption-text gallery-caption'><br />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. In semper arcu eget faucibus hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit.
</p></span>
</div>
<div class='gallery-item col-md-4 col-sm-6 col-xs-12'>
<span class='sub-gallery-icon'>
<a href='#' >
<img width="300" height="200" src="http://placehold.it/300x200" class="gallery-thumb-img wp-post-image" alt="" />
</a>
</span>
<span class='wp-caption-text gallery-caption'><br /> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p></span>
</div>
<div class='gallery-item col-md-4 col-sm-6 col-xs-12'>
<span class='sub-gallery-icon'>
<a href='#' >
<img width="300" height="200" src="http://placehold.it/300x200" class="gallery-thumb-img wp-post-image" alt="" />
</a>
</span>
<span class='wp-caption-text gallery-caption'><br /> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget leo leo. Sed sed pretium quam, ut bibendum libero. In semper arcu eget faucibus hendrerit.
</p></span>
</div>
</div>
A: Here is my code to get around this glitch.
You'll see I have 2 conditional statements below to cover large/medium size & small/x-small size.
<?php
/*
Template Name: Gallery
*/
?>
<?php get_header(); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="post" id="post-<?php the_ID(); ?>">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<div class="portfolio-gallery row">
<?php
$the_id = $post->ID;
$args = array(
'posts_per_page' => 50,
'offset' => 0,
'title_li' => '',
'post_parent' => $the_id,
'post_type' => 'page',
'order_by' => 'menu_order',
);
$pages = get_posts( $args );
$output = '';
$i = 0;
foreach($pages as $value){
$thumb = get_the_post_thumbnail( $value->ID, 'thumbnail', $attr = 'class=gallery-thumb-img' );
$tcopy = get_post_meta($value->ID, 'gallery_short_description', true);
$output .= "<div class='gallery-item col-xs-12 col-sm-6 col-md-4'><span class='sub-gallery-icon'>";
$output .= "<a href='" . $value->post_name . "' >" . $thumb . "</a></span>";
$output .= "<span class='wp-caption-text gallery-caption'><a href='" . $value->post_name . "' >" . $value->post_title . "</a><br />";
$output .= " " . $tcopy . "</span></div>";
if ($i == 2 || $i == 5 || $i == 8 || $i == 11) {
$output .= '<div class="clearfix visible-lg"></div><div class="clearfix visible-md"></div>';
}
if ($i == 1 || $i == 3 || $i == 7 || $i == 9 || $i == 11 || $i == 13) {
$output .= '<div class="clearfix visible-sm"></div><div class="clearfix visible-xs"></div>';
}
$i++;
}
echo $output;
?>
<?php echo do_shortcode('[gallery columns="0" size="thumbnail" link="file" itemtag="div" icontag="span" captiontag="span"]'); ?>
</div>
</div>
<br class="clear" />
<?php endwhile; endif; ?>
<?php get_footer(); ?>
| |
doc_23533165
|
I am currently using this code below which works fine in bringing in the current live image on page load:
exec('php -q /path/to/file/saveimage.php');
The problem I am having is getting the above code to run every 30 seconds. I've tried a few different attempts with ajax/jQuery but couldn't get them to work.
Seems like it should be pretty straight forward since all it needs to do is execute the .php, but I can't seem to figure it out.
A: As Tim said:
<script>
setInterval(function(){
$.get('/path/to/file/saveimage.php');
}, 30000);
</script>
| |
doc_23533166
|
I am thankful for any help, I've been staring at this for days. Here is the code.
The JS code.
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var name = document.getElementById('name');
var addr = document.getElementById('addr');
var phone = document.getElementById('phone');
var state = document.getElementById('state');
var username = document.getElementById('username');
var email = document.getElementById('email');
// Check each input in the order that it appears in the form!
if(isAlphabet(name, "Please enter only letters for your name")){
if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
if(isNumeric(phone, "Please enter only numeric values without any dashes")){
if(madeSelection(state, "Please Choose a State")){
if(lengthRestriction(username, 6, 8)){
if(emailValidator(email, "Please enter a valid email address")){
return true;
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg){
if(elem.value == "Select State..."){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
Here is the form code.
<?php
// Will not show if submitted once so client cant resubmit over and over again.
if ($submitted==2)
{
echo "<a href=\"../\"><h2>[ Return to main menu ]</h2></a>";
// sets variables to a Null string
$new_name='';
$new_phone='';
$new_email='';
$new_city='';
$new_state='';
$new_cost='';
$new_info ='';
}
else
{
echo "<div class=\"container\" >";
echo "<div class=\"form_container\" align=\"left\" >";
echo "<h2>Get Listed</h2>";
echo "<i>All required fields are marked with a red asteriks (<font color=\"red\"> * </font>)</i><br/><br/>";
echo "<form action=\"#\" onsubmit=\"return formValidator()\" method=\"post\" >";
echo "<font color=\"red\">*</font> <input type=\"checkbox\" name=\"terms\" value=\"yes\" >
Yes, I agree to our <a href=\"../legal/index.php\" target=\"_blank\" >
<i>Terms and Conditions</i></a><br/><br/>";
echo "<h2>Limo Service Details</h2>";
echo "<font color=\"red\"/>*</font> Service Name: <br/>";
echo "<input type=\"text\" name=\"in_name\" maxlength=\"60\" size=\"26\" id=\"name\" value='$new_name' >";
echo "<br/>";
echo "<font color=\"red\"/>*</font> Phone: <br/>";
echo "<input type=\"text\" name=\"in_phone\" maxlength=\"60\" size=\"26\" id=\"phone\" value='$new_phone' >";
echo "<br/>";
echo "<font color=\"red\"/>*</font> Email: <br/>";
echo "<input type=\"text\" name=\"in_email\" maxlength=\"60\" size=\"26\" id=\"email\" value='$new_email' >";
echo "<br/>";
echo "<font color=\"red\">*</font> Cost: <br/>";
echo "<input type=\"text\" name=\"in_cost\" maxlength=\"30\" size=\"11\" value='$new_cost' >";
echo " ";
echo "<select style=\"width: 120px\" name=\"in_rate\" >";
echo "<option value=\"daily\" selected>Daily</option>";
echo "<option value=\"hourly\">Hourly</option>";
echo "</select>";
echo "<br/>";
echo "<font color=\"red\">*</font> City: <select name=\"in_city\" style=\"width: 245px\" >";
echo "<option value=\"\">Select City...</option>";
echo "<option value=\"Atlanta\">Atlanta</option>";
echo "<option value=\"Atlantic City\">Atlantic City</option>";
echo "<option value=\"Austin\">Austin</option>";
echo "<option value=\"Baltimore\">Baltimore</option>";
echo "<option value=\"Boston\">Boston</option>";
echo "<option value=\"Charlotte\">Charlotte</option>";
echo "<option value=\"Chicago\">Chicago</option>";
echo "<option value=\"Cincinnati\">Cincinnati</option>";
echo "<option value=\"Columbus\">Columbus</option>";
echo "<option value=\"Dallas\">Dallas</option>";
echo "<option value=\"Denver\">Denver</option>";
echo "<option value=\"Detroit\">Detroit</option>";
echo "<option value=\"Fort Lauderdale\">Fort Lauderdale</option>";
echo "<option value=\"Honolulu\">Honolulu</option>";
echo "<option value=\"Houston\">Houston</option>";
echo "<option value=\"Indianapolis\">Indianapolis</option>";
echo "<option value=\"Irvine\">Irvine</option>";
echo "<option value=\"Las Vegas\">Las Vegas</option>";
echo "<option value=\"Los Angeles\">Los Angeles</option>";
echo "<option value=\"Miami\">Miami</option>";
echo "<option value=\"Minneapolis\">Minneapolis</option>";
echo "<option value=\"Nashville\">Nashville</option>";
echo "<option value=\"Newark\">Newark</option>";
echo "<option value=\"New York\">New York</option>";
echo "<option value=\"Oklahoma\">Oklahoma City</option>";
echo "<option value=\"Orlando\">Orlando</option>";
echo "<option value=\"Portland\">Portland</option>";
echo "<option value=\"Philadelphia\">Philadelphia</option>";
echo "<option value=\"Phoenix\">Phoenix</option>";
echo "<option value=\"Raleigh\">Raleigh</option>";
echo "<option value=\"Sacramento\">Sacramento</option>";
echo "<option value=\"Salt Lake City\">Salt Lake City</option>";
echo "<option value=\"San Antonio\">San Antonio</option>";
echo "<option value=\"San Diego\">San Diego</option>";
echo "<option value=\"San Francisco\">San Francisco</option>";
echo "<option value=\"Tampa\">Tampa</option>";
echo "</select>";
echo "<br/>";
// City2
echo " City 2: <select name=\"in_city2\" style=\"width: 245px\" >";
echo "<option value=\"\">Select City...</option>";
echo "<option value=\"Atlanta\">Atlanta</option>";
echo "<option value=\"Atlantic City\">Atlantic City</option>";
echo "<option value=\"Austin\">Austin</option>";
echo "<option value=\"Baltimore\">Baltimore</option>";
echo "<option value=\"Boston\">Boston</option>";
echo "<option value=\"Charlotte\">Charlotte</option>";
echo "<option value=\"Chicago\">Chicago</option>";
echo "<option value=\"Cincinnati\">Cincinnati</option>";
echo "<option value=\"Columbus\">Columbus</option>";
echo "<option value=\"Dallas\">Dallas</option>";
echo "<option value=\"Denver\">Denver</option>";
echo "<option value=\"Detroit\">Detroit</option>";
echo "<option value=\"Fort Lauderdale\">Fort Lauderdale</option>";
echo "<option value=\"Honolulu\">Honolulu</option>";
echo "<option value=\"Houston\">Houston</option>";
echo "<option value=\"Indianapolis\">Indianapolis</option>";
echo "<option value=\"Irvine\">Irvine</option>";
echo "<option value=\"Las Vegas\">Las Vegas</option>";
echo "<option value=\"Los Angeles\">Los Angeles</option>";
echo "<option value=\"Miami\">Miami</option>";
echo "<option value=\"Minneapolis\">Minneapolis</option>";
echo "<option value=\"Nashville\">Nashville</option>";
echo "<option value=\"Newark\">Newark</option>";
echo "<option value=\"New York\">New York</option>";
echo "<option value=\"Oklahoma\">Oklahoma City</option>";
echo "<option value=\"Orlando\">Orlando</option>";
echo "<option value=\"Portland\">Portland</option>";
echo "<option value=\"Philadelphia\">Philadelphia</option>";
echo "<option value=\"Phoenix\">Phoenix</option>";
echo "<option value=\"Raleigh\">Raleigh</option>";
echo "<option value=\"Sacramento\">Sacramento</option>";
echo "<option value=\"Salt Lake City\">Salt Lake City</option>";
echo "<option value=\"San Antonio\">San Antonio</option>";
echo "<option value=\"San Diego\">San Diego</option>";
echo "<option value=\"San Francisco\">San Francisco</option>";
echo "<option value=\"Tampa\">Tampa</option>";
echo "</select>";
echo "<br/>";
// City3
echo " City 3: <select name=\"in_city3\" style=\"width: 245px\" >";
echo "<option value=\"\">Select City...</option>";
echo "<option value=\"Atlanta\">Atlanta</option>";
echo "<option value=\"Atlantic City\">Atlantic City</option>";
echo "<option value=\"Austin\">Austin</option>";
echo "<option value=\"Baltimore\">Baltimore</option>";
echo "<option value=\"Boston\">Boston</option>";
echo "<option value=\"Charlotte\">Charlotte</option>";
echo "<option value=\"Chicago\">Chicago</option>";
echo "<option value=\"Cincinnati\">Cincinnati</option>";
echo "<option value=\"Columbus\">Columbus</option>";
echo "<option value=\"Dallas\">Dallas</option>";
echo "<option value=\"Denver\">Denver</option>";
echo "<option value=\"Detroit\">Detroit</option>";
echo "<option value=\"Fort Lauderdale\">Fort Lauderdale</option>";
echo "<option value=\"Honolulu\">Honolulu</option>";
echo "<option value=\"Houston\">Houston</option>";
echo "<option value=\"Indianapolis\">Indianapolis</option>";
echo "<option value=\"Irvine\">Irvine</option>";
echo "<option value=\"Las Vegas\">Las Vegas</option>";
echo "<option value=\"Los Angeles\">Los Angeles</option>";
echo "<option value=\"Miami\">Miami</option>";
echo "<option value=\"Minneapolis\">Minneapolis</option>";
echo "<option value=\"Nashville\">Nashville</option>";
echo "<option value=\"Newark\">Newark</option>";
echo "<option value=\"New York\">New York</option>";
echo "<option value=\"Oklahoma\">Oklahoma City</option>";
echo "<option value=\"Orlando\">Orlando</option>";
echo "<option value=\"Portland\">Portland</option>";
echo "<option value=\"Philadelphia\">Philadelphia</option>";
echo "<option value=\"Phoenix\">Phoenix</option>";
echo "<option value=\"Raleigh\">Raleigh</option>";
echo "<option value=\"Sacramento\">Sacramento</option>";
echo "<option value=\"Salt Lake City\">Salt Lake City</option>";
echo "<option value=\"San Antonio\">San Antonio</option>";
echo "<option value=\"San Diego\">San Diego</option>";
echo "<option value=\"San Francisco\">San Francisco</option>";
echo "<option value=\"Tampa\">Tampa</option>";
echo "</select>";
echo "<br/>";
// State
echo "<font color=\"red\">*</font> State: <select name=\"in_state\" id=\"state\" style=\"width: 245px\" >";
echo "<option>Select State...</option>";
echo "<option value=\"Alabama\">Alabama</option>";
echo "<option value=\"Alaska\">Alaska</option>";
echo "<option value=\"Arizona\">Arizona</option>";
echo "<option value=\"Arkansas\">Arkansas</option>";
echo "<option value=\"California\">California</option>";
echo "<option value=\"Colorado\">Colorado</option>";
echo "<option value=\"Connecticut\">Connecticut</option>";
echo "<option value=\"Delaware\">Delaware</option>";
echo "<option value=\"Florida\">Florida</option>";
echo "<option value=\"Georgia\">Georgia</option>";
echo "<option value=\"Hawaii\">Hawaii</option>";
echo "<option value=\"Idaho\">Idaho</option>";
echo "<option value=\"Illinois\">Illinois</option>";
echo "<option value=\"Indiana\">Indiana</option>";
echo "<option value=\"Iowa\">Iowa</option>";
echo "<option value=\"Kansas\">Kansas</option>";
echo "<option value=\"Kentucky\">Kentucky</option>";
echo "<option value=\"Louisiana\">Louisiana</option>";
echo "<option value=\"Maine\">Maine</option>";
echo "<option value=\"Maryland\">Maryland</option>";
echo "<option value=\"Massachusetts\">Massachusetts</option>";
echo "<option value=\"Michigan\">Michigan</option>";
echo "<option value=\"Minnesota\">Minnesota</option>";
echo "<option value=\"Mississippi\">Mississippi</option>";
echo "<option value=\"Missouri\">Missouri</option>";
echo "<option value=\"Montana\">Montana</option>";
echo "<option value=\"Nebraska\">Nebraska</option>";
echo "<option value=\"Nevada\">Nevada</option>";
echo "<option value=\"New Hampshire\">New Hampshire</option>";
echo "<option value=\"New Jersey\">New Jersey</option>";
echo "<option value=\"New Mexico\">New Mexico</option>";
echo "<option value=\"New York\">New York</option>";
echo "<option value=\"North Carolina\">North Carolina</option>";
echo "<option value=\"North Dakota\">North Dakota</option>";
echo "<option value=\"Ohio\">Ohio</option>";
echo "<option value=\"Oklahoma\">Oklahoma</option>";
echo "<option value=\"Oregon\">Oregon</option>";
echo "<option value=\"Pennsylvania\">Pennsylvania</option>";
echo "<option value=\"Rhode Island\">Rhode Island</option>";
echo "<option value=\"South Carolina\">South Carolina</option>";
echo "<option value=\"South Dakota\">South Dakota</option>";
echo "<option value=\"Tennessee\">Tennessee</option>";
echo "<option value=\"Texas\">Texas</option>";
echo "<option value=\"Utah\">Utah</option>";
echo "<option value=\"Vermont\">Vermont</option>";
echo "<option value=\"Virginia\">Virginia</option>";
echo "<option value=\"Washington\">Washington</option>";
echo "<option value=\"West Virginia\">West Virginia</option>";
echo "<option value=\"Wisconsin\">Wisconsin</option>";
echo "<option value=\"Wyoming\">Wyoming</option>";
echo "</select>";
echo "<br/><br/>";
//Additional Info
echo " Additional Info: ";
echo "<br/>";
echo "<textarea rows=\"5\" cols=\"26\" name=\"in_info\" >$new_info";
echo "</textarea>";
echo "<font size=\"1\"> (Maximum characters: 500)</font>";
echo "<br/>";
//Submit Button
echo "<input type=\"hidden\" name=\"submission\" value=\"1\">";
echo "<center><input type=\"submit\" value=\"LIST ME\" class=\"button2\" /></center>";
echo "</form>";
echo "</div>";
echo "</div>";
}
?>
Once validated it gets sent to a php mysql file that inputs it into my database. Thanks again for any help.
~Nikoli
A: Your code is not doing what you think it is.
var name = document.getElementById('name');
returns:
<input type="text" name="in_name" maxlength="60" size="26" id="name" value='$new_name' >
Instead, to get the value, you want to do:
var name = document.getElementById('name').value;
That should solve your current problem.
On another note, you should probably look into closing that php tag instead of wrapping everything in echo statements. Using CSS for your styles will save you a lot of headache in the future as well.
| |
doc_23533167
|
How to encode such strings Ã…land Islands?
UPDATE
HashMap params = new HashMap();
params.put(Constants.FULL_NAME, this.etFullname.getText().toString());
params.put(Constants.FATHER_NAME, this.etFathername.getText().toString());
params.put(Constants.CNIC, this.etNic.getText().toString());
params.put(Constants.PASSPORT, this.etPassport.getText().toString());
String name = "Ã…land Islands";
params.put(Constants.COUNTRY, name);
and Then used the StringReqeust
A: You can use URLEncoder.encode(String, String) to encode your parameters1. Something like,
String encoding = "UTF-16LE";
Map<String, String> params = new HashMap<>();
params.put(Constants.FULL_NAME, URLEncoder.encode(
this.etFullname.getText().toString(), encoding));
params.put(Constants.FATHER_NAME, URLEncoder.encode(
this.etFathername.getText().toString(), encoding));
params.put(Constants.CNIC,
URLEncoder.encode(this.etNic.getText().toString(), encoding));
params.put(Constants.PASSPORT, URLEncoder.encode(
this.etPassport.getText().toString(), encoding));
String name = "Ã…land Islands";
params.put(Constants.COUNTRY, URLEncoder.encode(name, encoding));
1Also, you should program to the Map interface and please don't use raw types.
| |
doc_23533168
|
This is my code:
Class PatientView:
public void readInRange(PatientModel pm, Integer a, Integer b) {
try {
String str;
BufferedReader bufferedReader = new BufferedReader(new FileReader("test.txt"));
for (int i = a; i < b+1; i++) {
while ((str = bufferedReader.readLine()) != null) {
System.out.println(str);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Class PatientModel and his getter methods and write to file method:
public Integer getId() {
return Id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getPatronymic() {
return patronymic;
}
public String getAddress() {
return Address;
}
public Integer getNumberPhone() {
return numberPhone;
}
public Integer getMedicalCard() {
return medicalCard;
}
public String getDiagnose() {
return diagnose;
}
private void writeToFile() {
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("test.txt", true))) {
bufferedWriter.write(String.format("%1d, %10s, %10s, %10s, %10s, %10d, %10d, %10s", Id, firstName,
lastName, patronymic, Address, numberPhone, medicalCard, diagnose));
bufferedWriter.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
A: Thanks everybody who tried to help me. This is how I solved this problem
My code:
public void readInRange(PatientModel pm, Integer low, Integer high) {
String[] splitdata;
String sixcol; Integer num=0;
try {
String str;
BufferedReader bufferedReader = new BufferedReader(new FileReader("test.txt"));
while ((str = bufferedReader.readLine()) != null) {
splitdata = str.split("[,\t]");
sixcol = splitdata[0];
Integer aa = num.valueOf(sixcol);
if(aa > low && aa < high) {
System.out.println(str);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
| |
doc_23533169
|
The descriptions are varying length, the field max size is 30 characters and I need to physically remove the full-stop rather than using a select statement to trim the full-stop.
I tried;
UPDATE PDPRODP SET PRDESC = PRDESC-1 where PRSTYLE = 1234
But I got this error:
Character in CAST argument not valid.
I also tried this following some googling;
UPDATE PDPRODP SET PRDESC=LEFT(PRDESC, LEN(PRDESC)-1)
WHERE PRCOMP = 1 AND PRSTYL = 31285
But got this error:
LEN in *LIBL type *N not found.
A: Use LENGTH
UPDATE PDPRODP SET PRDESC=LEFT(PRDESC, LENGTH(PRDESC)-1)
WHERE PRCOMP = 1 AND PRSTYL = 31285
A: The REPLACE() function can search for all occurrences of some string, and substitute another in its place. You might search for your full-stop, and replace it with a zero-length string ''. This would be handy in cases where your search string may not always be at the end.
| |
doc_23533170
|
public virtual string Name
{
get
{
return _name;
}
set
{
_name = value; // breakpoint here
}
}
The first time execution reaches the breakpoint, VS displays an error:
EDIT - for searchability, the message is this:
The following breakpoint cannot be set:
At (file).cs, line 137 character 17 ('(class).Name', line 12), when 'value == "Status"' is true
The function evaluation requires all threads to run.
Here's what the Threads window looks like:
Anyone seen this before, or have any ideas what might be causing the debugger to baulk at this seemingly-simple case? Might it have something to do with the sleeping thread?
A: I once had this problem when I encountered a situation when it goes out of the execution of the base thread. A bit more information on the flow of your application will help. It seems to me like a race condition.
A: I eventually devised a workaround:
public virtual string Name
{
get
{
return _name;
}
set
{
if (value == "Status")
DoSomeNoOp(); // Breakpoint here, or Debug.Fail() inside your no-op
_name = value;
}
}
A: I don't think it knows what value is. Try to put the breakpoint on the closing } and use _name in the condition.
| |
doc_23533171
|
If I download it and create a new "Installed JRE" entry, it detects the libs but when I go to Execution Environments it does not show the JRE. Has somebody had this issue? How to fix this?
I'm using Eclipse Version: 2020-12 (4.18.0) Build id: 20201210-1552 on Windows 10 x64.
A: try it with eclipse Oxygen builds.
jdk8 isn't very compatible with IDEs developed for java9+
| |
doc_23533172
|
DF1
App
Proc
Rej
Old
2021-05-11
2021-05-11
NA
NA
2021-05-11
2021-05-11
NA
NA
2021-05-11
NA
NA
NA
2021-05-11
2021-05-11
NA
NA
2021-05-12
2021-05-12
NA
2021-09-12
2021-05-12
2021-05-12
2021-10-01
NA
2021-05-13
2021-05-13
NA
2021-09-12
2021-05-13
2021-05-13
2021-10-01
NA
2021-05-13
2021-05-13
2021-10-01
NA
2021-05-13
NA
NA
NA
2021-05-13
2021-05-13
NA
2021-09-12
2021-05-13
NA
NA
NA
2021-05-13
2021-05-13
NA
NA
What I want: A new table with count of App and New by Dates. Ignoring Old and Rej
DFdesired:
Date
App
Proc
2021-05-11
4
3
2021-05-12
2
2
2021-05-13
7
5
A: Try this
library(dplyr , warn.conflicts = F)
DF1 |> group_by(App) |> summarise(app = n()) -> df2
DF1 |> group_by(Proc) |> summarise(proc =n()) -> df3
df2 |> left_join(df3 , by = c("App" = "Proc")) -> DFdesired
Output
DFdesired
# A tibble: 3 × 3
App app proc
<chr> <int> <int>
1 2021-05-11 4 3
2 2021-05-12 2 2
3 2021-05-13 7 5
A: Here is another approach using pivot_longer and pivot_wider from tidyr. You can select the App and Proc columns for pivoting, and remove rows where NA is the value.
library(tidyverse)
df1 %>%
pivot_longer(cols = c(App, Proc), values_drop_na = T) %>%
count(value, name) %>%
pivot_wider(id_cols = value, names_from = name, values_from = n)
Output
value App Proc
<chr> <int> <int>
1 2021-05-11 4 3
2 2021-05-12 2 2
3 2021-05-13 7 5
| |
doc_23533173
|
ERROR: duplicate key value violates unique constraint "pk_jhi_persistent_audit_event"
Full log:
2017-12-19T02:44:25.564551+00:00 app[web.1]: 2017-12-19 02:44:25.564 WARN 4 --- [ XNIO-2 task-26] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23505
2017-12-19T02:44:25.564734+00:00 app[web.1]: 2017-12-19 02:44:25.564 ERROR 4 --- [ XNIO-2 task-26] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: duplicate key value violates unique constraint "pk_jhi_persistent_audit_event"
2017-12-19T02:44:25.564737+00:00 app[web.1]: Detail: Key (event_id)=(42094) already exists.
2017-12-19T02:44:25.565215+00:00 app[web.1]: 2017-12-19 02:44:25.565 ERROR 4 --- [ XNIO-2 task-26] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2017-12-19T02:44:25.567741+00:00 app[web.1]: 2017-12-19 02:44:25.567 ERROR 4 --- [ XNIO-2 task-26] o.j.h.w.rest.errors.ExceptionTranslator : An unexpected error occurred: could not execute statement; SQL [n/a]; constraint [pk_jhi_persistent_audit_event]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
2017-12-19T02:44:27.820781+00:00 heroku[web.1]: Process running mem=523M(102.1%)
2017-12-19T02:44:27.820897+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2017-12-19T02:44:25.571359+00:00 heroku[router]: at=info method=POST path="/api/authenticate" host=www.21-points.com request_id=b54f7527-7479-42ee-acaa-d6794567c118 fwd="75.171.150.21" dyno=web.1 connect=0ms service=156ms status=500 bytes=550 protocol=https
Is it possible to reset the sequences for these tables, or move to a guid-based system that won't have collisions? I'm using PostgreSQL on Heroku.
A: The workaround I adopted was to set a rollbackFor=Exception.class in my CustomAuditEventRepository
It catch the exception and just rollback the transaction: so the login audit event will not be saved, but at least you are not going to have annoying exceptions that lock the app.
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor=Exception.class)
public void add(AuditEvent event) {
if (!AUTHORIZATION_FAILURE.equals(event.getType()) &&
!Constants.ANONYMOUS_USER.equals(event.getPrincipal())) {
PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
persistentAuditEvent.setPrincipal(event.getPrincipal());
persistentAuditEvent.setAuditEventType(event.getType());
persistentAuditEvent.setAuditEventDate(event.getTimestamp());
Map<String, String> eventData = auditEventConverter.convertDataToStrings(event.getData());
persistentAuditEvent.setData(truncate(eventData));
persistenceAuditEventRepository.save(persistentAuditEvent);
}
}
A: I experienced the same problem also with a 5.8.2 Jhipster microservice application (gateway + microservice) based on Postgres db. Especially after rebuilding the ms, I got the notorious:
ERROR: duplicate key value violates unique constraint "pk_jhi_persistent_audit_event"
I have observed that, when it happened, there was an overlapping of keys for hibernate_sequence as its next value retrieved with pgAdmin was different by the key that the application was trying to write in the audit table (curiously there was a difference of 50 or less...). I don't know in which way Hibernate deals with sequenceGenerator but this post gives me some tips (the fourth answer):
Liquibase + Postgresql + Spring Jpa : Id auto increment issue
I have not in my Postgres db a serial datatype for the id column, but indeed the behaviour is similar - Hibernate seems to send key values taken from some cache that survive also after a rebuilding. So I give up with Hibernate sequence and I created a new ordinary postgres sequence:
CREATE SEQUENCE public.id_persistent_audit_event_seq
AS bigint
MINVALUE 1 NO MAXVALUE
START WITH 1
CACHE 50;
On Java side (PersistentAuditEvent.java):
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "audit_event_generator")
@SequenceGenerator(name = "audit_event_generator", sequenceName="id_persistent_audit_event_seq", allocationSize=1)
@Column(name = "event_id")
private Long id;
Note the allocationSize=1 but CACHE 50 in Postgres. This should avoid performance issues on database side (look at jdubois' comment of 14 Sep 2018 in https://github.com/jhipster/generator-jhipster/issues/8029).
Hope it helps, now everything is working well for me!
| |
doc_23533174
|
class BaseType {
}
class MainType extends BaseType {
}
class ItemFactory {
items: { [type: string]: BaseType } = {};
get<T extends BaseType>(type: string): T | null {
let item = this.items[type];
if (!item) {
switch (type) {
case "main-type":
item = new MainType();
break;
default:
return null;
}
this.items[type] = item;
}
return item as T;
}
}
Is there a way to simplify call
itemFactory.get<MainType>("main-type"); // current call
// option 1
const resolvedType = itemFactory.get<MainType>();
// option 2
const resolvedType = itemFactory.get("main-type");
I would like to have either option 1 or option 2 (no need for both), so I don't have to pass both identifier and type to have correctly resolved resulting type.
A: You'll need to give the compiler some kind of mapping between names passed to itemFactory.get() and the expected output type. Mapping from names to types is what interfaces do best, so you can define one like this:
interface NameMap {
"main-type": MainType;
// other name-type mappings here
}
And then you change your get() method to this:
get<K extends keyof NameMap>(type: K): NameMap[K] | null {
let item = this.items[type];
if (!item) {
switch (type) {
case "main-type":
item = new MainType();
break;
default:
return null;
}
this.items[type] = item;
}
return item as NameMap[K];
}
You replace T extends BaseType to NameMap[K] where K extends keyof NameMap. Now the following ("option 2") will work:
const resolvedType = itemFactory.get("main-type"); // MainType | null
Note that you will never get "option 1" to work. TypeScript's type system gets erased when the JS is emitted, so this:
itemFactory.get<MainType>();
will become this at runtime:
itemFactory.get();
And there's no way for that to know what to return, since the relevant information has been left behind before the code started running. This is intentional; it is not a goal of TypeScript to "add or rely on run-time type information in programs, or emit different code based on the results of the type system." Instead, TypeScript should "encourage programming patterns that do not require run-time metadata"... in this case it means using a runtime value like the string "main-type" instead of a design-time type like MainType to keep track of what get() should do.
Okay, hope that helps. Good luck!
Link to code
| |
doc_23533175
|
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/toolbar_ll"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_myjeenees"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="@android:color/white"
android:minHeight="?attr/actionBarSize">
<TextView
android:id="@+id/toolbarShuffle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Shuffle Money"
android:textColor="@color/black"
android:textSize="18sp" />
</android.support.v7.widget.Toolbar>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="UserName"
android:textSize="25sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="May 15,Birthday" />
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="10dp"
android:background="@mipmap/ic_forward" />
</LinearLayout>
<com.android.jeenees.utils.CustomScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fillViewport="true"
>
<android.support.v4.view.ViewPager
android:id="@+id/shufflePager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white" />
</com.android.jeenees.utils.CustomScrollView>
<!--</LinearLayout>-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@color/colorPrimary"
android:padding="10dp"
android:src="@mipmap/ic_action_tick" />
<ImageButton
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@color/colorPrimary"
android:padding="10dp"
android:src="@mipmap/ic_back" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="10dp"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/firstwish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IPhone 5s" />
<View
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="@+id/costfirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rs 5300/32777" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<SeekBar
android:id="@+id/seekfirst"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:maxHeight="10dp"
android:progress="50"
android:progressDrawable="@drawable/progress_draw"
android:splitTrack="false"
android:thumb="@mipmap/ic_thumb"></SeekBar>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/secondwish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IPhone 5s" />
<View
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="@+id/costsecond"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rs 5300/32777" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<SeekBar
android:id="@+id/seeksecond"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:maxHeight="10dp"
android:progress="50"
android:progressDrawable="@drawable/progress_draw"
android:splitTrack="false"
android:thumb="@mipmap/ic_thumb"></SeekBar>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/thirdwish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IPhone 5s" />
<View
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="@+id/costthird"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rs 5300/32777" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<SeekBar
android:id="@+id/seekthird"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:maxHeight="10dp"
android:progress="50"
android:progressDrawable="@drawable/progress_draw_red"
android:splitTrack="false"
android:thumb="@mipmap/ic_red_thumb"></SeekBar>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="Rs 1700"
android:textSize="25sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="Released Money"
android:textSize="25sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:drawableLeft="@mipmap/ic_actin_add"
android:gravity="center"
android:padding="15dp"
android:text="Top Up"
android:textColor="@android:color/white" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
A: Each view take parent event first if your view pager is swipe horizonatly for change the page tab than you can not use horizonatl scroll in child fragment . It is not write practice you can arrange your page content as vertical and use vertical scroll view.
Or second option you will have to disable swipe event for view pager and only tab click is uesd to change page than you can use horizontal scroll view.
| |
doc_23533176
|
loadMap() {
const maps = this.props.google.maps;
const mapRef = this.refs.map; <---- ref set in render function on dom node
const node = ReactDOM.findDOMNode(mapRef); <--- the dom node
...
this.map = new maps.Map(node, mapConfig);
this.mapRef = mapRef;
}
It's pretty easy because mapref is set in the render method:
render() {
return (
<div style={{ height: mapHeight }} ref="map">
...
And then that is used to set node and then that is used to new up the map.
How would I do this with a map's marker? A marker doesn't need a dom node to be created and therefore I cant get a ref to the marker.
this.marker = new google.maps.Marker({someOptions}); <----- no dom node needed
I want to do this because I need to dynamically change the icon of the marker based on some value in my redux store. I have tried changing the icon via props (see below), but it somehow prevents the icon marker from being draggable even though draggable is set to true.
return (
<Marker
key={foo}
position={latLngPos}
icon={ active ? activeIcon : defaultIcon }
draggable={true}
onDragstart={() => { return this.handleMapMarkerDragStart();}}
onDragend={() => { return this.handleMapMarkerDrop();}}
/>);
I suspect things are acting strangely because to get google's maps api to work with react, the components have to deal with the actual dom nodes instead of the virtual dom nodes.
Any insight into this would be much appreciated.
A: Regarding
I want to do this because I need to dynamically change the icon of the
marker based on some value in my redux store. I have tried changing
the icon via props (see below), but it somehow prevents the icon
marker from being draggable even though draggable is set to true.
the following example demonstrates how to:
*
*set marker as draggable
*set custom icon per marker
Example
const handleDragEnd = (props, marker, event) => {
console.log(event.latLng);
};
const defaultIcon =
"http://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png";
const activeIcon =
"http://maps.google.com/mapfiles/kml/pushpin/pink-pushpin.png";
const MapWrapper = props => {
return (
<div className="map-container">
<Map
google={props.google}
className={"map"}
zoom={4}
initialCenter={{ lat: -24.9923319, lng: 135.2252427 }}
>
{props.places.map((place, i) => {
const active = i % 2 === 0;
return (
<Marker
icon={active ? activeIcon : defaultIcon}
key={place.id}
position={{ lat: place.lat, lng: place.lng }}
draggable={true}
onDragend={handleDragEnd}
/>
);
})}
</Map>
</div>
);
};
Note: Marker component does not support onDragstart event
listener at the moment in google-maps-react library, but it could be
attached directly to Google Maps Marker object
Demo
| |
doc_23533177
|
if ([self respondsToSelector:@selector(method:)]) {
}
Is there a similar test for enums? If not, how can I test for it?
A: I don't think that you can directly check for an enum availability, but you don't actually need it.
Simply check for one selector availability that you know is available on the same iOS version that you know has got the enum you need. In other words, check for some selector that was added to iOS at the same time as the enum.
It is not actually the same, but I think it does reasonably what you need. If the selector you check for does use that enum, you are pretty close to the perfect solution.
A: There is no method to check for the availability of the enum at the runtime. Best method would be to check for iOS version or check for the feature that you would want to enable or provide depending on the iOS version. If you can tell us the feature, I'm sure someone out here will surely be able to help you out.
| |
doc_23533178
|
Some sources refer to this as "ANSI-C Quoting", but is there a nicer name for it (and is "ANSI-C Quoted String" the proper name for these strings)?
| |
doc_23533179
|
TLang works, but I get weird strings in an empty project. (e.g. Samsung Galaxy Nexus and other mobile stuff) And I prefer another solution and not string-replace like TLang.
Unfortunately, resourcestring doesn't work. I tried to translate the resourcestrings with "resource dll expert" (IDE RAD Studio XE5). And the example application "RichEdit" also doesn't work.
Any idea?
A: Okay I found the problem, why it isn't running. The tool have some bugs. The path to the Project.exe can not contain spaces.
Another solution is Stringtable like this:
// default.rc file
#define firstString 1
#define secondString 2
STRINGTABLE
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
BEGIN
firstString , "Neutral String 1"
secondString , "Neutral String 2"
END
// english.rc file
#define firstString 1
#define secondString 2
STRINGTABLE
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
BEGIN
firstString , "First String"
secondString , "Second String"
END
And than {$R default.res default.rc} {$R english.res english.rc} into the *.pas file. To use the transalation: LoadStr(2)
With an resource-editor, I can see the two languages. But how I can change the default/neutral to another language at runtime. Is there a kind of "SetLanguage" function in Delphi?
A: For simple projects TLang works fine, but the included "Language Designer" (doubleclick on the TLang component) is not much fun.If you want to translate and handle your strings extern you only can import external languages files one by one and have to import all again, if some texts change.
I wrote a small tool to handle texts extern in a spreadsheet and convert this texts to the LNG format:
See TLang converter
For large projects you may also check out some commercial products for translating/localization of Delphi FMX projects like:
http://www.sisulizer.de
http://www.tsilang.com
http://www.regulace.org
| |
doc_23533180
|
I have a stored procedure that inserts 5 rows for each user.
Each user can have multiple concurrent call, first call from specific UserID inserts a set of values and other call just read the values for that UserID. This doesn't work by checking
if exists(Select 1 from Meta_cache Where UserID = @UserID)
when there is multiple concurrent calls.
I want to specific locking mechanism that locks conditionally on rows for specific UserID and another User Don't get affected by locking.
I just refers some script from
http://weblogs.sqlteam.com/dang/archive/2007/10/28/Conditional-INSERTUPDATE-Race-Condition.aspx
A: row locking can always lead to page lock and table lock
UPDATE
Employee WITH (ROWLOCK)
SET FullName='John Does'
WHERE Department = 'IT'
http://www.techrepublic.com/article/control-sql-server-locking-with-hints/
you can always avoid race condition by encapsulating your queries in a SQL Transaction.
| |
doc_23533181
|
1 post = app return nothing
2 post = app return data from previous post
var http = require('http');
var util = require('util');
var tenitem = [];
var dataa;
http.createServer(function (req, res) {
if (req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*' });
res.end('Hello World\n');
}
if (req.method === 'POST') {
var body = ''
console.log("POST");
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
console.log(body)
dataa = body;
http.get('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=' + dataa, function (api) {
var bod = '';
api.on('data', function (chunk) {
bod += chunk;
});
api.on('end', function () {
console.log(bod)
tenitem = JSON.parse(bod);
})
})
});
res.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' });
res.end(tenitem.lowest_price)
}
}).listen(port, hostname, function () {
console.log('Server running');
});
A: tenitem is initialized inside an inner function and you're trying to send it back. Just move res.end() in that function:
api.on('end', function () {
console.log(bod)
tenitem = JSON.parse(bod);
res.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' });
res.end(tenitem.lowest_price)
})
| |
doc_23533182
|
A: You should run your code in a loop and catch any exceptions inside your loop. e.g.
while (true) {
try {
//Do what ever your server does
} catch (Exception e) {
//Log your exception to a log file
}
}
| |
doc_23533183
|
What I'm currently attempting to do is go in the other direction, I'm trying to send a string of information (for example "1,2,3,45,18") from my Javascript code to MySQL to be set as a session parameter (call it @sparam). What is the process behind passing this value to MySQL?
Would I be able to access a MySQL variable through PHP in the same way I can access tables (for the purpose of getting a value back into Javascript)?
I'd appreciate any insight.
Thanks.
EDIT
Maybe I was unclear in my original post. What I'm asking is how would I be able to pass a string to a MySQL session variable, specifically a set of IDs directly related to the IDs in the table of the MySQL database, and then be able to work with these IDs by calling the necessary procedures in MySQL. In turn, the procedures called in MySQL would generate some output, which would then have to be passed back to the Javascript code.
A: I created a special JSON (JavaScript Object Notation) php pages that I would call from javascript. Then I would parse those JSON responses.
Simple example:
JAVASCRIPT:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "page_json.php?action=getsession",
type : "GET",
success : function(data) {
//Get Json and loop over it's data
if (data.length>10){
var jsonData = JSON.parse(data);
$.each(jsonData, function(Idx, Value) {
if (Idx>0){
//get values for each vehicle and then remove it's marker from the map and then add new marker on the map (thereofore update the marker)
c_latitude = Value["lat"];
c_longitude = Value["lon"];
c_name = Value["name"];
c_notes= Value["notes"];
removeMarker(c_name); //remove old marker function
addMarker(c_latitude, c_longitude, c_name); //add current marker function
}
});
}
}
});
});
}
PHP: Here I loop over my arrayList and then create a simple array with values. Then I just output it as a json string
foreach ($listOfCars->arrayList as $key => $value) {
$unit = new fleetUnit();
$unit = $value;
//create array for json output
$data[] = array('lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes);
}
echo json_encode($data);
| |
doc_23533184
|
<body>
<div id="main-panel">
// load content dynamically
</div>
<script src="myscripts.js"></script>
</body>
problem is, when the content arrives, it seems like it is not aware that
there are functionalities inside myscripts..
so my work around is to reload again myscripts.js, and then all works fine.
jQuery.getScript('myscripts.js');
but the downside is, myscripts.js will be loaded multiple times.. how can i make ajax result content to be aware of my host page's script?
Thank you in advance.
A: Put your script before load content.
<script src="myscripts.js"></script>
<body>
<div id="main-panel">
// load content dynamically
</div>
</body>
| |
doc_23533185
|
For uploading image using the text editor, i'm trying to post the file on uploadCallback function to S3 and return the url for the uploaded item to the editor.
But I don't know how to handle unused image (deleted before submit) that
s just hanging around in my S3 bucket. Is there any good method to prevent this? I was trying to just post the image in base64 format but that seems just way to much and waste of memory.
A: There are a couple of ways you can solve this:
Obtain Pre-signed URL from a Lambda
You can write a lambda function behind an API Gateway that you could call to give you pre-signed URL to post on S3. This URL will allow anyone that has this URL to upload one time to S3. When the user is ready to submit the text-editor, you would just post the attached file to S3 using the pre-signed URL.
C# Lambda Example
IAmazonS3 client;
client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
// Generate a pre-signed URL.
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Key = objectKey,
Verb = HttpVerb.PUT,
Expires = DateTime.Now.AddMinutes(5)
};
string url = null;
url = s3Client.GetPreSignedURL(request);
// Upload a file using the pre-signed URL.
HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
httpRequest.Method = "PUT";
using (Stream dataStream = httpRequest.GetRequestStream())
{
// Upload object.
}
HttpWebResponse response = httpRequest.GetResponse() as HttpWebResponse;
You can find more examples at AWS S3s documentation on obtaining a pre-signed URL via a Lambda written in Java, C#, Ruby, etc..
For doing the upload to a pre-signed URL from your Reactjs app, you can find some awesome examples at this Stackoverflow post.
S3 Object Expiration
You can move all pending images to a bucket that has its lifecycle configured to delete objects within a certain period. Then, when the post is submitted, you can move the object from the transitory bucket to a more permanent bucket. More information on S3 object expiration can be found in their docs.
A: Each Amazon S3 bucket can be configured to delete files in certain folders after a set period of time. I would suggest pushing all temp images to a specific directory, then configure the directory to empty itself out after enough time has elapsed for your program to make use of those files. This way, you don't have to actively monitor anything - S3 will empty out the directly based on file age for you automatically.
| |
doc_23533186
|
table {
width: 100%;
}
tbody {
display: block;
max-height: 160px;
overflow-y: scroll;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<table id="myHeader" class="scroll table table-striped table-hover table-bordered table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th class="mobiile">Document</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
[userName]
</td>
<td>
[userProfession]
</td>
<td class="mobiile"><iframe id="myHeader" src="https://i.stack.imgur.com/Pnq8a.jpg" width="250px" height="250px"></iframe></td>
<td>
<div class="dropdown">
<button class="dropbtn">Action</button>
<div class="dropdown-content">
<a class="btn btn-primary" href="user_images/['userPic']"><span class="glyphicon glyphicon-eye-open"></span> View</a>
<p id="i['userID']" style="display: none;">
['userPic']
</p>
<button onclick="copyToClipboard('#i['userID']')" class="btn btn-primary"><span class="glyphicon glyphicon-eye-open"></span> Share</button>
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
$("<div class='alert alert-success'>Copied url of image: <font color='blue'>[userName]</font>! </div>").insertBefore('#cr').delay(3000).fadeOut();
}
</script>
<a class="btn btn-success" href="user_images/['userPic']" title="Download [userName]" download><span class="glyphicon glyphicon-download"></span> Download</a>
<a class="btn btn-info" href="editform.php?edit_id=['userID']" title="click for edit"><span class="glyphicon glyphicon-edit"></span> Edit</a>
<a class="btn btn-danger" href="?delete_id=['userID']" title="click for delete" onclick="return confirm('sure to delete ?')"><span class="glyphicon glyphicon-remove-circle"></span> Delete</a>
</div>
</div>
</td>
</tr>
</tbody>
</table>
| |
doc_23533187
|
{
*left_mean = 0;
*right_mean = 0;
int32_t i_b;
float local_left = 0, local_right = 0;
for (i_b = -(block_height-1)/2; i_b < (block_height-1)/2; i_b++) {
#pragma omp parallel for reduction(+:local_left,local_right)
for ( int32_t j_b = -(block_width-1)/2; j_b < (block_width-1)/2; j_b++) {
// Borders checking
if (!(i+i_b >= 0) || !(i+i_b < h) || !(j+j_b >= 0) || !(j+j_b < w) || !(j+j_b-d >= 0) || !(j+j_b-d < w)) {
continue;
}
// Calculating indices of the block within the whole image
int32_t ind_l = (i+i_b)*w + (j+j_b);
int32_t ind_r = (i+i_b)*w + (j+j_b-d);
// Updating the block means
//*left_mean += *(left+ind_l);
//*right_mean += *(right+ind_r);
local_left += left[ind_l];
local_right += right[ind_r];
}
}
*left_mean = local_left/(block_height * block_width);
*right_mean = local_right/(block_height * block_width);
}
This now makes the program execution longer than non-threaded version. I added private(left,right) but it leads to bad memory access for ind_l.
A: I think this should get you closer to what you want, although I'm not quite sure about one final part.
float local_left, local_right = 0;
for ( int32_t i_b = -(block_height-1)/2; i_b < (block_height-1)/2; i_b++) {
#pragma omp for schedule(static, CORES) reduction(+:left_mean, +: right_mean)
{
for ( int32_t j_b = -(block_width-1)/2; j_b < (block_width-1)/2; j_b++) {
if (your conditions) continue;
int32_t ind_l = (i+i_b)*w + (j+j_b);
int32_t ind_r = (i+i_b)*w + (j+j_b-d);
local_left += *(left+ind_l);
local_right += *(right+ind_r);
}
}
}
*left_mean = local_left/(block_height * block_width);
*right_mean = local_right/(block_height * block_width);
Part I am unsure of is whether you need the schedule() and how to do two different reductions. I know for one reduction, you can simply do
reduction(+:left_mean)
EDIT: some reference for the schedule() http://pages.tacc.utexas.edu/~eijkhout/pcse/html/omp-loop.html#Loopschedules
It looks like you do not need this, but using it could produce a better runtime
| |
doc_23533188
|
def fun():
global v
v = 1
exec("global " + "k")
exec("k" + " = 1")
fun()
print(v)
# prints 1
print(k)
# NameError: name 'k' is not defined
I expect the algorithm to print 1 both for v and for k but I get an error.
A: Just add globals() to the exec function call:
def fun():
global v
v = 1
exec("k" + " = 1", globals())
fun()
print(v)
# prints 1
print(k)
# prints 1
A: If you need to use the exec you can assign the value of k like this
def fun():
exec("globals()['k'] = " + "1")
fun()
print(k) # output is 1
| |
doc_23533189
|
The 'float' property places the aside column to the right of all the content, but places it at the bottom. I have tried using 'flexbox' and this seems to solve the problem regarding the 'aside' element, but it places the footer vertically on-top of the content (& covering part of it) instead of horizontally at the bottom, along with moving the header to the left of the content (it should be at the top under the static nav-bar). This is what it does:
Can anybody help me? I'd really appreciate it.
body {
display: flex;
width: 800px;
height: auto;
margin-right: auto;
margin-left: auto;
text-align: center;
font-family: garamond, serif;
}
#navbar {
position: fixed;
right: 0;
left: 0;
}
.links {
margin: 8px;
padding: 16px;
background-color: orange;
-webkit-border-radius: 75%;
text-decoration: none;
color: black;
font-weight: 900;
transition: opacity 0.5s linear;
}
.links:hover {
opacity: 0.30;
width:
}
header {
font-size: 25px;
padding-top: 30px;
color: orange;
text-shadow: 8px 8px 16px grey;
}
#section1 {
padding-top: 8px;
}
#section2 {
padding-top: 16px;
padding-bottom: 16px;
}
section p {
text-align: justify;
}
#asideh2 {
text-align: center;
}
aside {
font-size: 12px;
width: 15%;
text-align: justify;
float: right;
}
footer {
justify-content: space-between;
background-color: #d3d3d3;
font-size: 12px;
padding: 8px;
}
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<title>Self-Help Emporium</title>
</head>
<body>
<nav id="navbar">
<a class="links" id="link1" href="#">Home</a>
<a class="links" id="link2" href="#">About</a>
<a class="links" id="link3" href="#">Blog</a>
<a class="links" id="link4" href="#">Contact</a>
<a class="links" id="link5" href="#">Disclaimer</a>
</nav>
<header>
<h1>Self-Help Emporium</h1>
<h2>Your Trusted Source for Self-help Material</h2>
</header>
<article>
<section id="section1">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tempus, elit ut vestibulum maximus, orci felis pulvinar velit, malesuada faucibus est lacus et arcu. Cras commodo est nec venenatis blandit. Nullam pretium feugiat ultricies. Proin accumsan, mi et convallis ullamcorper, turpis leo pretium justo, non tincidunt mi est vitae purus. Aenean ultrices scelerisque lacus, eget sagittis justo consectetur ac. Vestibulum interdum consectetur nibh ut lacinia. Aliquam ac fringilla lacus, ut scelerisque purus. Nulla faucibus fringilla varius. Quisque enim ante, placerat eget semper vitae, pulvinar bibendum mi. Maecenas pulvinar tempus tellus, ut consectetur purus feugiat vel. Nulla eget viverra urna. Nulla eu ex eu nisi accumsan scelerisque. Nullam et nulla bibendum, condimentum odio eget, aliquet sem. Nunc ornare volutpat urna ut feugiat.</p>
<p>Maecenas scelerisque leo ipsum, id molestie dui auctor ac. Nunc feugiat laoreet tortor et convallis. Duis quis nisl et libero consectetur bibendum tempor at lectus. Praesent tristique, mi semper pharetra fermentum, metus orci porta ipsum, sit amet accumsan dolor tellus sit amet magna. Nam iaculis odio vel gravida egestas. Vestibulum venenatis est non orci pharetra ultricies. Fusce urna leo, commodo a ex vel, cursus semper sem. Etiam rutrum at est ut volutpat. Etiam vitae ullamcorper lectus. Duis tempus maximus nisi, eu aliquet felis congue ut. Donec erat arcu, malesuada eu ligula quis, consectetur suscipit mauris. Mauris commodo tortor ac elit euismod facilisis.</p>
<p>Vestibulum porttitor pulvinar erat finibus molestie. In at felis eu augue feugiat ullamcorper in ut sapien. Pellentesque gravida eros non sapien convallis ullamcorper. Vivamus magna odio, tristique sed sapien aliquet, dictum aliquet augue. Nunc lorem quam, rutrum quis nulla euismod, ornare aliquet urna. Nullam lobortis malesuada nisl, vitae mattis purus pharetra nec. Duis enim est, malesuada quis odio ac, rutrum luctus nisl. Morbi tortor risus, posuere quis orci ut, pulvinar luctus lectus. Mauris auctor risus ut dapibus mattis. Suspendisse euismod felis mauris, sit amet rhoncus lacus posuere et. In scelerisque lacus vel arcu pellentesque facilisis. Aliquam nisl tortor, cursus ac tincidunt luctus, malesuada quis lectus.</p>
</section>
<section id="section2">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tempus, elit ut vestibulum maximus, orci felis pulvinar velit, malesuada faucibus est lacus et arcu. Cras commodo est nec venenatis blandit. Nullam pretium feugiat ultricies. Proin accumsan, mi et convallis ullamcorper, turpis leo pretium justo, non tincidunt mi est vitae purus. Aenean ultrices scelerisque lacus, eget sagittis justo consectetur ac. Vestibulum interdum consectetur nibh ut lacinia. Aliquam ac fringilla lacus, ut scelerisque purus. Nulla faucibus fringilla varius. Quisque enim ante, placerat eget semper vitae, pulvinar bibendum mi. Maecenas pulvinar tempus tellus, ut consectetur purus feugiat vel. Nulla eget viverra urna. Nulla eu ex eu nisi accumsan scelerisque. Nullam et nulla bibendum, condimentum odio eget, aliquet sem. Nunc ornare volutpat urna ut feugiat.</p>
<p>Maecenas scelerisque leo ipsum, id molestie dui auctor ac. Nunc feugiat laoreet tortor et convallis. Duis quis nisl et libero consectetur bibendum tempor at lectus. Praesent tristique, mi semper pharetra fermentum, metus orci porta ipsum, sit amet accumsan dolor tellus sit amet magna. Nam iaculis odio vel gravida egestas. Vestibulum venenatis est non orci pharetra ultricies. Fusce urna leo, commodo a ex vel, cursus semper sem. Etiam rutrum at est ut volutpat. Etiam vitae ullamcorper lectus. Duis tempus maximus nisi, eu aliquet felis congue ut. Donec erat arcu, malesuada eu ligula quis, consectetur suscipit mauris. Mauris commodo tortor ac elit euismod facilisis.</p>
<p>Vestibulum porttitor pulvinar erat finibus molestie. In at felis eu augue feugiat ullamcorper in ut sapien. Pellentesque gravida eros non sapien convallis ullamcorper. Vivamus magna odio, tristique sed sapien aliquet, dictum aliquet augue. Nunc lorem quam, rutrum quis nulla euismod, ornare aliquet urna. Nullam lobortis malesuada nisl, vitae mattis purus pharetra nec. Duis enim est, malesuada quis odio ac, rutrum luctus nisl. Morbi tortor risus, posuere quis orci ut, pulvinar luctus lectus. Mauris auctor risus ut dapibus mattis. Suspendisse euismod felis mauris, sit amet rhoncus lacus posuere et. In scelerisque lacus vel arcu pellentesque facilisis. Aliquam nisl tortor, cursus ac tincidunt luctus, malesuada quis lectus.</p>
</section>
</article>
<form>
</form>
</main>
<footer>
<span>Mathew J. M. | 2018 ™</span>
<span>Last updated: 11/09/2018</span>
</footer>
<aside>
<h2 id="asideh2">Self-Help Quotes:</h2>
<p>No matter where you are in life, you’ll save a lot of time by not worrying too much about what other people think about you. The earlier in your life that you can learn that, the easier the rest of it will be.</p>
<p>Our only limitations in life are those we set up in our own minds.</p>
<p>Focus on what you can control: your actions. How you react to negative feelings will be the key to your success.</p>
<p>Don’t Take Anything Personally. Nothing others do is because of you. What others say and do is a projection of their own reality, their own dream. When you are immune to the opinions of others, you won’t be the victim of needless suffering.</p>
</aside>
</body>
</html>
Edited: As you can see in the screenshot, the footer is vertical and is covering part of the main content. The header has been moved to the left of the main content. This has been caused by using 'flexbox'. If I don't use 'flexbox', the 'Self-Help Quotes' in the 'aside' element is placed under the content and not at the side.
A: I have solved this by adding a 'div' container with flexbox. I have kept the heading, nav-bar and footer outside of the flexbox container.
Note: In the picture below I have yet to add space and style for the 'aside' element.
A: You can use flexbox display: flex with fixed or sticky position position: fixed.
| |
doc_23533190
|
// $user = User::create([
// 'name' => $request->input('name'),
// 'email' => $request->input('email'),
// 'password' => Hash::make($request->input('password'))
// ]);
//
// return $user;
return "test";
}
Hi all,
basically, I'm trying to build a restful API with Laravel and my API is being hit by Postman, but when I send a JSON body my $request is an empty array.
It's the first time I'm touching Laravel so it's probably something obvious so thank you in advance !
A: Try this one
use Exception;
public function register(Request $request) {
try {
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => Hash::make($request->input('password'))
]);
return response()->json(['status' => true, 'message' => 'You have been register successfully', 'data' => $user]);
} catch (Exception $e) {
return response()->json(['status' => false, 'message' => $e->getMessage(), 'data' => []]);
}
}
| |
doc_23533191
|
I was wondering what the best way to fill the screen again would be without rewriting these hundreds of CGPoint calls. I was thinking if I could overload CGPointMake somehow to offset each one by (44,0) it would help to center things. Or maybe there's a way with OpenGL to shift everything in one direction? I'm not overly familiar with OpenGL so I'm not sure where the best place to start would be - any help is greatly appreciated!
A: Overloading CGPointMake sounds like too much magic to me. Are all these occurences really just centering the point? In that case you could write the screen-agnostic version:
// Or something similar given your UI orientation and transformations
CGPointMake(CGRectGetMidY([[UIScreen mainScreen] bounds]), someY);
And since that’s quite a mouthful, you could introduce a macro or a function:
CGPoint CGPointMakeHorizontalCenter(CGFloat y) { … }
Then bite the bullet, write a nice regular expression and replace all centering CGPointMake references with calls to this CGPointMakeHorizontalCenter.
(This all assumes you just need to center things better. In reality, maybe you also have to change some assets to better fill the screen? I think you could just stretch your whole older rendering code to fill the screen, but that would look ugly.)
| |
doc_23533192
|
don`t know sure...
<?php
if(isset($_GET['p'])) {
$allowedPages = array();
$openDir = opendir('./pages/');
while(false !== ($entry = readdir($openDir))) {
$allowedPages[] = $entry;
}
closedir($openDir);
$_GET['p'] = preg_replace('/([^.]+)(?:\.[^.]+)?$/', "$1.php", $_GET['p']);
$_GET['p'] = preg_replace('/\.[^.]+$/', '.php', $_GET['p']);
if(in_array($_GET['p'], $allowedPages)) {
include './pages/'.$_GET['p'];
} else {
header("HTTP/1.0 404 Not Found");
header("Location: ./404");
exit();
}
}
?>
| |
doc_23533193
|
Redis server is managed by a sentinel and the client is built as follows:
client := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: common.RedisSentinalMasterName,
SentinelAddrs: sentinalAddr,
PoolSize: poolSize,
MinIdleConns: idleConns,
MaxRetries: 3,
DB: 1,
ReadTimeout: 15 * time.Minute,
WriteTimeout: 15 * time.Minute,
})
result, err := client.XReadStreams(ctx, streamName, id).Result()
But it ends in an error always
"WRONGTYPE Operation against a key holding the wrong kind of value"
The same code is working when connected to a standalone server
| |
doc_23533194
|
If you try to access the configuration using ConfigurationManager.GetSection("unity") from a static context, it will return null. Calling the same thing from a non-static context produces the expected results (the section is returned). Since the first component works correctly calling that from a static context, what am I doing wrong?
Works in DLL 1, but not in DLL 2:
private static IUnityContainer m_unityContainer = new UnityContainer().LoadConfiguration()
Works in DLL 2:
private IUnityContainer m_unityContainer = new UnityContainer().LoadConfiguration()
or
private IUnityContainer m_unityContainer;
public void Process()
{
m_unityContainer = new UnityContainer().LoadConfiguration();
}
A: I'm not sure, but I think this had something to do with the differences in x64 and x86. I solved it by changing the code to
private static readonly Lazy<IUnityContainer> m_unityContainer = new Lazy<IUnityContainer>(() => new UnityContainer().LoadConfiguration());
A: Had a similar problem reading the config file in my COM+ assembly.
What worked for me:
1) BOTH the application.config file and application.manifest need to be in the same folder as the assembly (in my case debug folder).
2) The Application Root Directory needs to be specified in the Activation Tab of the COM+ Application. Run Component Services, right click Properties, go to Activation tab. Can also do this using regsvcs /appdir: option.
| |
doc_23533195
|
I have dragged a Pane inside the GridPane. The Pane seems to have to follow the constraints given by RowConstraints and ColumnConstraints. The problem is that these are not aligned with my pane:
I did not expect this to be a big problem, but this results in a gap that is visible when I run my code:
I am talking about the white-colored part in this figure - I want this to be blue. Also, I want to see the entire pane in my window.
I played around and tried to figure this out on my own, but I don't see what I am doing wrong. Any ideas?
A: What seems to fix the issue is the following:
Inside the Inspector, open the Layout-entry for ColumConstraints. Change HGrow and HAlignment from INHERIT to ALWAYS and LEFT, respectively.
But if anyone knows more about this, feel free to post a separate answer!
| |
doc_23533196
|
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.ArrayList
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:226)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:224)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:119)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
It is fetching the list from database and also printing in console but for some reason it is unable to convert to JSON
here's my web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Restaurant</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
here's my dispatcher servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan
base-package="com.mvcrest.controller"></context:component-scan>
</beans>
I've searched around and most solutions point towards adding jackson dependencies in pom.xml but I already have them
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MvcRest</groupId>
<artifactId>MvcRest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>
My controller is also being hit(I know this because the List is being printed in console)
@Controller
public class App {
IRestaurantService res;
public App() {
try {
res = new RestaurantService();
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@RequestMapping(value = "/menu", method = RequestMethod.GET)
public ResponseEntity<List<Menu>> getmenu() {
List<Menu> menus = res.getMenu();
for (Menu menu : menus) {
System.out.println(menu.getName());
}
return new ResponseEntity<List<Menu>>(menus, HttpStatus.OK);
}
}
Here's my console log(I use Eclipse Photon for the record).
Nov 12, 2018 5:47:34 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:MvcRest' did not find a matching property.
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/9.0.10
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Jun 20 2018 17:32:21 UTC
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 9.0.10.0
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 10
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 10.0
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jre1.8.0_102
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_102-b14
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: D:\WorkSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: D:\Tools\apache-tomcat-9.0.10
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=D:\WorkSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=D:\Tools\apache-tomcat-9.0.10
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=D:\WorkSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=D:\Tools\apache-tomcat-9.0.10\endorsed
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Nov 12, 2018 5:47:34 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_102\bin;C:\windows\Sun\Java\bin;C:\windows\system32;C:\windows;C:/Program Files/Java/jre1.8.0_102/bin/server;C:/Program Files/Java/jre1.8.0_102/bin;C:/Program Files/Java/jre1.8.0_102/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Microsoft Application Virtualization Client;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\Maven\bin\;C:\Program Files (x86)\MySQL\MySQL Utilities 1.6\;C:\Program Files\Tomcat\bin\;C:\Users\M1048950\AppData\Local\Microsoft\WindowsApps;;C:\Program Files\Microsoft VS Code\bin;C:\Users\M1048950\AppData\Roaming\npm;C:\windows\system32;;.]
Nov 12, 2018 5:47:34 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8030"]
Nov 12, 2018 5:47:34 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Nov 12, 2018 5:47:34 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8090"]
Nov 12, 2018 5:47:34 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Nov 12, 2018 5:47:34 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1426 ms
Nov 12, 2018 5:47:34 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Nov 12, 2018 5:47:34 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/9.0.10
Nov 12, 2018 5:47:44 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Nov 12, 2018 5:47:57 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Nov 12, 2018 5:47:57 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Nov 12, 2018 5:47:57 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Nov 12, 2018 5:47:57 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization started
Nov 12, 2018 5:47:57 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Mon Nov 12 17:47:57 IST 2018]; root of context hierarchy
Nov 12, 2018 5:47:58 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
Nov 12, 2018 5:48:00 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/menu],methods=[GET]}" onto public org.springframework.http.ResponseEntity<java.util.List<com.mvcrest.entity.Menu>> com.mvcrest.controller.App.getmenu()
Nov 12, 2018 5:48:01 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for @ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet': startup date [Mon Nov 12 17:47:57 IST 2018]; root of context hierarchy
Nov 12, 2018 5:48:02 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization completed in 4536 ms
Nov 12, 2018 5:48:02 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8030"]
Nov 12, 2018 5:48:02 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8090"]
Nov 12, 2018 5:48:02 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 27251 ms
Nov 12, 2018 5:48:03 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/MvcRest/] in DispatcherServlet with name 'dispatcher'
Burger
Pizza
Pasta
Nutella
Steak
Ice Cream
Nov 12, 2018 5:48:08 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpMessageNotWritable
WARNING: Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.ArrayList
I am hitting the endpoint "http://localhost:8030/MvcRest/menu" using Browser(Tried Postman too but that shouldn't make a difference and is irrelavent here).
Been at it for 3 Days. Any help is Much Appreciated
A: In your dispatcher servlet config xml file make sure you have this:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
The above code adds the necessary convertors.
Don't forget to add the namespace for mvc.
A: Try changing your @RequestMapping to @GetMapping or or change it from ResponseEntity<> to @ResponseBody
Example 1
@GetMapping("/menu")
public ResponseEntity<List<Menu>> getmenu() {
List<Menu> menus = res.getMenu();
for (Menu menu : menus) {
System.out.println(menu.getName());
}
return new ResponseEntity<List<Menu>>(menus, HttpStatus.OK);
}
Example 2
@RequestMapping(value = "/menu", method = RequestMethod.GET)
public @ResponseBody List<Menu> getmenu() {
List<Menu> menus = res.getMenu();
for (Menu menu : menus) {
System.out.println(menu.getName());
}
return menues;
}
https://www.baeldung.com/spring-response-entity
One last thing; youre IRestaurantService should be annotated as a @Service in the class or what implements it and then should be autowired into your controller so you do not have to instantiate it.
@Service
public class RestarauntService implements IRestaurantService {
...
}
Then
@Controller
public class App {
@Autowired
private RestaurantService res;
....
}
| |
doc_23533197
|
Something like:
import time
class Count_Watcher:
def __init__( self, to_watch ):
self.to_watch = to_watch
sleep_watch()
def sleep_watch( self ):
time.sleep( 5 )
print( self.to_watch )
line_counter = 0
separate_thread_printer = Count_Watcher( (?some operator) line_counter )
for line in some_file:
line_counter += 1
and the "current" value of line_counter ( as in, current to the for loop ) is printed every five seconds
A: You can do that by wrapping the variable into a list as shown below since all the reference points to the same instance of the list
import time
class Count_Watcher:
def __init__( self, to_watch ):
self.to_watch = to_watch
self.sleep_watch()
def sleep_watch( self ):
time.sleep( 5 )
print( self.to_watch[0] )
line_counter = [0]
separate_thread_printer = Count_Watcher(line_counter)
for line in some_file:
line_counter[0] += 1
A: A raw int will not work, but as k4vin points, out, any other type of object that can be referenced, will.
We can demonstrate this with a list that contains the count, as k4vin did:
class Watcher(object):
def __init__(self, to_watch):
self.to_watch = to_watch
def print_current_value(self):
print self.to_watch
i = 0
watcher = Watcher(i)
watcher.print_current_value()
# prints 0
i += 3
watcher.print_current_value()
# still prints 0
l = [0]
watcher = Watcher(l)
watcher.print_current_value()
# prints [0]
l[0] += 3
watcher.print_current_value()
# prints [3]
But it's a little clunky to keep your count in a list, so one option is to roll your own simple counter, which you can then reference (as with the list):
class Counter(object):
def __init__(self):
self.count = 0
def __add__(self, incr):
self.count += incr
def __str__(self):
return str(self.count)
c = Counter()
watcher = Watcher(c)
watcher.print_current_value()
# prints 0
c += 3
watcher.print_current_value()
# hooray! prints 3
| |
doc_23533198
|
public class Comment
{
public int Id { get; set; }
public string Text { get; set; }
public DateTime CreatedDate { get; set; }
}
And comments can be added to many objects, lets say for example Person and Vehicle, so I will have these classes
public class Person
{
public int Id { get; set; }
public List<Comment> Comments { get; set; }
}
and
public class Vehicle
{
public int Id { get; set; }
public List<Comment> Comments { get; set; }
}
When EF generates my database it adds a Person_Id and Vehicle_Id, which to me is incorrect because:
a) It suggests that a comment relates to a person AND a vehicle, where it should really be a "free standing" object
b) Comments can be added to future objects which will require a table change.
How can I get EF to rather use a linking table for this?
(Note: I cannot and do not want to add navigation properties to the Comment class as that will require a class change everytime a new object needs comments, and my comment class is in my generic library, unrelated to people or vehicles)
I have found this article, but I'm struggling to get my answer from it: http://weblogs.asp.net/manavi/archive/2011/05/17/associations-in-ef-4-1-code-first-part-6-many-valued-associations.aspx
A: EF is generating Person_Id and Vehicle_Id columns on the Comment table, which are nullable. That means that the Comments can be linked to a Person OR a Vehicle OR both a Person and a Vehicle OR Neither. So it is really a "free standing" object.
The model you are probably looking for uses inheritance.
public class Comment
{
public int Id { get; set; }
public string Text { get; set; }
public DateTime CreatedDate { get; set; }
}
public class VehicleComment : Comment
{
public int VehicleID;
}
public class PersonComment : Comment
{
public int PersonID;
}
public class Person
{
public int Id { get; set; }
public List<PersonComment> Comments { get; set; }
}
public class Vehicle
{
public int Id { get; set; }
public List<VehicleComment> Comments { get; set; }
}
EF will default to table-per-hierarchy inheritance. This will create a table similar to the one you have already, but with a "Discriminator" column. You can then work with a DbSet<VehicleComment> directly rather than having to query DbSet<Comment>...Where(x => x.Vehicle_Id != null) to get comments about Vehicles.
Yes, comments added to future objects will require a table change but that isn't exactly a hardship when using Code First. And writing code gets much simpler because you are not going via some kind of linking entity.
EDIT
The change that happens when you add a new Entity with a relationship to Comments is that another foreign key column is added to the Comments table to model that relationship. Adding a nullable column to an existing table is probably as simple a schema change as you can get. As for change control, you are adding a table for the new entity anyway - so you've got a migration file that contains a few extra lines of code.
Also, having a linking table would mean giving up foreign key constraints, cascade deletes etc. would it not?
public class FooComment : Comment
{
//FooID means one more column in the table
public int FooID;
}
public class Foo
{
public int Id { get; set; }
public List<FooComment> Comments { get; set; }
}
| |
doc_23533199
|
apiVersion: batch/v1
kind: Job
metadata:
name: pi13
spec:
template:
spec:
containers:
- name: pi
image: perl
command: ["/bin/echo"]
args: ["1 >> /data/text12.txt"]
volumeMounts:
- mountPath: /data
name: data
volumes:
- name: data
hostPath:
path: /home/user/data
restartPolicy: Never
backoffLimit: 1
It runs fine and gives this output in the dashboard
1 >> /data/shai12.txt
But writes nothing to the file (I try to read it on the host after the run is completed but nothing happens)
What am i missing here?
A: Your job should like like this:
apiVersion: batch/v1
kind: Job
metadata:
name: pi13
spec:
template:
spec:
containers:
- name: pi
image: perl
command: [ "sh", "-c"]
args: ["echo 1 >> /data/text12.txt"]
volumeMounts:
- mountPath: /data
name: data
volumes:
- name: data
hostPath:
path: /tmp/data
restartPolicy: Never
backoffLimit: 1
In your case you pass whole 1 >> /data/text12.txt to echo command and as results it prints 1 >> /data/text12.txt what you can check in job logs.
hostPath creates directory /data, so this is why you found it.
I hope it helps.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.