text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: cudaMemcpy returns cudaErrorInvalidArgument when reading from Device to Host, unclear why first post here. I'm currently working on a project that requires writing a large 2d array (on the order of 1,000,000x7) into my GPU, doing some computation, and returning it to the Host. Since I want to do so quickly and with such a large array, I attempted to flatten the array to help pass it into the GPU fairly straightforwardly. The array successfully writes (or at least cudaMalloc and cudaMemcpy both return cudaSuccess when I write to the device), but when I try to read it out cudaMemcpy returns an invalid argument error.
I've not been able to figure out why this is, since I think I should be writing a valid 1d array (flattened) onto the device and reading it back out, and I thought I was feeding the right arguments to do this. The only results for this error I've found online involve swapping the dst and src arguments for cudaMemcpy, but I think I've got those right here.
This is a simplified version of my code that reproduces the problem:
#include <iostream>
using namespace std;
void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){
arr = new float*[rows];
arr[0] = new float[rows * cols];
for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols;
}
void write2dArrayToGPU(float ** arr, float * devPtr, unsigned long int rows, unsigned long int cols){
if(cudaSuccess != cudaMalloc((void**)&devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed";
if(cudaSuccess != cudaMemcpy(devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed";
}
void read2dArrayFromGPU(float ** arr, float * devPtr, unsigned long int rows, unsigned long int cols){
if(cudaSuccess != cudaMemcpy(arr[0], devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl;
}
int main(){
int R = 100;
int C = 7;
cout << "Allocating an " << R << "x" << C << " array ...";
float ** arrA;
alloc2dArray(arrA, R, C);
cout << "Assigning some values ...";
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
arrA[i][j] = i*C + j;
}
}
cout << "Done!" << endl;
cout << "Writing to the GPU ...";
float * Darr = 0;
write2dArrayToGPU(arrA, Darr, R, C);
cout << " Done!" << endl;
cout << "Allocating second " << R << "x" << C << " array ...";
float ** arrB;
alloc2dArray(arrB, R, C);
cout << "Done!" << endl;
cout << "Reading from the GPU into the new array ...";
read2dArrayFromGPU(arrB, Darr, R, C);
}
I compile and run this on my laptop with
$nvcc -arch=sm_30 test.cu -o test
$optirun cuda-memcheck ./test
and get the result:
========= CUDA-MEMCHECK
Allocating an 100x7 array ...Assigning some values ...Done!
Writing to the GPU ... Done!
Allocating second 100x7 array ...Done!
========= Program hit cudaErrorInvalidValue (error 11) due to "invalid argument" on CUDA API call to cudaMemcpy.
========= Saved host backtrace up to driver entry point at error
Reading from the GPU into the new array ...========= Host Frame:/usr/lib64/nvidia-bumblebee/libcuda.so.1 [0x2ef343]
cudaMemcpy Read Failed========= Host Frame:./test [0x38c6f]
========= Host Frame:./test [0x2f08]
========= Host Frame:./test [0x3135]
========= Host Frame:/usr/lib64/libc.so.6 (__libc_start_main + 0xf1) [0x20401]
========= Host Frame:./test [0x2c6a]
=========
========= ERROR SUMMARY: 1 error
I'm moderately new to CUDA, and still learning, so any help would be appreciated, thanks!
A: Thanks to Robert Crovella for pointing me in the right direction with a comment above, and linking a similar question.
The gist is that by passing devPtr by value rather than by pointer or by reference into my GPU write and read functions, the cudaMalloc and cudaMemcpy functions were acting only on a copy in the function scope.
Two solutions - (both of these run without throwing errors for me)
First: Pass devPtr by reference into write2dArrayToGPU and read2dArrayFromGPU the solution then looks like.
#include <iostream>
using namespace std;
void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){
arr = new float*[rows];
arr[0] = new float[rows * cols];
for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols;
}
//changed float * devPtr to float * &devPtr
void write2dArrayToGPU(float ** arr, float * &devPtr, unsigned long int rows, unsigned long int cols){
if(cudaSuccess != cudaMalloc((void**)&devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed";
if(cudaSuccess != cudaMemcpy(devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed";
}
//changed float * devPtr to float * &devPtr
void read2dArrayFromGPU(float ** arr, float * &devPtr, unsigned long int rows, unsigned long int cols){
if(cudaSuccess != cudaMemcpy(arr[0], devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl;
}
int main(){
int R = 100;
int C = 7;
cout << "Allocating an " << R << "x" << C << " array ...";
float ** arrA;
alloc2dArray(arrA, R, C);
cout << "Assigning some values ...";
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
arrA[i][j] = i*C + j;
}
}
cout << "Done!" << endl;
cout << "Writing to the GPU ...";
float * Darr = 0;
write2dArrayToGPU(arrA, Darr, R, C);
cout << " Done!" << endl;
cout << "Allocating second " << R << "x" << C << " array ...";
float ** arrB;
alloc2dArray(arrB, R, C);
cout << "Done!" << endl;
cout << "Reading from the GPU into the new array ...";
read2dArrayFromGPU(arrB, Darr, R, C);
}
Second: Pass devPtr by pointer so the solution looks like
#include <iostream>
using namespace std;
void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){
arr = new float*[rows];
arr[0] = new float[rows * cols];
for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols;
}
//changed float * devPtr to float ** devPtr
void write2dArrayToGPU(float ** arr, float ** devPtr, unsigned long int rows, unsigned long int cols){
if(cudaSuccess != cudaMalloc((void**)devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed";
if(cudaSuccess != cudaMemcpy(*devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed";
}
//changed float * devPtr to float ** devPtr
void read2dArrayFromGPU(float ** arr, float ** devPtr, unsigned long int rows, unsigned long int cols){
if(cudaSuccess != cudaMemcpy(arr[0], *devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl;
}
int main(){
int R = 100;
int C = 7;
cout << "Allocating an " << R << "x" << C << " array ...";
float ** arrA;
alloc2dArray(arrA, R, C);
cout << "Assigning some values ...";
for(int i = 0; i < R; i++){
for(int j = 0; j < C; j++){
arrA[i][j] = i*C + j;
}
}
cout << "Done!" << endl;
cout << "Writing to the GPU ...";
float * Darr = 0;
write2dArrayToGPU(arrA, &Darr, R, C); \\changed Darr to &Darr
cout << " Done!" << endl;
cout << "Allocating second " << R << "x" << C << " array ...";
float ** arrB;
alloc2dArray(arrB, R, C);
cout << "Done!" << endl;
cout << "Reading from the GPU into the new array ...";
read2dArrayFromGPU(arrB, &Darr, R, C); // changed Darr to &Darr
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45045913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AJAX load more posts script out putting nothing, no warnings, no notices, no data Can anyone tell me why this is outputting nothing.. at all? No errors, no notices. Nada.
I really need help with this, theres nothing wrong with the SQL details. The codes purpose is too display Mysql data with an AJAX div that loads more posts. If theres anything that could be causing this please post below. Thanks!:)
Source code:
<?php
/* grab stuff */
function get_posts($start = 0, $number_of_posts = 5) {
/* connect to the db */
$connection = mysql_connect('localhost','root','');
mysql_select_db('draft2',$connection) or die(mysql_error());
$posts = array();
/* get the posts */
$query = "SELECT item_id, username, item_content FROM updates ORDER BY update_time DESC LIMIT $start,$number_of_posts" or die(mysql_error());
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
preg_match("/<p>(.*)<\/p>/",$row['item_content'],$matches);
$row['item_content'] = strip_tags($matches[1]);
$posts[] = $row;
}
/* return the posts in the JSON format */
return json_encode($posts);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<style type="text/css">
.style1 {
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande", "Lucida Sans", Arial, sans-serif;
background-image: url('images/banner.gif');
}
.style2 {
font-size: x-small;
color: #62D7D7;
}
.style3 {
text-align: center;
}
.style5 {
font-size: 12px;
font-family: "lucida grande", "tahoma", "verdana", "arial", "sans-serif"
}
.style6 {
font-family: "lucida grande", "tahoma", "verdana", "arial", "sans-serif";
}
.style7 {
text-align: left;
font-size: x-small;
font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande", "Lucida Sans", Arial, sans-serif;
color: #0070B8;
}
#load-more { background-color:#eee; color:#999; font-weight:bold; text-align:center; padding:10px 0; cursor:pointer; }
#load-more:hover { color:#666; }
.activate { background:url(loadmorespinner.gif) 140px 9px no-repeat #eee; }
</style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.scrollTo-1.4.2.js"></script>
<script type="text/javascript">
//when the DOM is ready
$(document).ready(function(){
//settings on top
var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
//function that creates posts
var postHandler = function(postsJSON) {
$.each(postsJSON,function(i,post) {
//post url
var postURL = '' + domain + post.post_name;
var id = 'post-' + post.ID;
//create the HTML
$('<div></div>')
.addClass('post')
.attr('id',id)
//generate the HTML
.html('<a href="' + postURL + '" class="username">' + post.username + '</a><p class="item_content">' + post.item_content + '<br /><a href="' + postURL + '" class="post-more">Read more...</a></p>')
.click(function() {
window.location = postURL;
})
//inject into the container
.appendTo($('#posts'))
.hide()
.slideDown(250,function() {
if(i == 0) {
$.scrollTo($('div#' + id));
}
});
});
};
//place the initial posts in the page
postHandler(initialPosts);
//first, take care of the "load more"
//when someone clicks on the "load more" DIV
var start = <?php echo $_SESSION['posts_start']; ?>;
var desiredPosts = <?php echo $number_of_posts; ?>;
var loadMore = $('#load-more');
//load event / ajax
loadMore.click(function(){
//add the activate class and change the message
loadMore.addClass('activate').text('Loading...');
//begin the ajax attempt
$.ajax({
url: 'jquery-version.php',
data: {
'start': start,
'desiredPosts': desiredPosts
},
type: 'get',
dataType: 'json',
cache: false,
success: function(responseJSON) {
//reset the message
loadMore.text('Load More');
//increment the current status
start += desiredPosts;
//add in the new posts
postHandler(responseJSON);
},
//failure class
error: function() {
//reset the message
loadMore.text('Oops! Try Again.');
},
//complete event
complete: function() {
//remove the spinner
loadMore.removeClass('activate');
}
});
});
});
</script>
</head>
<body>
<!-- Widget XHTML Starts Here -->
<div id="posts-container">
<!-- Posts go inside this DIV -->
<div id="posts"></div>
<!-- Load More "Link" -->
<div id="load-more">Load More</div>
</div>
<!-- Widget XHTML Ends Here -->
</body>
</html>
I actually have posted this problem before, i know that will get you all angry. But i tried fixing it for a while but im just not as experienced as the people on here so I return. Please dont hate me.
A: @user663049: I think your problem is this line --
$query = "SELECT item_id, username, item_content FROM updates ORDER BY update_time DESC LIMIT $start,$number_of_posts" or die(mysql_error());
It should be --
$query = "SELECT item_id, username, item_content FROM updates ORDER BY update_time DESC LIMIT " . $start . ", " . $number_of_posts;
$result = mysql_query($query) or die(mysql_error());
A: If it displays nothing maybe because of web server configuration. Could you just try to insert at the begining of the PHP block the following, so you may see at least errors and make the debugging
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5413201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I define an ext property from Heap.io with gradle kotlin dsl Im using the heap.io and their Android SDK and they advise you to setup their library like:
*
*build.gradle:
android {
defaultConfig {
// Add this section to enable Heap event capture.
ext {
heapEnabled = true
}
// ...
}
// ...
}
But this is using the gradle groovy sintax, Im trying to use it with the Kotlin DSL of gradle like:
*
*build.gradle.kts
android {
defaultConfig {
ext {
set("heapEnabled", true)
}
But it does not work for some reason, so:
Why that may be happening?
A: This works:
(this as ExtensionAware).extensions.extraProperties.set("heapEnabled", true)
I believe Heap is looking into making it so the cast isn't necessary.
A: extra.set("heapEnabled", false)
A: I was able to make it work using withGroovyBuilder like:
android {
defaultConfig {
withGroovyBuilder {
"ext" {
setProperty("heapEnabled", LhConfig.isAnalyticEnabled(project))
}
}
I still dont understand where is the issue :(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62580898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add a new line in text field of dropdown in semantic-ui react? Here is the render function
render(){
const { members, user } = this.props;
let memberOptions = [];
members.forEach((member, i) => {
memberOptions.push({
key: i,
text: member.user.name,
value: member.user.id,
image: { avatar: true, src: member.user.gravatar },
});
});
return (
<Dropdown placeholder='Select User' fluid selection options={memberOptions} />
)
}
This will render perfectly. But I also want to add one more text(say email) in this text field in a new line. So that dropdown items show similar to this : https://react.semantic-ui.com/elements/list#list-example-relaxed
How can I achieve this?
A: Akhila, I would recommend that you use the content prop instead of the text prop for your Dropdown.Item that you are rendering from your memberOptions array. The text prop specifically expects a string. The content prop will accept anything, including other React components or nodes. So instead of returning text as a string, you could do something like this for content, maybe as a separate class method on your component:
const renderItemContent = (member) => {
const {
email,
name,
} = member.user;
const emailStyle = {
color : '#333',
fontSize : '.875em',
}
return(
<React.Fragment>
{name}
{email &&
<div style={emailStyle}>{email}</div>
}
</React.Fragment>
)
}
Then set content: this.renderItemContent(member) on your memberOptionsArray.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50129466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How set set bash variable to file name in Docker I have a Dockerfile in which files in a directory are downloaded:
RUN wget https://www.classe.cornell.edu/~cesrulib/downloads/tarballs/ -r -l1 --no-parent -A tgz \
--cut=99 -nH -nv --show-progress --progress=bar:force:noscroll
I know that there is exactly one file here of the form "bmad_dist_YYYY_MMDD.tgz" where "YYYY_MMDD" is a date. For example, the file might be named "bmad_dist_2020_0707.tgz". I want to set a bash variable to the file name without the ".tgz" extension. If this was outside of docker I could use:
FULLNAME=$(ls -1 bmad_dist_*.tgz)
BMADDIST="${FULLNAME%.*}"
So I tried in the dockerfile:
ENV FULLNAME $(ls -1 bmad_dist_*.tgz)
ENV BMADDIST "${FULLNAME%.*}"
But this does not work. Is it possible to do what I want?
A: Shell expansion does not happen in Dockerfile ENV. Then workaround that you can try is to pass the name during Docker build.
Grab the filename during build name and discard the file or you can try --spider for wget to just get the filename.
ARG FULLNAME
ENV FULLNAME=${FULLNAME}
Then pass the full name dynamically during build time.
For example
docker build --build-args FULLNAME=$(wget -nv https://upload.wikimedia.org/wikipedia/commons/5/54/Golden_Gate_Bridge_0002.jpg 2>&1 |cut -d\" -f2) -t my_image .
A: The ENV ... ... syntax is mainly for plaintext content, docker build arguments, or other environment variables. It does not support a subshell like your example.
It is also not possible to use RUN export ... and have that variable defined in downstream image layers.
The best route may be to write the name to a file in the filesystem and read from that file instead of an environment variable. Or, if an environment variable is crucial, you could set an environment variable from the contents of that file in an ENTRYPOINT script.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62786274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Test services with real backend in angular I want to test a service, which calls a real backend url and can not find the solution for it. My service has to call data from server and I want to be sure, that the data comes to the service and the service handle it right.
So here is just a simple example of my Login Service:
@Injectable()
export class LoginService {
/**
* The token, which will be stored on the localStorage.
*/
public token: string;
//Eventemitter, for updating the navigation, when the user logs in
@Output() loggedInEm:EventEmitter<any> = new EventEmitter();
constructor(private http: Http) {
// set token if saved in local storage
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.token;
}
login(_mail, _pass): Observable<number> {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var data = {
mail: _mail,
pass: _pass
};
return this.http.post('/login', JSON.stringify(data), {
headers : headers
}).map((response: Response) => {
let res = response.json();
this.logged = res;
});
}
public loggedIn() : boolean {
return this.logged;
}
This is how I want to test it:
describe('Login Service', () => {
let loginService: LoginService;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
],
providers: [
LoginService
],
imports: [
FormsModule,
IonicModule
],
});
inject([LoginService], (service) => {
loginService = service;
});
});
it("Should login user", () => {
loginService.login("[email protected]", "123456");
let loggedIn = loginService.loggedIn();
expect(loggedIn).toBe(true);
});
});
But I get following error:
TypeError: Cannot read property 'login' of undefined, so the service must be undefined. I could mock the service, but I want to work it with the real database, which I have on my backend server.
So what could be the problem and how can I solve it?
Kind regards,
Andrej
A: Try this :
it("Should login user", () => {
loginService.login("[email protected]", "123456").subscribe(value => {
let loggedIn = loginService.loggedIn();
expect(loggedIn).toBe(true);
done();
});
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46252236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: TypeError: _onRequestWithOpts is not a function at Object.httpsProvider._onRequestWithOpts I'm creating an app that uses firebase-functions. I created my app directory and ran firebase init. After that was completed I tried to run the hello world program that it gives you using firebase serve, and I get this error:
TypeError: _onRequestWithOpts is not a function
at Object.httpsProvider._onRequestWithOpts
from what it looks like, it seems to be an issue with the onRequest() method but I have made apps using this before and have never ran into this issue. I literally didn't change a single piece of code that they initially give you so unless they decided to change something overnight i'm not sure what the issue is.
using firebase deploy works, but firebase serve does not. Using express and adding new functions, the error pops up when running firebase deploy and serve.
const functions = require('firebase-functions');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-
functions
//
exports.helloWorld = functions.https.onRequest((request, response)
=> {
response.send("Hello from Firebase!");
});
Gabriels-MacBook-Pro:functions Mike$ firebase serve
=== Serving from '/Users/Gabe/Desktop/mycart-functions'...
⚠ Your requested "node" version "8" doesn't match your global
version "10"
✔ functions: Emulator started at http://localhost:5000
i functions: Watching "/Users/Gabe/Desktop/mycart-
functions/functions" for Cloud Functions...
⚠ TypeError: _onRequestWithOpts is not a function
at Object.httpsProvider._onRequestWithOpts
(/usr/local/lib/node_modules/firebase-
tools/lib/emulator/functionsEmulatorRuntime.js:278:24)
at Object.httpsProvider.onRequest
(/usr/local/lib/node_modules/firebase-
tools/lib/emulator/functionsEmulatorRuntime.js:283:34)
at Object.<anonymous> (/Users/Gabe/Desktop/mycart-
functions/functions/index.js:6:39)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js
(internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
⚠ We were unable to load your functions code. (see above)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56947340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQLite query running successfully in version 3.5.2 but giving error in version 3.7.11 - using aggregate functions My query was working fine in Sqlite 3.5.1 version but when I run the same query in 3.7.11 version am getting misuse of aggregate function min() error. Below one is my query. Please help me in this regard
select distinct category from m_ipaperdara order by min(displayorder) asc
A: DISTINCT is not a grouping that can be used for aggregate functions.
If you want take the smalled displayorder in each category, you have to explicitly group by that column:
SELECT category FROM m_ipaperdara GROUP BY category ORDER BY MIN(displayorder)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12594607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is PyCharm Community Edition doesn't have Database Tool? I'm using pycharm 2020.3 community edition. but id doesn't showing database tool. it means this edition comes without that option? or any action we have to do for this?
*Note: some people saying add plugin data base browser. but that is not built in. I want database tool.
A: PyCharm Community doesn't have database tools. See comparison matrix https://www.jetbrains.com/pycharm/features/editions_comparison_matrix.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66837584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: solr LowerCaseFilterFactory should not filter number I'm using a query schema which need to let abc match Abc and 400 match 400 (user name match).
But I found when I use LowerCaseFilterFactory, It not return any result when I query 400.
I digg into the source code, and found LowerCaseTokenizerFactory use LowerCaseTokenizer which extends LetterTokenizer, and it filter all the numbers.
How should I fix this?
A: You are right that LowerCaseTokenizer will remove all non-letters. It would very useful (as far as providing a meaningful answer) to see your schema, as I don't believe just using the lowercase filter factory should generate a Tokenizer of any kind.
At any rate, though, there are plenty of other options for tokenizers. Both Standard or Classic might suit your needs better.
Something along the line of:
<analyzer>
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
Might do well for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16248589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ErrorException: Creating default object from empty value - Laravel I have just got this error all the tries while updating my table data.
ErrorException: Creating default object from empty value
AdminController.php
public function update(Request $r, $post_id) {
$post = Post::find($post_id);
$post->post_title = $r->post_title;
$post->post_image = $r->post_image;
$post->post_details = $r->post_details;
$post->post_rating = $r->post_rating;
$post->id = $r->id;
$post->save();
return back();
}
My Resource Route
Route::resource('post', AdminController::class);
Blade File
<div class="edit-post-content">
<form action="{{ route('post.update',$list->post_id) }}" method="POST">
@csrf
@method('PUT')
<input type="hidden" name="id" value="{{$list->id}}">
<input type="hidden" name="post_rating" value="{{$list->post_rating}}">
<div class="mb-3">
Edit Title: <input class="form-control" name="post_title" type="text" id="exampleFormControlInput1" value="{{$list->post_title}}" aria-label="default input example">
</div>
<div class="mb-3">
Edit Description:
<textarea class="form-control" id="exampleFormControlTextarea1" name="post_details" rows="3">
{{ $list->post_details }}
</textarea>
</div>
<div>
<img src="{{asset('images/'.trim($list->post_image))}}" alt="" width="120px;">
Edit Photos:
<input id="formFileMultiple" class="form-control form-control-lg" name="post_image" type="file" value="{{ $list->post_image }}" multiple>
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</form>
</div>
Could someone help me, please?
A: There is a chance that the model doesn't exist. You can add a check for this in your controller as follows:
public function update(Request $r, $post_id) {
$post = Post::find($post_id);
if (!$post) {
// You can add code to handle the case when the model isn't found like displaying an error message
return back();
}
$post->post_title = $r->post_title;
$post->post_image = $r->post_image;
$post->post_details = $r->post_details;
$post->post_rating = $r->post_rating;
$post->id = $r->id;
$post->save();
return back();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68810878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Communicating between Kernel Threads in Linux I am porting a app/PCI driver from vxWorks to Linux and I would like to keep the same architecture if possible. The current driver has 2 tasks(threads) that communicate with each other using message queues. Is there a mechanism to communicate between kernel threads? The message queues are being used to pass buffer addresses and size info so the tasks can use DMA to move large amounts of data.
A: It sounds like the workqueue interface might be what you're after - or for something lighter-weight, a kfifo combined with a rwsem semaphore.
A: I would strongly advise against keeping the VxWorks architecture on Linux. Kernel thread proliferation is frowned upon, your code will never make it into official kernel tree. Even if you don't care about that, are you 100% sure that you want to develop a driver in a non-standard way ? Things would be much simpler if you would just get rid of these two tasks. BTW, why on earth you need tasks for PCI driver to begin with ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1442270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django Attribute Error - Form object has no attribute 'is_valid' I am receiving an error, object has no attribute 'is_valid', when trying to insert form data into a form. Below is the structure of my code:
Views.py:
def add_user(request):
form = Car(request.POST)
if request.method == 'POST' and form.is_valid():
last_store = form.cleaned_data.get['value']
make = request.POST.get('make', '')
model = request.POST.get('model', '')
..
car_obj = Car(last_store = last_store, make = make, model = model, series = series, series_year = series_year, price_new = price_new, engine_size = engine_size, fuel_system = fuel_system, tank_capacity = tank_capacity, power = power, seating_capacity = seating_capacity, standard_transmission = standard_transmission, body_type = body_type, drive = drive, wheelbase = wheelbase, available = available)
car_obj.save()
return HttpResponseRedirect('/inventory/add/')
else:
form = Car()
return render(request, 'cars/inventory-add.html', {})
Class:
class Car(models.Model):
make = models.CharField(max_length=200, null=False)
model = models.CharField(max_length=200, null=False)
series = models.CharField(max_length=200, null=False)
series_year = models.IntegerField(null=False)
price_new = models.IntegerField(null=False)
..
last_store = models.ForeignKey(Store, on_delete=models.DO_NOTHING, related_name="last_store")
available = models.BooleanField(null=False, default=True)
def __str__(self):
return(self.make + " " + self.model)
CarForm (forms.py)
class CarForm(forms.ModelForm):
class Meta:
model = Car
fields = ['last_store', 'make', 'model', 'series', 'series_year', 'price_new', 'engine_size', 'fuel_system', 'tank_capacity', 'power', 'seating_capacity', 'standard_transmission', 'body_type', 'drive', 'wheelbase', 'available']
The error lies within the last_store as without form.is_valid(), apparently I cannot use form.cleaned_data, but form.is_valid() seems to not even exist? As seen in the class, last_store is of type a foreign key, therefore I am struggling to set the default value for it when the user enters input into the form. The last_store variable is attempting to fetch the value from the inputted form data which consists of a SELECT option..
A: You have a clash between your model and form, which are both named Car. Typically you would fix this by renaming the form CarForm.
Note that you shouldn't normally need to create the object with car_obj = Car(...). If you use a model form, you can simplify your code to car_obj = form.save(). You should also move CarForm(request.POST) inside the if request.method == 'POST' check, and include form in the template context. Putting that together, you get something like:
def add_user(request):
if request.method == 'POST':
form = CarForm(request.POST)
if form.is_valid():
car_obj = form.save()
return HttpResponseRedirect('/inventory/add/')
else:
form = CarForm()
return render(request, 'cars/inventory-add.html', {'form': form})
A: In your views.py file line 2
form = Car(request.POST):
change it to
form = CarForm(request.POST):
Hope it works!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52952348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how do i define props in a function i am new to react and i am trying to use props in a function and i am not sure how to use it. This is the code.
import React from 'react';
import './Card.css';
import { connect } from 'react-redux';
import { addBasket } from '../actions/addAction';
function Card({props},{image, title,author,price}) {
return (
<div className='card-container'>
<div className="image-container">
<img src={props.image} alt='' />
</div>
<div className="card-content">
<div className="card-title">
<h3>{props.title}</h3> </div>
<div className="card-author">
<h4>{props.author}</h4>
</div>
<div className="card-price">
<h3> <span>£{props.price}</span></h3> </div>
</div>
<div className="btn">
<button>
<a onClick={props.addBasket}>
Add to Basket
</a>
</button></div>
</div>
);
}
export default connect(null, { addBasket })(Card);
And that's the error i am getting.
TypeError: Cannot read property 'title' of undefined
</div>
<div className="card-content">
<div className="card-title">
<h3>{props.title}</h3> </div>
<div className="card-author">
<h4>{props.author}</h4>
</div>
A: Replace
function Card({props},{image, title,author,price}) {
with
function Card(props) {
I recommend working through the official React tutorial before using Redux.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65298201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How To get the Check Rule Constraint How can I get the expression of a check constraint?
With MSSMS I can easly see that Table Person has a CHECK constraint named CK_Person validating the expression ([DateOfBirth]<[DateOfDeath]).
With this query I can get the COLUMN_NAME, CONSTRAINT_NAME and CONSTRAINT_TYPE:
SELECT CCU.COLUMN_NAME, CCU.CONSTRAINT_NAME, TC.CONSTRAINT_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CCU ON TC.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME
WHERE TC.TABLE_NAME = 'Person'
Resulting
+-------------+-----------------+-----------------+
| COLUMN_NAME | CONSTRAINT_NAME | CONSTRAINT_TYPE |
+-------------+-----------------+-----------------+
| PersonID | PK_Person | PRIMARY KEY |
| DateOfBirth | CK_Person | CHECK |
| DateOfDeath | CK_Person | CHECK |
+-------------+-----------------+-----------------+
But how can I get the actual expression itself?
A: Try this...
SELECT definition AS Check_Expression
,name AS ConstraintName
FROM sys.check_constraints
WHERE Parent_object_ID = OBJECT_ID('TableName')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30226137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom view, onSaveInstanceState is not called I created a custom view, and tried to restore the state automatically on screen rotation (just as EditText restores current input text automatically), but when I see the log, onSaveInstanceState is not called, and only onRestoreInstanceState is called. What is wrong?
class MyView:LinearLayout
{
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context, attrs, defStyleAttr)
init
{
isSaveEnabled=true
}
override fun onSaveInstanceState(): Parcelable
{
return super.onSaveInstanceState()
Log.d("ss", "save")
}
override fun onRestoreInstanceState(state: Parcelable?)
{
super.onRestoreInstanceState(state)
Log.d("ss", "restore")
}
}
Activity layout:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/top"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.loser.mylayouttest.MyView
android:id="@+id/myView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</AbsoluteLayout>
Activity:
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
A: The reason why you can't see Log.d("ss", "save") being called is simply that the code line is invoked after the return statement. The onSaveInstanceState() is actually called. To see the log move Log.d("ss", "save") above return super.onSaveInstanceState().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50555614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: MySQL : Updating a table having a 'where' clause with a max value I want to update the last generated row (the max(id) row.
I tried this code but it doesn't work
update person t1
set t1.age = 25
where t1.id = (select max(t2.id) from person t2
where t2.address = 'LA, California');
MySQL tells me that : Error Code: 1093. You can't specify target table 't1' for update in FROM clause
So, I suppose that I cannot reach the same tale while performing operations such as updates.
How can I sole this problem ?
Regards.
A: You cannot reference the same table in a subquery, but you can instead do it in a JOIN (which is allowed in UPDATE and DELETE statements):
UPDATE person a
JOIN (SELECT MAX(id) AS id FROM person WHERE address = 'LA, California') b
ON a.id = b.id
SET a.age = 25
Another way you can do it is by using the ORDER BY / LIMIT technique:
UPDATE person
SET age = 25
WHERE address = 'LA, California'
ORDER BY id DESC
LIMIT 1
A: You can try as:
UPDATE person t1
INNER JOIN (SELECT MAX(id) AS id FROM person
WHERE t2.address = 'LA, California') t2
ON t1.id = t2.id
SET t1.age = 25;
or
SELECT MAX(t2.id)
INTO @var_max_id
FROM person t2
WHERE t2.address = 'LA, California';
UPDATE person t1
SET t1.age = 25
WHERE t1.id = IFNULL(@var_max_id, -1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11719346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ClosedXML Copy and Paste Range of formulas as values I have a function ApplyFormulas() that will obviously apply formulas like so
detailWs.Range(companyModel.RevenueFormulaRangeDollars).FormulaR1C1 = companyModel.RevenueFormulaDollars;
However Now I need to copy that range and paste it in the same spot so the values are real and not just formula references.
I am able to do this in VBA with excel interop but I am utilizing ClosedXML. Does anyone know of a way to do this? I tried CopyTo() but there is no paste special etc.
I also attempted
detailWs.Range(companyModel.NoChargeFormulaRangePercent).Value = detailWs.Range(companyModel.NoChargeFormulaRangePercent).Value;
but im getting a property or indexer cant be used because it lacks a getter but from what I can tell both have a get; set; property.
I've tried a couple for things and still not working..
var test = detailWs.Range(companyModel.NoChargeFormulaRangePercent).CellsUsed();
foreach(var c in test)
{
c.Value = c.Value.ToString();
}
A: Here's what I created a few months ago to copy all the formulas in one worksheet to another.
Note: I am having a problem where some formulas using a Name are not correctly copying the Name because something thinks the Name(i.e. =QF00) is a reference and will change it with AutoFill. Will update when I figure it out.
cx.IXLWorksheet out_buff
cx.IXLRange src_range
cx.IXLCells tRows = src_range.CellsUsed(x => x.FormulaA1.Length > 0);
foreach (cx.IXLCell v in tRows)
{
cell_address = v.Address.ToString();
out_buff.Range(cell_address).FormulaA1 = v.FormulaA1;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53675836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Only the last usercontrol shows contentcontrol I have a weird problem. I've created a usercontrol with a label and a canvas.
The canvas references a resource.
But the canvas is only shown on the last control in my stackpanel.
This is my window
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:UserControlSolution" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="UserControlSolution.MainWindow"
Title="MainWindow" Height="836" Width="270.5" Background="#FF2B2B2B" BorderBrush="{DynamicResource Border}" Loaded="Window_Loaded" >
<Window.Resources>
<LinearGradientBrush x:Key="Border" EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF6C6C6C" Offset="0.009"/>
<GradientStop Color="#FFA1A1A1" Offset="1"/>
</LinearGradientBrush>
<SolidColorBrush x:Key="Orange" Color="#FFF5610E"/>
<SolidColorBrush x:Key="Red" Color="#FFE51400"/>
<SolidColorBrush x:Key="Blue" Color="#FF1BA1E2"/>
<SolidColorBrush x:Key="Yellow" Color="#FFFFC40D"/>
</Window.Resources>
<StackPanel Margin="0,10,0,0">
<local:UserControlButton x:Name="Robby" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
<local:UserControlButton x:Name="Erwin" Height="50" VerticalAlignment="Top" Margin="2,0,0,5" />
<local:UserControlButton x:Name="Laurens" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
<local:UserControlButton x:Name="Kevin" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
<local:UserControlButton x:Name="Liesbeth" Height="50" VerticalAlignment="Top" Margin="2,0,0,5" Background="{DynamicResource Orange}"/>
<local:UserControlButton x:Name="Jack" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
<local:UserControlButton x:Name="Filip" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
<local:UserControlButton x:Name="Stefaan" Height="50" VerticalAlignment="Top" Margin="2,0,0,5" Background="{DynamicResource Red}"/>
<local:UserControlButton x:Name="Sami" Height="50" VerticalAlignment="Top" Margin="2,0,0,5" Background="{DynamicResource Blue}"/>
<local:UserControlButton x:Name="Jurgen" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
</StackPanel>
This is my usercontrol, in the contentcontrol at the bottom I reference my canvas.
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
mc:Ignorable="d"
x:Class="UserControlSolution.UserControlButton"
x:Name="UserControl"
Height="50" Background="#FF2F2F2F">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter">
<ei:GoToStateAction TargetObject="{Binding ElementName=UserControl}" StateName="Expand"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeave">
<ei:GoToStateAction TargetObject="{Binding ElementName=UserControl}" StateName="Collapse"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid x:Name="LayoutRoot" Height="50" RenderTransformOrigin="0.5,0.5">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="VisualStateGroup">
<VisualState x:Name="Expand">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Height)" Storyboard.TargetName="LayoutRoot">
<EasingDoubleKeyFrame KeyTime="0" Value="80"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Height)" Storyboard.TargetName="UserControl">
<EasingDoubleKeyFrame KeyTime="0" Value="79"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Collapse"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Rectangle x:Name="rectangle" RenderTransformOrigin="0.5,0.5" Width="230" Height="50"/>
<TextBlock x:Name="NameLabel" FontSize="16" Foreground="#FFE5E5E5" Height="34" Width="149" Text="Onthaal Telefoon" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,10,0,0" FontFamily="Segoe UI Semibold"/>
<Viewbox HorizontalAlignment="Right" VerticalAlignment="Top" Height="50" Width="58.789">
<ContentControl Content="{DynamicResource appbar_close}" Width="91.96" Height="79.911" />
</Viewbox>
</Grid>
</UserControl>
And this is my App file where I define my resources
<Application x:Class="UserControlSolution.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Canvas x:Key="appbar_close" x:Name="appbar_close" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
<Path Width="31.6666" Height="31.6667" Canvas.Left="22.1666" Canvas.Top="22.1667" Stretch="Fill" Fill="#FFEE1111" Data="F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z " Stroke="#FF2F2F2F"/>
</Canvas>
<Canvas x:Key="appbar_check" x:Name="appbar_check" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
<Path Width="37.9998" Height="31.6665" Canvas.Left="19.0001" Canvas.Top="22.1668" Stretch="Fill" Fill="#FF00A300" Data="F1 M 23.7501,33.25L 34.8334,44.3333L 52.2499,22.1668L 56.9999,26.9168L 34.8334,53.8333L 19.0001,38L 23.7501,33.25 Z " Stroke="#FF2F2F2F"/>
</Canvas>
<Canvas x:Key="appbar_arrow_right" x:Name="appbar_arrow_right" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
<Path Width="39.25" Height="28" Canvas.Left="19.0002" Canvas.Top="24" Stretch="Fill" Fill="#FF2B5797" Data="F1 M 19.0002,34L 19.0002,42L 43.7502,42L 33.7502,52L 44.2502,52L 58.2502,38L 44.2502,24L 33.7502,24L 43.7502,34L 19.0002,34 Z " Stroke="#FF2F2F2F"/>
</Canvas>
<SolidColorBrush x:Key="UserControlBackground" Color="#FF2F2F2F"/>
</Application.Resources>
As you can see in the screenshot, only the last control shows the canvas..
A: Since you have only one Canvas and each Visual can have only one parent in visual tree therefore each time you place your resource it's put in that place of visual tree and removed from the previous place. You can either put Canvas directly into ViewBox in UserControl and make Path a resource or you can try setting x:Shared attribute to false on your Canvas which should result in new instance of resource being created each time you refer to it:
<Application.Resources>
<Canvas x:Key="appbar_close" x:Shared="False" ...>
<!-- -->
</Canvas>
</Application.Resources>
A: Set x:Shared=false on resource. It will work.
<Canvas x:Key="appbar_close" x:Name="appbar_close" x:Shared="false" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0" >
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18658092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Problems while running the alexa helloWorldSample I try to deploy the alexa helloworld skill on my own Server using this tutorial
I can build the Sample and get 2 jar files in the target directory but when i try to run the Server via
mvn exec:java -Dexec.executable=”java” -DdisableRequestSignatureCheck=true
i get this error:
java.lang.ClassNotFoundException: Launcher
Can anyone help me in this case?
Best regards,
FelixT
Here is my logfile with the error:
[DEBUG] Goal: org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli)
[DEBUG] Style: Regular
[DEBUG] Configuration: <?xml version="1.0" encoding="UTF-8"?>
<configuration>
<arguments>${exec.arguments}</arguments>
<classpathScope default-value="runtime">${exec.classpathScope}</classpathScope>
<cleanupDaemonThreads>${exec.cleanupDaemonThreads} default-value=</cleanupDaemonThreads>
<commandlineArgs>${exec.args}</commandlineArgs>
<daemonThreadJoinTimeout default-value="15000">${exec.daemonThreadJoinTimeout}</daemonThreadJoinTimeout>
<includePluginDependencies default-value="false">${exec.includePluginDependencies}</includePluginDependencies>
<includeProjectDependencies default-value="true">${exec.includeProjectDependencies}</includeProjectDependencies>
<keepAlive default-value="false">${exec.keepAlive}</keepAlive>
<killAfter default-value="-1">${exec.killAfter}</killAfter>
<localRepository default-value="${localRepository}"/>
<mainClass>Launcher</mainClass>
<pluginDependencies default-value="${plugin.artifacts}"/>
<project default-value="${project}"/>
<remoteRepositories default-value="${project.remoteArtifactRepositories}"/>
<skip default-value="false">${skip}</skip>
<sourceRoot>${sourceRoot}</sourceRoot>
<stopUnresponsiveDaemonThreads>${exec.stopUnresponsiveDaemonThreads} default-value=</stopUnresponsiveDaemonThreads>
<systemProperties>
<systemProperty>
<key>javax.net.ssl.keyStore</key>
<value>/root/java-keystore.jks</value>
</systemProperty>
<systemProperty>
<key>javax.net.ssl.keyStorePassword</key>
<value>XXXXXXXXXX</value>
</systemProperty>
<systemProperty>
<key>com.amazon.speech.speechlet.servlet.disableRequestSignatureCheck</key>
<value>true</value>
</systemProperty>
<systemProperty>
<key>com.amazon.speech.speechlet.servlet.supportedApplicationIds</key>
<value>${supportedApplicationIds}</value>
</systemProperty>
<systemProperty>
<key>com.amazon.speech.speechlet.servlet.timestampTolerance</key>
<value>${timestampTolerance}</value>
</systemProperty>
</systemProperties>
<testSourceRoot>${testSourceRoot}</testSourceRoot>
</configuration>
[DEBUG] =======================================================================
[INFO]
[INFO] >>> exec-maven-plugin:1.2.1:java (default-cli) @ helloworld >>>
[INFO]
[INFO] <<< exec-maven-plugin:1.2.1:java (default-cli) @ helloworld <<<
[DEBUG] Could not find metadata joda-time:joda-time/maven-metadata.xml in local (/root/.m2/repository)
[DEBUG] Failure to find joda-time:joda-time/maven-metadata.xml in file:///root/samples/skill-samples-java-master/helloworld/repo was cached in the local repository, resolution will not be reattempted until the update interval of alexa-skills-kit-repo has elapsed or updates are forced
[DEBUG] Skipped remote update check for joda-time:joda-time/maven-metadata.xml, locally cached metadata up-to-date.
[DEBUG] alexa-skills-kit-samples:helloworld:jar:1.0
[DEBUG] com.amazon.alexa:alexa-skills-kit:jar:1.6.0:compile
[DEBUG] org.eclipse.jetty:jetty-server:jar:9.0.6.v20130930:compile
[DEBUG] org.eclipse.jetty.orbit:javax.servlet:jar:3.0.0.v201112011016:compile
[DEBUG] org.eclipse.jetty:jetty-http:jar:9.0.6.v20130930:compile
[DEBUG] org.eclipse.jetty:jetty-util:jar:9.0.6.v20130930:compile
[DEBUG] org.eclipse.jetty:jetty-io:jar:9.0.6.v20130930:compile
[DEBUG] org.eclipse.jetty:jetty-servlet:jar:9.0.6.v20130930:compile
[DEBUG] org.eclipse.jetty:jetty-security:jar:9.0.6.v20130930:compile
[DEBUG] log4j:log4j:jar:1.2.17:compile
[DEBUG] org.slf4j:slf4j-api:jar:1.7.10:compile
[DEBUG] org.slf4j:slf4j-log4j12:jar:1.7.10:compile
[DEBUG] org.apache.commons:commons-lang3:jar:3.4:compile
[DEBUG] org.apache.directory.studio:org.apache.commons.io:jar:2.4:compile
[DEBUG] commons-io:commons-io:jar:2.4:compile
[DEBUG] com.amazonaws:aws-lambda-java-core:jar:1.0.0:compile
[DEBUG] com.amazonaws:aws-lambda-java-log4j:jar:1.0.0:compile
[DEBUG] com.amazonaws:aws-java-sdk-dynamodb:jar:1.9.40:compile
[DEBUG] com.amazonaws:aws-java-sdk-s3:jar:1.9.40:compile
[DEBUG] com.amazonaws:aws-java-sdk-kms:jar:1.9.40:compile
[DEBUG] com.amazonaws:aws-java-sdk-core:jar:1.9.40:compile
[DEBUG] commons-logging:commons-logging:jar:1.1.3:compile
[DEBUG] org.apache.httpcomponents:httpclient:jar:4.3.4:compile
[DEBUG] org.apache.httpcomponents:httpcore:jar:4.3.2:compile
[DEBUG] commons-codec:commons-codec:jar:1.6:compile
[DEBUG] com.fasterxml.jackson.core:jackson-databind:jar:2.3.2:compile
[DEBUG] com.fasterxml.jackson.core:jackson-annotations:jar:2.3.0:compile
[DEBUG] com.fasterxml.jackson.core:jackson-core:jar:2.3.2:compile
[DEBUG] joda-time:joda-time:jar:2.9.9:compile
[INFO]
[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ helloworld ---
[DEBUG] Created new class realm maven.api
[DEBUG] Importing foreign packages into class realm maven.api
[DEBUG] Imported: org.apache.maven.cli < plexus.core
[DEBUG] Imported: org.codehaus.plexus.lifecycle < plexus.core
[DEBUG] Imported: org.apache.maven.lifecycle < plexus.core
[DEBUG] Imported: org.apache.maven.repository < plexus.core
[DEBUG] Imported: org.codehaus.plexus.personality < plexus.core
[DEBUG] Imported: org.apache.maven.usability < plexus.core
[DEBUG] Imported: org.codehaus.plexus.configuration < plexus.core
[DEBUG] Imported: org.sonatype.aether.version < plexus.core
[DEBUG] Imported: org.sonatype.aether.* < plexus.core
[DEBUG] Imported: org.sonatype.aether.artifact < plexus.core
[DEBUG] Imported: org.apache.maven.* < plexus.core
[DEBUG] Imported: org.apache.maven.project < plexus.core
[DEBUG] Imported: org.sonatype.aether.repository < plexus.core
[DEBUG] Imported: org.sonatype.aether.impl < plexus.core
[DEBUG] Imported: org.apache.maven.exception < plexus.core
[DEBUG] Imported: org.apache.maven.plugin < plexus.core
[DEBUG] Imported: org.sonatype.aether.collection < plexus.core
[DEBUG] Imported: org.codehaus.plexus.* < plexus.core
[DEBUG] Imported: org.codehaus.plexus.logging < plexus.core
[DEBUG] Imported: org.apache.maven.profiles < plexus.core
[DEBUG] Imported: org.sonatype.aether.metadata < plexus.core
[DEBUG] Imported: org.sonatype.aether.spi < plexus.core
[DEBUG] Imported: org.codehaus.plexus.util.xml.pull.XmlPullParserException < plexus.core
[DEBUG] Imported: org.apache.maven.wagon.* < plexus.core
[DEBUG] Imported: org.sonatype.aether.graph < plexus.core
[DEBUG] Imported: org.apache.maven.rtinfo < plexus.core
[DEBUG] Imported: org.sonatype.aether.installation < plexus.core
[DEBUG] Imported: org.apache.maven.monitor < plexus.core
[DEBUG] Imported: org.sonatype.aether.transfer < plexus.core
[DEBUG] Imported: org.codehaus.plexus.context < plexus.core
[DEBUG] Imported: org.apache.maven.wagon.observers < plexus.core
[DEBUG] Imported: org.apache.maven.wagon.resource < plexus.core
[DEBUG] Imported: org.sonatype.aether.deployment < plexus.core
[DEBUG] Imported: org.apache.maven.model < plexus.core
[DEBUG] Imported: org.codehaus.plexus.util.xml.Xpp3Dom < plexus.core
[DEBUG] Imported: org.apache.maven.artifact < plexus.core
[DEBUG] Imported: org.apache.maven.toolchain < plexus.core
[DEBUG] Imported: org.codehaus.plexus.util.xml.pull.XmlSerializer < plexus.core
[DEBUG] Imported: org.apache.maven.settings < plexus.core
[DEBUG] Imported: org.apache.maven.wagon.authorization < plexus.core
[DEBUG] Imported: org.apache.maven.wagon.events < plexus.core
[DEBUG] Imported: org.apache.maven.wagon.authentication < plexus.core
[DEBUG] Imported: org.apache.maven.reporting < plexus.core
[DEBUG] Imported: org.apache.maven.wagon.repository < plexus.core
[DEBUG] Imported: org.apache.maven.configuration < plexus.core
[DEBUG] Imported: org.codehaus.plexus.classworlds < plexus.core
[DEBUG] Imported: org.codehaus.classworlds < plexus.core
[DEBUG] Imported: org.codehaus.plexus.util.xml.pull.XmlPullParser < plexus.core
[DEBUG] Imported: org.apache.maven.classrealm < plexus.core
[DEBUG] Imported: org.sonatype.aether.resolution < plexus.core
[DEBUG] Imported: org.apache.maven.execution < plexus.core
[DEBUG] Imported: org.apache.maven.wagon.proxy < plexus.core
[DEBUG] Imported: org.codehaus.plexus.container < plexus.core
[DEBUG] Imported: org.codehaus.plexus.component < plexus.core
[DEBUG] Populating class realm maven.api
[DEBUG] org.codehaus.mojo:exec-maven-plugin:jar:1.2.1:
[DEBUG] org.apache.maven:maven-toolchain:jar:1.0:compile
[DEBUG] org.apache.maven:maven-project:jar:2.0.6:compile
[DEBUG] org.apache.maven:maven-settings:jar:2.0.6:compile
[DEBUG] org.apache.maven:maven-profile:jar:2.0.6:compile
[DEBUG] org.apache.maven:maven-plugin-registry:jar:2.0.6:compile
[DEBUG] org.apache.maven:maven-model:jar:2.0.6:compile
[DEBUG] org.apache.maven:maven-artifact:jar:2.0.6:compile
[DEBUG] org.apache.maven:maven-artifact-manager:jar:2.0.6:compile
[DEBUG] org.apache.maven:maven-repository-metadata:jar:2.0.6:compile
[DEBUG] org.apache.maven:maven-core:jar:2.0.6:compile
[DEBUG] org.apache.maven:maven-plugin-parameter-documenter:jar:2.0.6:compile
[DEBUG] org.apache.maven.reporting:maven-reporting-api:jar:2.0.6:compile
[DEBUG] org.apache.maven.doxia:doxia-sink-api:jar:1.0-alpha-7:compile
[DEBUG] org.apache.maven:maven-error-diagnostics:jar:2.0.6:compile
[DEBUG] commons-cli:commons-cli:jar:1.0:compile
[DEBUG] org.apache.maven:maven-plugin-descriptor:jar:2.0.6:compile
[DEBUG] org.codehaus.plexus:plexus-interactivity-api:jar:1.0-alpha-4:compile
[DEBUG] org.apache.maven:maven-monitor:jar:2.0.6:compile
[DEBUG] classworlds:classworlds:jar:1.1:compile
[DEBUG] org.apache.maven:maven-plugin-api:jar:2.0.6:compile
[DEBUG] org.codehaus.plexus:plexus-utils:jar:2.0.5:compile
[DEBUG] org.codehaus.plexus:plexus-container-default:jar:1.0-alpha-9:compile
[DEBUG] junit:junit:jar:3.8.2:test (scope managed from compile) (version managed from 3.8.1)
[DEBUG] org.apache.commons:commons-exec:jar:1.1:compile
[DEBUG] Created new class realm plugin>org.codehaus.mojo:exec-maven-plugin:1.2.1
[DEBUG] Importing foreign packages into class realm plugin>org.codehaus.mojo:exec-maven-plugin:1.2.1
[DEBUG] Imported: < maven.api
[DEBUG] Populating class realm plugin>org.codehaus.mojo:exec-maven-plugin:1.2.1
[DEBUG] Included: org.codehaus.mojo:exec-maven-plugin:jar:1.2.1
[DEBUG] Included: org.apache.maven.reporting:maven-reporting-api:jar:2.0.6
[DEBUG] Included: org.apache.maven.doxia:doxia-sink-api:jar:1.0-alpha-7
[DEBUG] Included: commons-cli:commons-cli:jar:1.0
[DEBUG] Included: org.codehaus.plexus:plexus-interactivity-api:jar:1.0-alpha-4
[DEBUG] Included: org.codehaus.plexus:plexus-utils:jar:2.0.5
[DEBUG] Included: org.apache.commons:commons-exec:jar:1.1
[DEBUG] Excluded: org.apache.maven:maven-toolchain:jar:1.0
[DEBUG] Excluded: org.apache.maven:maven-project:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-settings:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-profile:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-plugin-registry:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-model:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-artifact:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-artifact-manager:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-repository-metadata:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-core:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-plugin-parameter-documenter:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-error-diagnostics:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-plugin-descriptor:jar:2.0.6
[DEBUG] Excluded: org.apache.maven:maven-monitor:jar:2.0.6
[DEBUG] Excluded: classworlds:classworlds:jar:1.1
[DEBUG] Excluded: org.apache.maven:maven-plugin-api:jar:2.0.6
[DEBUG] Excluded: org.codehaus.plexus:plexus-container-default:jar:1.0-alpha-9
[DEBUG] Excluded: junit:junit:jar:3.8.2
[DEBUG] Configuring mojo org.codehaus.mojo:exec-maven-plugin:1.2.1:java from plugin realm ClassRealm[plugin>org.codehaus.mojo:exec-maven-plugin:1.2.1, parent: sun.misc.Launcher$AppClassLoader@a14482]
[DEBUG] Configuring mojo 'org.codehaus.mojo:exec-maven-plugin:1.2.1:java' with basic configurator -->
[DEBUG] (f) arguments = []
[DEBUG] (f) classpathScope = runtime
[DEBUG] (f) cleanupDaemonThreads = false
[DEBUG] (f) daemonThreadJoinTimeout = 15000
[DEBUG] (f) includePluginDependencies = false
[DEBUG] (f) includeProjectDependencies = true
[DEBUG] (f) keepAlive = false
[DEBUG] (f) killAfter = -1
[DEBUG] (f) localRepository = id: local
url: file:///root/.m2/repository/
layout: none
[DEBUG] (f) mainClass = Launcher
[DEBUG] (f) pluginDependencies = [org.codehaus.mojo:exec-maven-plugin:maven-plugin:1.2.1:, org.apache.maven.reporting:maven-reporting-api:jar:2.0.6:compile, org.apache.maven.doxia:doxia-sink-api:jar:1.0-alpha-7:compile, commons-cli:commons-cli:jar:1.0:compile, org.codehaus.plexus:plexus-interactivity-api:jar:1.0-alpha-4:compile, org.codehaus.plexus:plexus-utils:jar:2.0.5:compile, org.apache.commons:commons-exec:jar:1.1:compile]
[DEBUG] (f) project = MavenProject: alexa-skills-kit-samples:helloworld:1.0 @ /root/samples/skill-samples-java-master/helloworld/pom.xml
[DEBUG] (f) remoteRepositories = [ id: alexa-skills-kit-repo
url: file:///root/samples/skill-samples-java-master/helloworld/repo
layout: default
snapshots: [enabled => true, update => daily]
releases: [enabled => true, update => daily]
, id: central
url: https://repo.maven.apache.org/maven2
layout: default
snapshots: [enabled => false, update => daily]
releases: [enabled => true, update => daily]
]
[DEBUG] (f) skip = false
[DEBUG] (f) stopUnresponsiveDaemonThreads = false
[DEBUG] (s) key = javax.net.ssl.keyStore
[DEBUG] (s) value = /root/java-keystore.jks
[DEBUG] (s) key = javax.net.ssl.keyStorePassword
[DEBUG] (s) value = Felix123
[DEBUG] (s) key = com.amazon.speech.speechlet.servlet.disableRequestSignatureCheck
[DEBUG] (s) value = true
[DEBUG] (s) key = com.amazon.speech.speechlet.servlet.supportedApplicationIds
[DEBUG] (s) key = com.amazon.speech.speechlet.servlet.timestampTolerance
[DEBUG] (f) systemProperties = [org.codehaus.mojo.exec.Property@7b159b, org.codehaus.mojo.exec.Property@5d9a50, org.codehaus.mojo.exec.Property@957c0f, org.codehaus.mojo.exec.Property@13a5f75, org.codehaus.mojo.exec.Property@1cb4004]
[DEBUG] -- end configuration --
[DEBUG] Invoking : Launcher.main()
[DEBUG] Plugin Dependencies will be excluded.
[DEBUG] Project Dependencies will be included.
[DEBUG] Collected project artifacts [com.amazon.alexa:alexa-skills-kit:jar:1.6.0:compile, org.eclipse.jetty:jetty-server:jar:9.0.6.v20130930:compile, org.eclipse.jetty.orbit:javax.servlet:jar:3.0.0.v201112011016:compile, org.eclipse.jetty:jetty-http:jar:9.0.6.v20130930:compile, org.eclipse.jetty:jetty-util:jar:9.0.6.v20130930:compile, org.eclipse.jetty:jetty-io:jar:9.0.6.v20130930:compile, org.eclipse.jetty:jetty-servlet:jar:9.0.6.v20130930:compile, org.eclipse.jetty:jetty-security:jar:9.0.6.v20130930:compile, log4j:log4j:jar:1.2.17:compile, org.slf4j:slf4j-api:jar:1.7.10:compile, org.slf4j:slf4j-log4j12:jar:1.7.10:compile, org.apache.commons:commons-lang3:jar:3.4:compile, org.apache.directory.studio:org.apache.commons.io:jar:2.4:compile, commons-io:commons-io:jar:2.4:compile, com.amazonaws:aws-lambda-java-core:jar:1.0.0:compile, com.amazonaws:aws-lambda-java-log4j:jar:1.0.0:compile, com.amazonaws:aws-java-sdk-dynamodb:jar:1.9.40:compile, com.amazonaws:aws-java-sdk-s3:jar:1.9.40:compile, com.amazonaws:aws-java-sdk-kms:jar:1.9.40:compile, com.amazonaws:aws-java-sdk-core:jar:1.9.40:compile, commons-logging:commons-logging:jar:1.1.3:compile, org.apache.httpcomponents:httpclient:jar:4.3.4:compile, org.apache.httpcomponents:httpcore:jar:4.3.2:compile, commons-codec:commons-codec:jar:1.6:compile, com.fasterxml.jackson.core:jackson-databind:jar:2.3.2:compile, com.fasterxml.jackson.core:jackson-annotations:jar:2.3.0:compile, com.fasterxml.jackson.core:jackson-core:jar:2.3.2:compile, joda-time:joda-time:jar:2.9.9:compile]
[DEBUG] Collected project classpath [/root/samples/skill-samples-java-master/helloworld/target/classes]
[DEBUG] Adding to classpath : file:/root/samples/skill-samples-java-master/helloworld/target/classes/
[DEBUG] Adding project dependency artifact: alexa-skills-kit to classpath
[DEBUG] Adding project dependency artifact: jetty-server to classpath
[DEBUG] Adding project dependency artifact: javax.servlet to classpath
[DEBUG] Adding project dependency artifact: jetty-http to classpath
[DEBUG] Adding project dependency artifact: jetty-util to classpath
[DEBUG] Adding project dependency artifact: jetty-io to classpath
[DEBUG] Adding project dependency artifact: jetty-servlet to classpath
[DEBUG] Adding project dependency artifact: jetty-security to classpath
[DEBUG] Adding project dependency artifact: log4j to classpath
[DEBUG] Adding project dependency artifact: slf4j-api to classpath
[DEBUG] Adding project dependency artifact: slf4j-log4j12 to classpath
[DEBUG] Adding project dependency artifact: commons-lang3 to classpath
[DEBUG] Adding project dependency artifact: org.apache.commons.io to classpath
[DEBUG] Adding project dependency artifact: commons-io to classpath
[DEBUG] Adding project dependency artifact: aws-lambda-java-core to classpath
[DEBUG] Adding project dependency artifact: aws-lambda-java-log4j to classpath
[DEBUG] Adding project dependency artifact: aws-java-sdk-dynamodb to classpath
[DEBUG] Adding project dependency artifact: aws-java-sdk-s3 to classpath
[DEBUG] Adding project dependency artifact: aws-java-sdk-kms to classpath
[DEBUG] Adding project dependency artifact: aws-java-sdk-core to classpath
[DEBUG] Adding project dependency artifact: commons-logging to classpath
[DEBUG] Adding project dependency artifact: httpclient to classpath
[DEBUG] Adding project dependency artifact: httpcore to classpath
[DEBUG] Adding project dependency artifact: commons-codec to classpath
[DEBUG] Adding project dependency artifact: jackson-databind to classpath
[DEBUG] Adding project dependency artifact: jackson-annotations to classpath
[DEBUG] Adding project dependency artifact: jackson-core to classpath
[DEBUG] Adding project dependency artifact: joda-time to classpath
[DEBUG] joining on thread Thread[Launcher.main(),5,Launcher]
[WARNING]
java.lang.ClassNotFoundException: Launcher
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:285)
at java.lang.Thread.run(Thread.java:748)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:46.627s
[INFO] Finished at: Fri Oct 27 19:09:37 UTC 2017
[INFO] Final Memory: 7M/17M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli) on project helloworld: An exception occured while executing the Java class. Launcher -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli) on project helloworld: An exception occured while executing the Java class. Launcher
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. Launcher
at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:352)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
... 19 more
Caused by: java.lang.ClassNotFoundException: Launcher
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:285)
at java.lang.Thread.run(Thread.java:748)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
and the Pom.xml:
http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
alexa-skills-kit-samples
helloworld
jar
1.0
helloworld
http://developer.amazon.com/ask
<repositories>
<repository>
<id>alexa-skills-kit-repo</id>
<url>file://${project.basedir}/repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.amazon.alexa</groupId>
<artifactId>alexa-skills-kit</artifactId>
<version>1.6.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.0.6.v20130930</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.0.6.v20130930</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.10</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>2.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-log4j</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>1.9.40</version>
</dependency>
</dependencies>
<properties>
<property name="disableRequestSignatureCheck" value="false"/>
<property name="supportedApplicationIds" value=""/>
<property name="timestampTolerance" value="150"/>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src/resources</directory>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>Launcher</mainClass>
<systemProperties>
<systemProperty>
<key>javax.net.ssl.keyStore</key>
<value>/root/java-keystore.jks</value>
</systemProperty>
<systemProperty>
<key>javax.net.ssl.keyStorePassword</key>
<value>Felix123</value>
</systemProperty>
<systemProperty>
<key>com.amazon.speech.speechlet.servlet.disableRequestSignatureCheck</key>
<value>${disableRequestSignatureCheck}</value>
</systemProperty>
<systemProperty>
<key>com.amazon.speech.speechlet.servlet.supportedApplicationIds</key>
<value>${supportedApplicationIds}</value>
</systemProperty>
<systemProperty>
<key>com.amazon.speech.speechlet.servlet.timestampTolerance</key>
<value>${timestampTolerance}</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46982459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Keep icon bar floated right and wrap text around I have a little header bar in html/css where there are a couple icons floated to the right side. I want them to remain in position and have the title (on the left) just wrap below if the area gets too small on the right side. Right now, my html looks like so (using bootstrap) :
<div class="activity-panel-item--header">
<div class="col-sm-8"><p>02 Development, LLC v. 607 South Park, LLC </p></div>
<div class="col-sm-4"><span class="icon icon-trash-o pull-right"></span><span class="icon icon-cog2 pull-right"></span><span class="icon icon-pencil3 pull-right"></span></div>
</div>
So I have a col-sm-8 and col-sm-4. This will not work in the long run because col-sm-4 is too small in certain sizes, so I need to make the right column with the icon have a set width (140px lets say). So if a set a min-width on the right side it's going break on smaller sizes.
What I am wondering if, is there a way to let that title on the left side in the col-sm-8 move around the set width buttons on the right side when responsive (i basically want the buttons to stay in the same place the whole time). Something like if the buttons on the right were absolutely position but not out of the flow so the text reacts to it.
Here is a fiddle I was fooling with https://jsfiddle.net/DTcHh/24085/
EDIT
So I improvised a solution by doing the following :
- taking the right icon-bar element out of the dom flow by absolutely positioning it and giving it a set with
- adding the same width as padding to the element wrapping both the left and the right items
I could then just do away with the col's all together. The code looks like so :
HTML:
<div class="activity-panel-item col-md-12">
<div class="activity-panel-item--header">
<p>02 Development, LLC v. 607 South Park, LLC </p>
<div class="activity-panel-item--header--iconbar">
<span class="icon icon-trash-o pull-right">1</span><span class="icon icon-cog2 pull-right">2</span><span class="icon icon-pencil3 pull-right">3</span>
</div>
</div>
<div class="activity-panel-item--body">
<p>test 123345.</p>
<h3></h3>
<p>cases</p>
</div>
</div>
CSS:
.activity-panel-item {
height: 100%;
padding: 0;
}
.activity-panel-item--header {
position: fixed;
width: 100%;
top: 0;
left: 0;
padding: 12px 125px 12px 12px;
min-height: 50px;
background-color: rgba(0, 0, 0, 0.8);
}
.activity-panel-item--header p {
color: #fff;
}
.activity-panel-item--header .icon {
cursor: pointer;
color: #fff;
margin: 0px 12px;
font-size: 20px;
}
.activity-panel-item--body {
overflow-y: auto;
padding: 10px 20px;
display: block;
width: 100%;
height: 100%
}
.activity-title-input {
width: 100%;
}
.activity-panel-item--header--iconbar {
display: block;
float: right;
top: 10px;
right: 10px;
width: 125px;
min-height: 50px;
height: auto;
position: absolute;
}
See working fiddle: https://jsfiddle.net/DTcHh/24114/
Any and all input would be helpful, or if anyone has a different working approach that would be great also. Thanks!
A: You can do it without bootstrap col-*-* and by giving the explicit width to both divs, plus little extra style to your icon bar.
Updated Code
<div class="activity-panel-item--header">
<div class="pull-left" style="width: 75%;">
<p>02 Development, LLC v. 607 South Park, LLC </p>
</div>
<div class="pull-right" style="position: absolute; right: 0px; min-width: 25%;"><span class="icon icon-trash-o pull-right">1</span><span class="icon icon-cog2 pull-right">2</span><span class="icon icon-pencil3 pull-right">3</span></div>
</div>
jsFiddle
EDIT 1
If you think deeply according to this solution we both are at same point. Let me explain, I am giving minimum width 25% to icon bar and 75% width to left element. That mean depending on situation width of icon bar can be increase but it must be at least 25% of total screen or container and width of left element is 75% that can be decrease depending on situation.
And you are giving width 125px or any to icon bar that means it can be increase or decrease depending on situation but the original is 125px
Here the situation I mean area and screen resolution. If icon are larger and not fit in 25% then this width can be increase and left element can be decrease same is your edited case if icon bar not fit in 125px then this width can be increase because we are not mentioning the maximum width to icon bar or minimum width to left element.
.
EDIT 2
I hope this is not illegal on stackoverflow to edit answer as many time as I need.
Apart from coding let’s do some math. Suppose we have 3 icon of (32x32) each. So the total width of icon wrapper will (32+32+32) 96px add little margin of 12px to each icon (12x3=36) on right side for beauty. Now the wrapper width is 96+36 = 132px. And we are on device that has width of 400px. My icon wrapper is (25%) 100px of 400px (device width) and your wrapper is 125px. I am saying OK browser minimum width of icon wrapper is 100px but if icons are larger and not fit in 100px you can increase this width according to you need, In this case it will increase 100px to 132px or any. But I don't want to break these icons to next line. They should be display in their original size and style (32x32) plus margin. You can break left content (text) to wrap around these icons but don't break the icons itself. They should retain their original size. No matter what ever device width is. Browser, Please don't decrease the icon size just increase wrapper width.
And your 125px is less than 132px. So your wrapper will break and one of its icon will move to next line. Until you have to go to you CSS and explicitly wrote 132px or any in width. And what if after one month your boss said please place icon of 40x40 and after 3 month and so on...?
Try it, place larger icons and see what happens to your width: 125px.
A: Unless I am totally misunderstanding you.. here is a easy method. Too much CSS
classes so I used my own but you get the concept.
<div class="top">
<div class="content1">
<p>02 Development, LLC v. 607 South Park, LLC </p>
</div>
<div class="content2">
<span>1</span>
<span>2</span>
<span>3</span>
</div>
</div>
<div class="content3">
<p>test 123345.</p>
<h3>Nothing Here</h3>
<p>cases</p>
</div>
Demo: https://jsfiddle.net/norcaljohnny/ovo83p5k/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39153253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Displaying malformed html with twig Assume we have a string
$mystring = "<b> Hello"
How can I display this string using twig while preventing leaking html tags? Or in other word how can I make twig to close tags automatically if they are still open?
I guess {{ mystring | raw }} just prints raw text without verifying / purifying.
A: sw_sanitize does this already.
{{ '<b> hello' | sw_sanitize }}
Produces:
<b> hello</b
Internally \HTMLPurifier::purify is used, which
Filters an HTML snippet/document to be XSS-free and standards-compliant.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71459150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Compare Checkbox List values for Nothing Checked through LINQ I'm using below code for filtering on the basis of Checkboxlist but, filter is not working if I don't select anything. It has to show all the values if I don't checked any value.
Below is the code for that :
var selectedIds = chklstDepartment.Items.Cast<ListItem>().Where(item => item.Selected).Select(item => item.Value).ToArray();
List<LessonLearnDetails> objLessonDetails = objLessonDashboard.getLessonLearntDetails();
var searchData = objLessonDetails.Where(i => (ddlAsset.SelectedValue == "0") || (i._Asset.AssetID == ddlAsset.SelectedValue))
.Where(i => (ddlAuditType.SelectedValue == "0") || (i._Audit.AuditTypeID == ddlAuditType.SelectedValue))
.Where(i => (chklstDepartment.SelectedValue == "0") || (selectedIds.Contains(i._Department.DepartmentID)))
.Where(i => (ddlCategory.SelectedValue == "0") || (i._Category.CategoryID == ddlCategory.SelectedValue))
.Where(i => (ddlStartYear.SelectedItem.Text == "--Select All--") || (Convert.ToInt32(i._Year.StartYear) >= Convert.ToInt32(ddlStartYear.SelectedItem.Text)))
.Where(i => (ddlEndYear.SelectedItem.Text == "--Select All--") || (Convert.ToInt32(i._Year.EndYear) <= Convert.ToInt32(ddlEndYear.SelectedItem.Text)))
.Distinct().ToList();
BindGrid(searchData);
A: Use "" in place of "0".
chklstDepartment.SelectedValue == ""
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44922008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I create views with dynamic content in iOS? I' m encountered with a problem because of my lack of knowledge of iOS platform I think.I have a view controller User Profile. The main view has next structure: ScrollView which contains one subview and this UIView has 7 UIViews with UILabels, UItextViews, UIImageViews, etc. each of them displays specific info about user. The problem - data for this views is fetched from the server and it can be different. E.g I have a subview Education, it contains next info: name of the institute, degree, years of learning, etc. But one user can have several educations. So the size of this view can be dynamic. But i can't simply change the view size with view.frame = CGRectMake because under it I have a view job experience and etc. Or for example professional skills view: it can be one skill and it can be one hundred skills for one user -so I need to change the size of this view but under it I have another view so i need to move it and so on and so forth. So the question what is the correct way of dealing with this situation? I understood that I can't just change view frames with view.frame= CGRectMake() - because it is too much work and it is a stupid approach I think. I know there must be some more straightforward way for this very common problem, may be autolayout or something else? Anyway I hope for some help and advice of how can I make views with dynamic content.
A: I really don't know why you said "I can't just change view frames". Of course you can!
The approach I always take to this scenario (where your view's height is variable) is to declare a yOffset property and based on this I place my content at the right y position.
@property (nonatomic, assign) int yOffset;
Then inside the init method I initialize this property to either 0 or some predefined initial margin.
_yOffset = TOP_MARGIN;
Then consider the following scenario: a user profile with n number of skills. This is how you would use the yOffset property.
for (int i=0; i<n; ++i)
{
// place the skillView at the right 'y' position
SkillView *skillView = [[SkillView alloc] initWithFrame:CGRectMake(0,self.yOffset,300,50)];
// configure the skillView here
[self.view addSubview:skillView];
// Don't forget it has to be "+=" because you have to keep track of the height!!!
self.yOffset += skillView.frame.size.height + MARGIN_BETWEEN_SKILLS;
}
And then imagine the user profile has c number of Education entries; same thing:
for (int i=0; i<c; ++i)
{
// place the educationView at the right 'y' position
EducationView *educationView = [[EducationView alloc] initWithFrame:CGRectMake(0,self.yOffset,300,50)];
// configure the educationView here
[self.view educationView];
// Don't forget it has to be "+=" because you have to keep track of the height!!!
self.yOffset += educationView.frame.size.height + MARGIN_BETWEEN_EDUCATIONS;
}
Finally, when all your subviews have been added you have to change the frame of the containing view. (Because when you created it you couldn't know upfront how tall it was going to be)
CGRect viewFrame = self.view.frame;
viewFrame.size.height = self.yOffset + BOTTOM_MARGIN;
self.view.frame = viewFrame;
And that's it.
Hope this helps!
A: As you've stated, manually updating the frames is a lot of work and is the old way of doing things. The new better way as you've also said is to use auto layout. Describing how to use auto layout to position your views would require more specific information on how you want it to look but there are some awesome tutorials out there on the web! Here's one of many:
Ray Wenderlich autolayout in iOS 7 part 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19595590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: [wso2][APIM 3.2] conditional engagement of handler does not work I try to write my own WSO2 3.2 APIM Handler.
My purpose is :
*
*engage Handler when a dedicated property is set on API
*consume the request and use the binary response to decrypt part of it
*change the content type of the response after decryption
I successfuly write my handler and modify the velocity_template.xml as follow (following the documentation):
#if($apiObj.additionalProperties.get('encrypted') == "true"))
<handler class="org.rudi.wso2.mediation.EncryptedMediaHandler">
<property name="encryptedMimeType" value="$apiObj.additionalProperties.get('encrypted_mime_type')"/>
<property name="mimeType" value="$apiObj.additionalProperties.get('mime_type')"/>
<property name="providerUuid" value="dummy"/>
</handler>
#end
But this does not work and the handler is not engaged.
If I remove the #if condition the handler is engaged but the properties are not interpreted (for exemple the "mimeType" field is explicitly set to "$apiObj.additionalProperties.get('mime_type')" and not to the value of the additionnalProperty set on API.
What is wrong ?
How could I use the additionnal properties added on API ?
Next when the Handler is called, I did not find any way to read the response of the endpoint.
I find code to change the response ou the response status code to write fault for exemple
But I did not find a way to read the binary response send by my endpoint to work on it.
Help will be appreciated!
UPDATED
For the second part of the question, I create a method as follow:
private void replaceBody(SOAPBody body) throws IOException {
OMElement element = body.getFirstElement();
if (element.getLocalName().equalsIgnoreCase(BINARY_LOCAL_NAME)) {
OMNode subChild = element.getFirstOMChild();
if (subChild instanceof OMText && ((OMText) subChild).isBinary()) {
OMText textNode = ((OMText) subChild);
DataHandler originalDataHandler = (DataHandler) textNode.getDataHandler();
InputStream modifiedInputStream = modify(originalDataHandler.getInputStream());
DataHandler newDataHandler = new DataHandler(new StreamingOnRequestDataSource(modifiedInputStream ));
OMText newTextNode = body.getOMFactory().createOMText(newDataHandler, true);
textNode.insertSiblingBefore(newTextNode);
textNode.detach();
}
}
}
And I lookup for SOAPBody as follow :
org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext)
.getAxis2MessageContext();
RelayUtils.buildMessage(axis2MC, true);
axis2MC.setProperty(RelayConstants.FORCE_RESPONSE_EARLY_BUILD, Boolean.TRUE);
SOAPBody body = axis2MC.getEnvelope().getBody();
I test the behaviour on small file but I think we need to do more stuff to handle big file ou chunked api.
Any advice?
A: Regarding velocity_template.xml & API Properties Configurations
The velocity_template.xml file is used to construct the API Synapse Artifacts to deploy them in the Gateway. As it is a common template file, you have to place your conditions and customizations in the correct sections of the template to reflect in the Synapse Artifact.
If you are trying to publish a REST API, then place your code block after this section in the velocity_template.xml
#foreach($handler in $handlers)
<handler xmlns="http://ws.apache.org/ns/synapse" class="$handler.className">
#if($handler.hasProperties())
#set ($map = $handler.getProperties() )
#foreach($property in $map.entrySet())
<property name="$!property.key" value="$!property.value"/>
#end
#end
</handler>
#end
<!-- place your block here -->
This makes sure, that your handler is engaged after all mandatory Handlers of the API Managers are engaged. If you want to engage your handler in the middle, then add a condition within #foreach block to append your handler. You can follow this doc for more detailed information.
Once the velocity_template.xml changes are made, re-publish the API by selecting the Gateway environments to deploy the updated Synapse Artifacts. If it is a distributed environment, make sure to update the velocity_template.xml of the Publisher node.
Also, check for any typos in your code block: I see an extra ) at the end of the #if condition.
#if($apiObj.additionalProperties.get('encrypted') == "true"))
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72698024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stanford Parser for Python: Output Format I am currently using the Python interface for the Stanford Parser.
from nltk.parse.stanford import StanfordParser
import os
os.environ['STANFORD_PARSER'] ='/Users/au571533/Downloads/stanford-parser-full-2016-10-31'
os.environ['STANFORD_MODELS'] = '/Users/au571533/Downloads/stanford-parser-full-2016-10-31'
parser=StanfordParser(model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz")
new=list(parser.raw_parse("The young man who boarded his usual train that Sunday afternoon was twenty-four years old and fat. "))
print new
The output I get looks something like this:
[Tree('ROOT', [Tree('S', [Tree('NP', [Tree('NP', [Tree('DT', ['The']), Tree('JJ', ['young']), Tree('NN', ['man'])]), Tree('SBAR', [Tree('WHNP', [Tree('WP', ['who'])]), Tree('S', [Tree('VP', [Tree('VBD', ['boarded']), Tree('NP', [Tree('PRP$', ['his']), Tree('JJ', ['usual']), Tree('NN', ['train'])]), Tree('NP', [Tree('DT', ['that']), Tree('NNP', ['Sunday'])])])])])]), Tree('NP', [Tree('NN', ['afternoon'])]), Tree('VP', [Tree('VBD', ['was']), Tree('NP', [Tree('NP', [Tree('JJ', ['twenty-four']), Tree('NNS', ['years'])]), Tree('ADJP', [Tree('JJ', ['old']), Tree('CC', ['and']), Tree('JJ', ['fat'])])])]), Tree('.', ['.'])])])]
However, I only need the part of speech labels, therefore I'd like to have an output in a format that looks like word/tag.
In java it is possible to specify -outputFormat 'wordsAndTags' and it gives exactly what I want. Any hint on how to implement this in Python?
Help would be GREATLY appreciated.
Thanks!
PS: Tried to use the Stanford POSTagger but it is by far less accurate on some of the words I'm interested in.
A: If you look at the NLTK classes for the Stanford parser, you can see that the the raw_parse_sents() method doesn't send the -outputFormat wordsAndTags option that you want, and instead sends -outputFormat Penn.
If you derive your own class from StanfordParser, you could override this method and specify the wordsAndTags format.
from nltk.parse.stanford import StanfordParser
class MyParser(StanfordParser):
def raw_parse_sents(self, sentences, verbose=False):
"""
Use StanfordParser to parse multiple sentences. Takes multiple sentences as a
list of strings.
Each sentence will be automatically tokenized and tagged by the Stanford Parser.
The output format is `wordsAndTags`.
:param sentences: Input sentences to parse
:type sentences: list(str)
:rtype: iter(iter(Tree))
"""
cmd = [
self._MAIN_CLASS,
'-model', self.model_path,
'-sentences', 'newline',
'-outputFormat', 'wordsAndTags',
]
return self._parse_trees_output(self._execute(cmd, '\n'.join(sentences), verbose))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41522476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTML in MySQL Database -- Best Practices I'm beginning to create a system whereby I (as the only user at present) will be loading a dynamically created PHP page which has a <table> in it. I then will be grabbing the HTML of that <table> and saving it to be displayed to other users in a separate area of the website.
My Questions: What are some best practices to follow for this kind of thing? Saving the HTML as TEXT or LONGTEXT in MySQL? BLOB? Maybe even saving this data as a .txt file which uses PHP include() to include it into the file which displays it to users?
I'm not really sure of the best approach for this kind of thing, and thus the barrage of questions. I'm also not very familiar with creating databases and therefore, I'm not knowledgeable as to their strengths/weaknesses. It seems like using a MySQL database for this is the way to go, but I'm not married to it.
Note #1: The HTML must be preserved in it's entirety. So something like <div>Let's use blue for this.</div> can't end up coming out as <div>Let\'s use blue for this.</div>.
Note #2: The table I'm saving from gets randomly generated (including number of rows/columns) each time. So, I need all data within the table, including all <tr>'s and <td>'s.
A: Both MySQL and HTML files can work. Your choice should depend on how simple the data is, and how much you are storing.
Some considerations:
*
*Speed. The HTML files and include() approach is going to be faster. The file system is the fastest, simplest form of data persistence.
*Horizontal scalability. If you adopt the file system approach, you are more or less tied to the disk on that machine. With a separate database engine, you have the future option of running the database on separate cluster servers on the network.
*Meta Data. Do you need to store things like time of creation, which user created the HTML, how many times it has been viewed by other users? If so, you probably only have one realistic choice - a "proper" database. This can be MySQL or perhaps one of the NoSQL solutions.
*Data Consumption. Do you show the table in its entirety to other users? Or do you show selected parts of it? Possibly even different parts to different users? This impacts how you store data - the entire table as ONE entity, or each row as an entity, or each individual cell.
*TEXT or LONGTEXT? Of course only applicable if you're going with SQL. The only way to answer this is to know how many bytes you are expecting to store per "HTML fragment". Note that your character encoding also impacts the number of bytes stored. Refer to: TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes
Also note that in MySQL, each TEXT/LONGTEXT may also result in an I/O to the disk.
As for the concern:
The HTML must be preserved in its entirety.
As long as you don't escape the HTML at any point, you should be fine. At first glance, this violates a security best practice, but if you think about it, "not escaping HTML" is exactly what you want to do. The practice of escaping HTML output only helps to eliminate HTML syntax being parsed as HTML tags (potential malicious), but in your case, you don't want HTML syntax eliminated at all - you intentionally want <td> to be parsed into an actual HTML table cell. So do not escape anything and the example you gave should never occur.
Just note: although you do not HTML-escape the output, you still should filter your inputs. In essence, this means: before writing to your DB, check that the user input is indeed HTML. To enhance your application's security, it may also be wise to define rules for what can be stored in those table cells - perhaps no <iframe> or <a> allowed, no style attributes allowed etc. Also, watch out for SQL injection - use PDO and prepared statements if you're going PHP + MySQL.
A: Live by this rule: PHP is for formatting; MySQL is for data.
PHP is for building HTML. MySQL is useful as a persistent store for data from which PHP can build HTML.
I have built several systems with Apache+PHP+MySQL. Each page is PHP-generated HTML. I do not store <html tags> in MySQL, only data.
Some of my pages perform one SELECT; many pages perform a dozen or more. The performance is just fine. I use PHP subroutines to build <table>s. I construct style variations based on the data.
Let's use blue for this might be in some database table; PHP code would add the <div> tags around it.
A: Someone is going to come up with the php to do this correctly, but here's an idea.
*
*Learning a database is a separate exercise that should not be mixed with learning anything else. Leave MySQL out of this. If you want to go back and redo the project with it as a learning exercise, after you've spent some time learning the basics, go ahead.
*What you are going to want to do is to generate your table as a separate .php fragment, and then save it to the disk under a unique name that you can use to find it again later (maybe it is a date/time, maybe a number that keeps increasing, maybe a different way). After it is saved, you can then include it into your page as well as the other pages you want to include it. Getting that unique name may be a challenge, but that is a different question (and if you look around, probably already has an answer somewhere).
*If you know .php enough, the rest should be self explanatory. If you don't, then now is an excellent time to learn. If you have further questions, you can search stack overflow or google for the answers. Chances are, the answers are out there.
*Since I do know databases, there could be an interesting discussion that the other posters are trying to have with you about how to store the data. However, that discussion will only be really useful to you once you understand what we are trying to talk about. Besides, I bet it has already been asked at least once.
So try out that plan and come back and post how you did it for future readers. Happy coding.
A: What you want to do is absolutely not Three-tier architecture like said Rick James, you are mixing data and presentation.
But like in everything, it is up what you want to do and your strategy.
*
*Let say, if you are looking to build an application with specific mould of page with a specific space for an image with a specific data at this place and you want to maintain this same architecture for years, you should separate data and presentation. Most of the time, big companies, big applications are looking for this approch. Even if I know some big companies application, we have stored some HTML code in database.
*Now, if you want to be free to change every page design quickly, you can have HTML tag in your database.
For example, Wordpress has a lot of HTML tag in its table for years and it is still maintained and used by a lot of people. Saving HTML in database? According to your needs/strategy, it does not schock me.
*And for your information, in Wordpress a HTML post is saved as LONGTEXT.
*In this approach, like Wordpress, you will not have a strong database model, it will be messy and not really relationnal.
^^
A: I don't know how many tables are you planning to store, but if you don't need to make complicated operations like sorting or filtering you could just store them in files in a folder structure, that will consume less resources than MySQL and the entire file is preserved.
If you need many tables then don't store the HTML table, store a json with the info like this:
[
[
{
"content": "Let's use blue for this.",
"color": "blue"
},
{
"content": "Let's use red for this.",
"color": "red"
}
],
[
{
"content": "Another row.",
"color": "blue"
},
{
"content": "Another row.",
"color": "red"
}
]
]
And then rebuild it when you call it. Will use less space and will be faster to transfer.
If your tables are in a fixed format, then make a table with the fields you need.
A: I would recommend thinking of your table as a kind of object. SQL tables are meant to store relational data. As such, why not represent the table in that fashion? Below is a really basic example of how you could store a table of People data in SQL.
<table>
<thead>
<th>People ID</th>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>2</td>
<td>Jane</td>
<td>Doe</td>
</tr>
</tbody>
And then your SQL Table would store the encrypted string as follows (using JS):
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
var my_table = $('#table').html();
// Store this
var encrypted_string = utf8_to_b64(my_table);
// Decode as so
var table = b64_to_utf8(encrypted_string);
B64 encoding retrieved from here: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30696962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: copying a page n number of times with pdfbox I have made a single page pdf template file. I then use pdfbox to create a pdf with "n" number of pages (depending on report size). I want all "n" of these pages to be the page from the template pdf file. What is the best way to get all "n" pages to be a copy of that page? Here is my current code:
PDDocument document = null;
try {
document = PDDocument.load(WestfieldClientReportApp.class.getResource("/com/dramble/resources/template.pdf"));
} catch (IOException ex) {
Logger.getLogger(WestfieldClientReportView.class.getName()).log(Level.SEVERE, null, ex);
}
PDPage templatepage = (PDPage) document.getDocumentCatalog().getAllPages().get(0);
int n = 0;
while (n < numPages) {
n++;
document.importPage(templatepage);
}
The problem is when I have large result sets. I'll open the pdf, it will show as 11 pages, the first 2 pages look great, but when I scroll to the 3rd page, Acrobat errors, though the template page seems to be there, but without my report data on it. I figure the problem is probably with the code above. Any ideas? Thanks.
A: it might be because when you are casting explicitely from list to PDPage, it removes its acrofields.
A: Your code doesn't appear to be saving the result. Are you?
Here is my answer to a similar scenario which may help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7815613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Refresh id_token ADAL: Angular 4 I'm using Angular 4 with ADAL to authenticate users in my web application, using ng2-adal library which is a wrapper for adal.js.
The problem I'm facing is the following:
So the token expires after a time limit and I have a canActivate route guard that checks if the user is authenticated. If not, it navigates the users to the login page. This is how my route guard is looking:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AdalService } from 'ng2-adal/dist/core';
@Injectable()
export class RouteGuard implements CanActivate {
constructor(private router: Router, private adalService: AdalService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.adalService.userInfo.isAuthenticated) {
return true;
} else {
this.router.navigate(['/user-login']);
return false;
}
}
}
so whenever the token expires, the user is navigated to the login page, which is annoying for the users. Is there a way to renew the token whenever it expires?
A: I figured it out. This is how I added it:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AdalService } from 'ng2-adal/dist/core';
@Injectable()
export class RouteGuard implements CanActivate {
constructor(private router: Router, private adalService: AdalService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.adalService.userInfo.isAuthenticated) {
return true;
} else {
this.adalService.acquireToken(this.adalService.config.clientId).toPromise().then((data) => {
console.log('Generating a new authentication token.');
return true;
},
(error) => {
console.log('No user logged in.');
this.router.navigate(['/user-login']);
return false;
}
}
}
}
A: I had the same issue and my fix worked.
In app.component.ts, add this code to ngOnit().
this.adalService.handleWindowCallback();
this.adalService.acquireToken(this.adalService.config.loginResource).subscribe(token => {
this.adalService.userInfo.token = token;
if (this.adalService.userInfo.authenticated === false) {
this.adalService.userInfo.authenticated = true;
this.adalService.userInfo.error = '';
}
}, error => {
this.adalService.userInfo.authenticated = false;
this.adalService.userInfo.error = error;
this.adalService.login();
});
When token expires, app component gets called, and acquire token refreshes the token silently. But the this.adalService.userInfo.authenticated is still false leading to redirection or again calling login method. So manually setting it to true fixes the redirection error. this.adalService.config.loginResource this is automactically set by adal-angular itself with the resource that we need token for.
Also add expireOffsetSeconds: 320, to adal configuration data settings along with
tenant: configData.adalConfig.tenant,
clientId: configData.adalConfig.clientId,
redirectUri: window.location.origin,
expireoffsetseconds invalidates the token based on the time that we specify before its actual expiry.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49949172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Save changes in xlsm Workbook as xlsx without subsequent user confirmation I have an Excel file with a macro (.xlsm).
In the macro, I want to make changes in thisworkbook (where macro is) and save the organized workbook in the same folder of thisworkbook with a different name (and if possible as a .xlsx file, since I do not need the macro in the final file, if not possible as .xlsm).
After running macro, I do not want the user to do anything. Also, I do not want to save any changes in the original (reference) workbook.
I tried the following: (Assume this is in macro's sub)
Dim wb As Workbook
Set wb = ThisWorkbook
''''''''''''''''''''''''''''''''''''''''''''''''
' Check if final file exists, if so delete '''''
''''''''''''''''''''''''''''''''''''''''''''''''
wb.SaveCopyAs (wb.path & "\final.xlsm")
Dim wbf As Workbook
Set wbf = Workbooks.Add(wb.path & "\final.xlsm")
wbf.Activate
''''''''''''''''''''''''''''''''''''''''''''''''
' Changes to wbf '''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''
wbf.Save
I (as user) get a selection box:
" The following features cannot be saved in macro free workbooks
" VB project
" To save a file with these features, click No, and then choose a macro enabled file type in the File Type list.
" To continue saving as a macro free workbook, click Yes
"Yes", "No", "Help"
If I click Yes, it mentions that final1.xlsx already exists, and asks whether to overwrite or not. If click overwrite, the mentioned xlsx file open, final xlsm file gets saved at path.
This situation asks the user to click on something and also displays a new Excel file which I hope to avoid.
A: Try adding Application.DisplayAlerts = False prior to the main code, and set it back to Application.DisplayAlerts = True after.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72214390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Primitive derived operations and combinators in EDSL:s I recently flunked an exam, mostly because of a EDSL question. I did not grasp these concepts so I think thats why I failed. I think my teachers explanation was to abstract for me to understand, so I wonder if someone could explain it more clearly.
I wonder if someone could explain briefly what the components of a EDSL is, and what characterize them. In our course we have gone through Shallow and Deep Embedding of a DSL and looked at the following building blocks for a DSL:
*
*Constructor functions
*Combinators (primitive and derived)
*Run functions
I think contructor and run functions are more self-explanatory, so Im more interested to understand what makes a Combinator derived or primitive. It doesn´t hurt if someone will explain the other concepts. Here is an example from our lectures for reference. Its a shallow implemenation of a DSL for creating signals:
module Signal.Shallow
( Time
-- | the 'Signal' type is abstract
, Signal
-- * Smart constructors
, constS, timeS
-- * Combinators
, ($$), mapT
-- * Derived operation
, mapS
-- * Run function
, sample
) where
-- * Smart constructors
constS :: a -> Signal a
timeS :: Signal Time
-- * Combinators
($$) :: Signal (a -> b) -> Signal a -> Signal b
mapT :: (Time -> Time) -> Signal a -> Signal a
-- * Derived operation
mapS :: (a -> b) -> Signal a -> Signal b
-- * Run function
sample :: Signal a -> Time -> a
type Time = Double
newtype Signal a = Sig {unSig :: Time -> a}
-- | The constant signal.
constS x = Sig (const x)
-- | The time signal
timeS = Sig id
-- | Function application lifted to signals.
fs $$ xs = Sig (\t -> unSig fs t (unSig xs t))
A: A primitive combinator is one that's built into the DSL, defined in the base language (ie Haskell). DSLs are often built around an abstract type—a type whose implementation is hidden to the end-user. It's completely opaque. The primitive combinators, presented by the language, are the ones that need to know how the abstraction is actually implemented to work.
A derived combinator, on the other hand, can be implemented in terms of other combinators already in the DSL. It does not need to know anything about the abstract types. In other words, a derived combinator is one you could have written yourself.
This is very similar to the idea of primitive types in Haskell itself. For example, you can't implement Int or the Int operations like + yourself. These require things built into the compiler to work because numbers are treated specially. On the other hand, Bool is not primitive; you could write it as a library.
data Bool = True | False -- ... you can't do this for Int!
"Primitive" and "derived" for DSLs is the same idea except the compiler is actually your Haskell library.
In your example, Signal is an abstract type. It's implemented as a function Time -> a, but that information is not exported from the module. In the future, you (as the author of the DSL) are free to change how Signal is implemented. (And, in fact, you'd really want to: this is not an efficient representation and using Double for time is finicky.)
A function like $$ is primitive because it depends on knowing that Signal is Time -> a. When you change the representation of Signal, you'll have to rewrite $$. Moreover, a user of your library wouldn't be able to implement $$ themselves.
On the other hand, mapS is a derived operation because it could be written entirely in terms of the other things you're exporting. It does not need to know anything special about Signal and could even be written by one of the users of the library. The implementation could look something like:
mapS f signal = constS f $$ signal
Note how it uses constS and $$, but never unwraps signal. The knowledge of how to unwrap signal is hidden entirely in those two functions. mapS is "derived" because it is written just in your DSL without needing anything below your level of abstraction. When you change the implementation of Signal, mapS will still work as-is: you just need to update constS and $$ properly and you get mapS for free.
So: primitive combinators are ones which are built directly into your language and need to know about its internal implementation details. Derived combinators are written purely in terms of your language and do not depend on any of these internal details. They're just convenience functions which could have just as easily been written by the end-user of your library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25593992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to query on a Mysql cursor? I have fetched data into mysql cursor now i want to sum up a column in the cursor.
Is there any BIF or any thing i can do to make it work ?
db = cursor.execute("SELECT api_user.id, api_user.udid, api_user.ps, api_user.deid, selldata.lid, api_selldata.sells
FROM api_user
INNER JOIN api_user.udid=api_selldata.udid AND api_user.pc='com'")
A: I suspect the answer is that you can't include aggregate functions such as SUM() in a query unless you can guarantee (usually by adding a GROUP BY clause) that the values of the non-aggregated columns are the same for all rows included in the SUM().
The aggregate functions effectively condense a column over many rows into a single value, which cannot be done for non-aggregated columns unless SQL knows that they are guaranteed to have the same value for all considered rows (which a GROUP BY will do, but this may not be what you want).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24545472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Exception in create user on ejabberd16.09:Denied by ACL I installed the ejabberd16.09 in the Linux. An when I create a new user in Android , get these codes:
<iq from='hsoft.com' to='[email protected]/Smack' id='T61DB-59' type='error'>
<query xmlns='jabber:iq:register'><username>ddk</username>
<password>123456</password><registered/></query><error code='403' type='auth'>
<forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/><text xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'>
Denied by ACL</text></error></iq>
And my file 'conf/ejabberd.yml' in the Linux :
## To disable in-band registration, replace 'allow' with 'deny'.
register:
- allow
## Only allow to register from localhost
trusted_network:
- allow
## Do not establish S2S connections with bad servers
## s2s:
## - deny:
## - ip: "XXX.XXX.XXX.XXX/32"
## - deny:
## - ip: "XXX.XXX.XXX.XXX/32"
## - allow
My Android code :
private void XmppRegister(){
AccountManager account = AccountManager.getInstance(con);
account.sensitiveOperationOverInsecureConnection(true);
try {
account.createAccount("ddk".toLowerCase(), "123456");
Log.d("PushTest", "register successfully");
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
Please help me! Thank you!
A: You have to add
AccountManager.getInstance(connection)
.sensitiveOperationOverInsecureConnection(true);
to disable your ACL while you are registering a new user, then switch back to default settings:
AccountManager.getInstance(connection)
.sensitiveOperationOverInsecureConnection(false);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40171494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to define where my MDB database is stored in local hard disk (VB.NET) VB.net seem to place my database file into /userprofile/local settings/apps/2.0/data/random/random/appname/data/ folder.
Can I define easier location for my published app. I am also worried that when upgrading this database is ignored or something bad happens?
A:
Can I define easier location for my published app.
Well inside of your connection string you can specify the location of the database under Data Source.
Take your database and move it where ever you want, and then update the Data Source inside of your connection string to point to that path. You might have to play with it a few times to get the path right, but this should do what you are wanting to do.
VB.net seem to place my database file into /userprofile/local settings/apps/2.0/data/random/random/appname/data/ folder.
If you are making an installer then you will want to keep the database close to the application, most likely inside a sub-folder in the application's directory (like the data folder). That is why VS (not VB .Net) tends to place a created database inside of the data folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/975454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mongodb connection error in Rails I am getting following error while connecting to mongodb using rails console :
Getting Error Mongo::Error::NoServerAvailable: No server is available matching preference: # using server_selection_timeout=30 and local_threshold=0.015
This happens when I switch my rails application.
It is working fine in another rails application(which I was working on for a while) console but when I try to use it in another rails application it gives above error.
I have checked my mongo server it is running and I have also checked my mongoid.yml file configuration. Everything seems fine.
I am a newbie on rails.
Any help would be appreciated. Thanks in Advance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48840515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: use rollapply and zoo to calculate rolling average of a column of variables I want to calculate the rolling mean for all variables in column "sp". This is a sample of my data:
the_date sp wins
01-06--2012 1 305
02-06--2012 1 276
03-06--2012 1 184
04-06--2012 1 248
05-06--2012 1 243
06-06--2012 1 363
07-06--2012 1 272
01-06--2012 2 432
02-06--2012 2 369
03-06--2012 2 302
04-06--2012 2 347
05-06--2012 2 357
06-06--2012 2 331
07-06--2012 2 380
01-06--2012 3 1
02-06--2012 3 2
03-06--2012 3 3
04-06--2012 3 2
05-06--2012 3 0
06-06--2012 3 2
07-06--2012 3 0
What I want, is to have a column added to data, that gives the moving average over 3 days for each sp. So the following output is what I desire:
the_date sp wins SMA_wins
01-06--2012 1 305 305.00
02-06--2012 1 276 290.50
03-06--2012 1 184 255.00
04-06--2012 1 248 236.00
05-06--2012 1 243 225.00
06-06--2012 1 363 284.67
07-06--2012 1 272 292.67
01-06--2012 2 432 432.00
02-06--2012 2 369 400.50
03-06--2012 2 302 367.67
04-06--2012 2 347 339.33
05-06--2012 2 357 335.33
06-06--2012 2 331 345.00
07-06--2012 2 380 356.00
01-06--2012 3 1 1.00
02-06--2012 3 2 1.50
03-06--2012 3 3 2.00
04-06--2012 3 2 2.33
05-06--2012 3 0 1.67
06-06--2012 3 2 1.33
07-06--2012 3 0 0.67
I am using rollapply.
df <- group_by(df, sp)
df_zoo <- zoo(df$wins, df$the_date)
mutate(df, SMA_wins=rollapplyr(df_zoo, 3, mean, align="right", partial=TRUE))
If I filter my data on a specific sp, it works perfectly.
How can I make this work when I group by sp?
Thanks
A: You can do it like this:
library(dplyr)
library(zoo)
df %>% group_by(sp) %>%
mutate(SMA_wins=rollapplyr(wins, 3, mean, partial=TRUE))
It looks like your use of df and df_zoo in your mutate call was messing things up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33769770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to delete a MySQL row that only the logged-in user created I made a website that creates 'awards' and user has to login. I am trying to create a 'delete' button so that the user can delete awards he created. The problem with the code I created, the user can delete ANY award that any user created. I need it so that only awards that the logged-in user can be deleted by the same logged-in user.
//deletes the award from awards table
app.post('/Update_Award', function(request, response) {
//app.delete('/Delete_Award', function(request, response) {
var connection = request.app.get('pool');
if (request.session.loggedin) {
//delete query - this delete query works but it can delete ANY award by ANY user
//connection.query('DELETE FROM award WHERE id = ?', [request.body.id], function(error, results, fields) {
//I tried this query so that only the logged-in user can delete its own created award
//but this does not delete anything at all
**connection.query('DELETE FROM award WHERE id IN (SELECT id FROM accounts WHERE username = ?)', [request.session.username], function(error, results, fields) { **
if (error) {
throw error;
} else
var context = {};
connection.query('SELECT * FROM award', function(error, results, fields) {
if (error) {
console.log(error);
} else {
context.awards = results;
connection.query('SELECT id, title, defaultDescription FROM awardType;', function(error, results, fields) {
context.awardTypes = {};
results.forEach(function(el) {
context.awardTypes[el.id] = el.title;
});
response.render('Update_Award.html', { awards: context.awards, awardTypes: context.awardTypes, msg: 'Successfully deleted!' });
});
}
});
});
}
});
I've been stuck with this problem so any help would be much appreciated. So far, it doesn't output any error but it cannot delete a row.
The award table has the "isserId" which is the "id" of the user in the accounts table which contains all the users.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59188172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I need to iterate an array over columns of my table in a blade file I need a table which I can iterate data of my table over its columns.
like
<table>
<thead>
<tr colspan="2">کارکرد</tr>
<tr colspan="2">پرداخت</tr>
<tr colspan="2">کسور</tr>
</thead>
<tbody>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
</tbody>
</table>
please help me out here
The issue is I should iterate each column of data separately, and I have no idea how to do that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67996759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: getElementsByTagName not working in IE when returning XML file? I'm trying to select certain elements from an XML file via JavaScript, I've got it working in Firefox, Chrome and IE9+ but IE8 is proving to be a real stumbling block, I'm using the code below to return the XML file:
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', theUrl, false);
xmlHttp.send();
if(window.DOMParser) {
var parser = new DOMParser();
var doc = parser.parseFromString(xmlHttp.responseText, 'text/xml');
return doc;
}
else {
var xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
xmlDocument.async = false;
xmlDocument.loadXML(xmlHttp.responseText);
return xmlDocument;
}
}
I'm then using the below selectors to make a list of certain items in the XML file:
var rssData = httpGet(rssFeed);
var allTitles = convertToArray(rssData.getElementsByTagName('title'));
var allDates = convertToArray(rssData.getElementsByTagName('pubDate'));
var allText = convertToArray(rssData.getElementsByTagName('text'));
I then concatenate the array items together and set an items innerHTML to that value (I can provide this code if needed)
the strange thing is that IE8 returns the right number of items, but each item has the value undefined as oppsed to the actual value e.g. "Hello world"
I've been battling this for hours and still come up blank ... does anybody have any idea what I'm doing wrong?
EDIT: as requested here is the convert to array function
function convertToArray(htmlCollection) {
var nodes = [];
var collectionLength = htmlCollection.length;
for(i = 0; i < collectionLength; i++) {
nodes.push(htmlCollection[i]);
}
return nodes;
}
A: The problem was that you'd have to use .text and not .textContent for ie8, because the textContent property doesn't exist in ie.
You can see in MDN that textContent is available only for ie 9+
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16194785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hibernate: Exception occurred in target VM: failed to lazily initialize a collection I have User to Cars 1-to-n.
mappings:
User:
<set inverse="true" name="cars" table="CAR">
<key>
<column name="UserID" not-null="false"/>
</key>
<one-to-many class="entity3.Car"/>
</set>
Car:
<many-to-one class="entity3.User" name="user">
<column name="UserID" not-null="false"/>
</many-to-one>
After i get some users and close session, in debugger, in user i see PersistentSet cars with this exception as value:
>Exception occurred in target VM: failed to lazily initialize a collection of role: entity3.User.cars, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: entity3.User.cars, no session or session was closed
Is this normal behavior? Do those exceptions slow down perfomance?
A: You are getting this exception because the session that has been used to fetch the User entity has been closed (more probably it must have been destroyed somewhere in the code).
If you need to fetch the Cars collection you will have to make sure that you have the same session open when you try to access the Cars property in the User entity.
I have also fallen once in this pitfall.
I don't think that exceptions itself causes any performance issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9277466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gridview empty when SelectedIndexChanged called I have a DataGrid which is being bound dynamically to a database query. The user enters some search text into a text field, clicks search, and the code behind creates the appropriate database query using LINQ (searches a table based on the string and returns a limited set of the columns).
It then sets the GridView datasource to be the query and calls DataBind().
protected void btnSearch_Click(object sender, EventArgs e)
{
var query = from record in DB.Table
where record.Name.Contains(txtSearch.Text) //Extra string checking etc. removed.
select new
{
record.ID,
record.Name,
record.Date
};
gvResults.DataSource = query;
gvResults.DataBind();
}
This works fine.
When a user selects a row in the grid, the SelectedIndexChanged event handler gets the id from the row in the grid (one of the fields), queries the full record from the DB and then populates a set of editor / details fields with the records full details.
protected void gvResults_SelectedIndexChanged(object sender, EventArgs e)
{
int id = int.Parse(gvResults.SelectedRow.Cells[1].Text);
DisplayDetails(id);
}
This works fine on my local machine where I'm developing the code. On the production server however, the function is called successfully, but the row and column count on gvResults, the griview is 0 - the table is empty.
The gridview's viewstate is enabled and I can't see obvious differences. Have I made some naive assumptions, or am I relying on something that is likely to be configured differently in debug?
Locally I am running an empty asp.net web project in VS2008 to make development quicker. The production server is running the sitecore CMS so is configured rather differently.
Any thoughts or suggestions would be most welcome. Thanks in advance!
A: Check your web.config. Likely the "AutomaticDataBind" property is set to "false" in one environment, and "true" on your dev box.
I cannot be sure, obviously, but I've been hammered by a similar issue in the past and the symptoms were exactly like you describe here :-)
P.S. Sitecore defaults this value to false.
A: Having poked around the sitecore forums some more, I came across this blog post explaining one potential solution.
I added <type>System.Web.UI.WebControls.GridView</type> to the <typesThatShouldNotBeExpanded> section of Web.config and it seems to work for us.
It seems to be to do with sitecore's page layout rendering pipeline, where it expands sub-layouts and internal placeholders to generate the full page rendering. It accesses the .Net controls on the page and pokes them around a bit, which can cause some controls to not work correctly.
There is an article on the SDN about this, although you can only read it if you have an account with sufficient privalegs. Hope this might help any other sitecore users out there in future.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2599100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: multiple undefined Variable I have a problem with an application.
Notice: Undefined variable: nombre in C:\wamp\www
Notice: Undefined variable: puesto in C:\wamp\www
Notice: Undefined variable: area in C:\wamp\www
Notice: Undefined variable: id in C:\wamp\www
here's the codes:
<?php
session_start();
header('Content-type: application/json');
//si es una llamada ajax
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
//Funcion para verifica si el request en un tipo Ajax rquest
if (is_ajax()) {//si esta seteado el pots
if (isset($_POST["nombre"]) && !empty($_POST["nombre"]))
{ //verificar si nombre existe y tiene valor
$nombre = $_POST["nombre"];
if (!preg_match("/^[a-zA-Z ]*$/", $nombre))
{
echo "Solo letras y espacios estan permitidos para el Nombre";
die;
}
} //set variable puesto
if (isset($_POST["puesto"]) && !empty($_POST["puesto"]))
{ //verificar si puesto existe y tiene valor
$puesto = $_POST["puesto"];
if (!preg_match("/^[a-zA-Z ]*$/", $puesto))
{
echo "Solo letras y espacios estan permitidos para el puesto";
die;
}
} //set varia
if (isset($_POST["area"]) && !empty($_POST["area"]))
{ //verificar si area y tiene valor
$area = $_POST["area"];
if (!preg_match("/^[0-9]*$/", $area))
{
echo "Error";
die;
}
}
if (isset($_GET["id"]) && !empty($_GET["id"]))
{ //verificar si area y tiene valor
$id = $_GET["id"];
if (!preg_match("/^[0-9]*$/", $id))
{
echo "Error";
die;
}
}
}
require_once 'connection.php';
try
{
$sql = "Update tbl_empleados SET Nombre = '$nombre', Puesto = '$puesto', fk_idarea= '$area' where idEmpleados = '$id'";
// use exec() because no results are returned
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "Empleado Actualizado Satisfactoriamente";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
die;
}
$conn = null;
?>
JavaScript:
$(document).ready(function () {
var urid = getUrlVars()["id"].replace("#", '');
$('#btn-actualizar').click(function () {//evento click del boton:
parametros = validarFormulario(document.frmactualizarempleado);
//Funcion para validar los campos
if (parametros.Status) {
//ejecutar Ajax para cargar usuarios URL: altaempleados.php
parametros.id = urid;
console.log(parametros);
$.ajax({
type: "POST",
url: "resources/includes/actualizare.php",
data: parametros,
success: function () {
$('#frmactualizarempleado').html("<div id='message'></div>");
$('#message').html("<h2>Los datos han sido guardados correctamente!</h2>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<a href='index.php?action=see'>Ver empleados registrados</a>");
});
}
});
return false;
runOnLoad(function () {
$("input#name").select().focus();
});
}
});
});
Form:
<?php require_once 'resources/includes/header.php';
require_once 'resources/includes/connection.php';
try
{
$sql = "select idAreas as `Key`, nombre as `Value` from tbl_areas";
$stmt = $conn->prepare($sql);
$stmt->execute();
// set the resulting array to associative array
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//fetch query result to array
$result = $stmt->fetchAll();
}
catch (Exception $e)
{
echo "Ocurrio un Error:" . "'".(string)$e->getMessage()."'";
die();
}
$stmt = null;
?>
<link rel="stylesheet" href="resources/css/tablestyle.css">
<body class="">
<div class="panel bottom-padding-0">
<div class="row">
<div class="large-5 columns"><h3 class="h3">Actualizar Empleados.</h3></div>
<div class="row">
</div>
<div class="large-12 columns">
<form name="frmactualizarempleado">
<div class="row">
<div class="large-4 columns">
<label>Nombre:</label>
<input type="text" name="nombre" placeholder="Nombre" />
</div>
<div class="large-4 large-rigth columns">
<label>Puesto:</label>
<input type="text" name="puesto" placeholder="Puesto" />
</div>
<div class="large-4 large-rigth columns">
<label>Area:</label>
<select id="areas" name="area">
<option value="" disabled selected>Selecciona tu Area</option>
<?php
// Echo $result while row >= EOF
foreach($result as $results) { ?>
<option value="<?php echo $results['Key'] ?>"><?php echo $results['Value'] ?></option>
<?php }?>
</select>
</div>
</div>
<div class="small-3 columns large-centered">
<a href="#" id='btn-actualizar' class="button postfix">Actualizar</a>
</div>
</form>
</div>
</div>
</div>
</body>
<?php require_once 'resources/includes/footer.php';?>
<script src="resources/js/actualizaremp.js"></script>
| {
"language": "es",
"url": "https://stackoverflow.com/questions/32145241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Regular Expressions to Parse Facebook API Long Term Access Token I'm using the Facebook API Javascript SDK for website login and to various information from the user's profile. For my server side HTTP request to Facebook for a long term access token I'm using Ruby on Rails with HTTParty Gem. I'm successfully receiving the token but would like to parse it using RegEx before persisting it to the database. My response looks as follows:
"access_token=long_term_access_token&expires=5183165"
I would like to remove the the access_token= from the beginning of the string and the &expires=5183165 from the end of the string. I would prefer to do this with regex rather than the Ruby gsub method because I would like to preserve the information for later use.
A: Use /access_token=(.*?)&/i:
Here's a working example: http://regex101.com/r/oN6fW0
This ensures that you capture (using parentheses ()) everything after access_token=, and between the next & using a non-greedy, 0 or more of anything expression .*?.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20592450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: QT for beginners everybody, I'm beginner in programming, I've just finished my course on C++, I want to train my skills and try to write some programs on C++ with graphic windows (not console programs, I did it during all my course), I want to start working with QT, is it good idea, or I need to begin with something simplier, thanks in advance
A: Qt is, among other things, a great framework for developing applications with GUIs. The only way to know if it is appropriate is to try it out. I suggest going through this Qt tutorial, which involves creating a simple game.
A: To begin with Qt is an excellent idea. Qt is already simpler.
You should begin with these official tutorials: http://doc.qt.nokia.com/4.7-snapshot/tutorials.html
A: GUI program is a big change from a console app - the difference is that you don't know when things are going to happen and in what order.
But Qt is a very good place to start, the signal/slot mechanism is much clearer (IMHO) than the hidden macros of MFC or some other gui toolkits.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3197360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are the contents need to add in hteader.html from index.html? I have created simple web page using HTML5, CSS and jQuery.
Here is my index.html:
<!DOCTYPE HTML>
<html>
<head>
<title>Responsive Design Website</title>
<link rel = "stylesheet" type = "text/css" href = "css/style.css" media="screen"/>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.jsdelivr.net/animatecss/2.1.0/animate.min.css">
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700,800" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="engine1/style.css" />
<link href="video-js.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="img/favicon.ico">
<script src="video.js"></script>
<script type="text/javascript" src="engine1/jquery.js"></script>
<script>
videojs.options.flash.swf = "video-js.swf";
</script>
</head>
<body id="demo-one">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div id = "wrap">
<header>
----
</header>
<!--Here slideshow-->
<aside>
------
</aside>
<!---Main content-->
<footer>
------
</footer>
</div>
</body>
</html>
Now i want to know basic knowledge about, What are the contents that need to add in header.html and footer.html from index.html file?
Any help would be highly appreciated.
A: In header.html
logo
menu
In footer.html
social icon
copy rights
A: all of this needs to go in the header.html
<!DOCTYPE html>
<html>
<head>
<title>Responsive Design Website</title>
<link rel = "stylesheet" type = "text/css" href = "css/style.css" media="screen"/>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.jsdelivr.net/animatecss/2.1.0/animate.min.css">
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700,800" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="engine1/style.css" />
<link href="video-js.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="img/favicon.ico">
</head>
</html>
And this goes in the footer.html
<!DOCTYPE html>
<html>
<footer>
<script src="video.js"></script>
<script type="text/javascript" src="engine1/jquery.js"></script>
<script>
videojs.options.flash.swf = "video-js.swf";
</script>
</footer>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26645344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is this a variation of the decorator pattern or a pattern at all? Below is a simplified version of code I've written to override a class method (using composition), in this case method name i'm overriding is addbuttons(); The class "Screen" adds buttons to a screen whereas class "SubScreen" adds custom buttons to an instance of Screen. Maybe this is not an example of decorator pattern since I'm overriding functionality instead of extending it ? Is there a better way (using a design pattern ?) to achieve same functionality ?
public class Driver {
public static void main(String args[]){
AddComponents add1 = new Screen();
add1.addButtons();
Screen newScreen = new Screen();
AddComponents add2 = new SubScreen(newScreen);
add2.addButtons();
}
}
public interface AddComponents {
public void addButtons();
}
public class Screen implements AddComponents{
public void addButtons() {
//Add Buttons to screen class
}
}
public class SubScreen implements AddComponents{
private Screen screen;
public SubScreen(Screen screen){
this.screen = screen;
}
public void addButtons() {
//add different custom buttons to Screen class
}
}
A: Another possibility would be to call it Proxy. Decorator and Proxy are technically very similar - the difference is - in most cases - not a technical one but based on the intention.
Your example is a little bit minimal and therefore it is hard to guess the intention correctly.
Edit
At the detailed level: Screen and SubScreen do not share any code. If you start adding methods to both implementations and the common interface AddComponents you might find
*
*that you must duplicate code both in Screen and SubScreen (or delegate to Screen) and
*that you must add methods to AddComponents which make this interface badly named.
If both screen classes are similar both on the abstract logical level and at the implementation level, then a an class AbstractScreen with two derived classed would be better. To bring back pattern speak: Use a Factory Method in AbstractScreen to specialize the behaviour regarding the different buttons.
On your current code there is one strange thing: Why is there a method addButton defined anyway? Simply add the buttons in the appropriate constructor, since the user has to call addButtons in any case and the method does not have arguments.
Another point not explained is this: SubScreen has a reference to Screen which is not used. Why? Will there be more method in all involved classes Screen, SubScreen and AddComponents? Will each method be a in SubScreen delegate to Screen or only half of them?
You see - there are many possibilities we do not know and are not shown in the example code but are very important. I'm sure that your head contains a lot of details saying "This proposed stuff will not work because I want to do this and that one way or the other in the near future." Sadly we cannot get the content of your head into this site without more writing. :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7666972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Firebase re-authenticate using PhoneNumberProvider To delete user the user has to be recently authenticated ... I am using Phone number authentication and looking at the example in the docs: https://firebase.google.com/docs/auth/android/manage-users#re-authenticate_a_user
I need to get the credential of the user which requires 2 parameters: verification Id and SMS code which are fetched from authenticating the user in the first place ... so is there another way to fetch them or I have to send a verification code once more as I did when the user was first authenticated ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46139780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: AttributeError: 'dict' object has no attribute 'plot' from iexfinance import Stock
import matplotlib.pyplot as plt
tsla = Stock('TSLA')
tsla.get_close()
tsla.get_price()
from iexfinance import get_historical_data
from datetime import datetime
import pandas as pd
pd.set_option('display.max_rows', 1000)
start = datetime(2017, 2, 9)
end = datetime(2017, 5, 24)
df = get_historical_data("TSLA", start=start, end=end, output_format='json')
df.plot()
plt.show()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call
last)
<ipython-input-16-77b5455be846> in <module>()
8
9 df = get_historical_data("TSLA", start=start, end=end,
output_format='json')
---> 10 df.plot()
11 plt.show()
12 df
AttributeError: 'dict' object has no attribute 'plot'
I am trying to get the plot for the dataframe created with the different prices from the start and end date. I tried reading different blogs but none seem to solve it. I am sure I am making a very basic error. Although, I am not able to figure out what am I doing wrong here, any suggestions to fix it?
A: You cannot directly plot a dictionary in matplotlib. It needs x values and y values.
You can see that type(df) will be a <class 'dict'> which contains the value something like this:
{'TSLA': {'2017-02-09': {'open': 266.25, 'high': 271.18, 'low': 266.15, 'close': 269.2, 'volume': 7820222}}}
so, if you want to get it graphed, you need to convert it into pandas dataFrame
your code has to change like this:
from iexfinance import Stock
import matplotlib.pyplot as plt
tsla = Stock('TSLA')
tsla.get_close()
tsla.get_price()
from iexfinance import get_historical_data
from datetime import datetime
import pandas as pd
pd.set_option('display.max_rows', 1000)
start = datetime(2017, 2, 9)
end = datetime(2017, 5, 24)
df = get_historical_data("TSLA", start=start, end=end, output_format='json')
df = pd.DataFrame(df["TSLA"]).transpose() #transpose to get dates as x
df = df.drop(columns = "volume") #deleted volume column, else it make other graphs smaller
df.index = pd.to_datetime(df.index) #change string to date format
df.plot()
plt.show();
You will get a graph like this:
Graph
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51816097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to configure mvc to support binding dd/MM/yyyy date formates for all cultures? I have MVC web application and I am supporting 2 languages(Arabic, English).
I have post-action which takes the following model:
public class MyModel
{
public DateTimeOffset StartDate { get; set; }
public DateTimeOffset EndDate { get; set; }
}
When UI language is English it serializes the following date formate "dd/MM/yyyy" perfectly after adding globalization config inside web.config:
<globalization uiCulture="en" culture="en-GB" />
but when UI language is Arabic they are serialized into 0001-01-01T00:00:00 +00:00 (even the value posted by Jquery is startDate: 26/08/2020)
So how can I configure my web application to support binding the "dd/MM/yyyy" format for all cultures?
A: Try using this
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTimeOffset StartDate { get; set; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63592435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using JavaScript inside a Eclipse plugin It is possible to use JavaScript inside a view of a Eclipse Plugin?
A: By default eclipse runs on java in a JVM. But JVMs have more and more support for dynamic scripting languages. You can always use org.mozilla.javascript so your view can implement parts in javascript. The linke I've included to eclipse Orbit builds are versions that have been OSGi-ified so they can be used easily in eclipse.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11018009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: RegEx to match if the string contains 1 or more sets of 1-10 alphanumerics RegEx to match if the string contains 1 or more sets of 1-10 alphanumerics (separated by 1 space)
Right now i have this and that will match the alphanumeric part.
var regex = /^[0-9a-zA-Zs]+$/;
After it matches i plan to just use
var matches = thetext.Split(' ');
to get the various matches.
Thanks in advance
A: You wrote s in your regular expression instead of \s (meaning whitespace).
If you want to enforce that there is exactly one space character (not multiple spaces and not tabs or other whitespace characters) then you can use this:
/^[0-9A-Za-z]{1,10}(?: [0-9A-Za-z]{1,10})*$/
If you also want to allow underscores, you can use \w to make the expression more concise:
/^\w{1,10}(?: \w{1,10})*$/
A: Try regexp like this if you don't expact space at begin and spaces should be longer than 1 character
var regex = /^([0-9a-zA-Zs]+\s*)*$/;
With possible space at begin you can use
var regex = /^\s*([0-9a-zA-Zs]+\s*)*$/;
If you expact exactly one space and no spaces at begin or end then use
var regex = /^([0-9a-zA-Zs]+\s)*[0-9a-zA-Zs]+$/;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8071445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: android bootcamp medical calculator fails to open Whenever I try to run the below calculator app on the emulator, it instantly crashes. Not knowing Java, reading the logcat is a bit overwhelming.
The program's purpose is to create a weight conversion app that uses a radio group and converts kilograms to pounds or vice versa.
Here is my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.androidbootcamp.medicalcalculator"
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Here is my logcat:
>02-26 11:14:42.147 1535-1535/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{net.androidbootcamp.medicalcalculator/net.androidbootcamp.medicalcalculator.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at net.androidbootcamp.medicalcalculator.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Here is my MainActivity:
package net.androidbootcamp.medicalcalculator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
double conversionRate = 2.2;
double weightEntered;
double convertedWeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
final EditText weight = (EditText)findViewById(R.id.txtWeight);
final RadioButton lbToKilo = (RadioButton)findViewById(R.id.radLbToKilo);
final RadioButton kiloToLb = (RadioButton)findViewById(R.id.radKiloToLb);
final TextView result = (TextView)findViewById(R.id.txtResult);
Button convert = (Button)findViewById(R.id.btnConvert);
convert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
weightEntered=Double.parseDouble(weight.getText().toString());
DecimalFormat tenth = new DecimalFormat("#.#");
if(lbToKilo.isChecked()){
if (weightEntered <= 500){
convertedWeight = weightEntered / conversionRate;
result.setText(tenth.format(convertedWeight) + "kilograms");
} else {
Toast.makeText(MainActivity.this,"Pounds must be less than 500",Toast.LENGTH_LONG).show();
}
}
if(kiloToLb.isChecked()){
if(weightEntered <= 225) {
convertedWeight = weightEntered * conversionRate;
result.setText(tenth.format(convertedWeight) + "pounds");
} else {
Toast.makeText(MainActivity.this,"Kilos must be less than 225",Toast.LENGTH_LONG).show();
}
}
}
});
}
}
A: In your manifest you are using android:theme="@style/AppTheme.NoActionBar" so the main activity will not contain the action bar and you will get a NullPointerException.
The assert getSupportActionBar() != null throw the Exception because it is always null in this case. In this case the Assert works like:
if(!getSupportActionBar() != null) {
throw new Exception(); //NullPointerException in this case
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35657145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MyBatis do a fetch and based on return value do an update/insert inside the Xxxmapper.xml? Is there a way to embed a select from table inside a Mybatis Insert SQL config, Which checks if the record is existing -> Runs the Update on the same table
else just inserts the data.
I know it can be done programtically but need a way to do it in the mapper.xml
Database: Oracle 11g, mybatis 3.1.x
Any suggestions are helpful
thanks
A: Use UPSERT statement, most of the database support UPSERT statements. the return value would be number of records updated or inserted. Though You have not provided the database against which you have performing the update or insert operation.
UPDATE
Oracle 11g does support upsert
MERGE INTO KP_TBL USING DUAL ON (MY_KEY= #{myKey})
WHEN MATCHED THEN
UPDATE SET OTHER_PARAM = #{myOtherParam},
SEC_PARAM = #{sec_param}
WHEN NOT MATCHED THEN
INSERT (MY_KEY, OTHER_PARAM,SEC_PARAM) VALUES(#{myKey},#{myOtherParam},#{sec_param)
A: This could be done using means of SQL. Unfortunately you didn't mention which particular database management systen you use as there is no such feature in ANSI SQL.
For example if you use MySQL INSERT ... ON DUPLICATE KEY UPDATE is the way to go.
E.g.:
<insert id="instSample" parameterType="SampleModel">
INSERT INTO table (a,b,c) VALUES (#{a}, #{b}, #{c})
ON DUPLICATE KEY UPDATE c = #{c};
</insert>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28993805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regex input only number and backspace I have a code
private void DataGridTypePayments_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
}
I need input number or backspace.How i can disable input symbol space?
A: The C-style escape for the backspace character is \b which is also the Regex escape for a word boundary. Fortunately you can put it in a character class to change the meaning:
e.Handled = Regex.IsMatch(e.Text, "[0-9\b]+");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32965221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Load local files(CSS or JS) into website of choice I want to load my own coded CSS into a website that I do not own or have server access too. This is for perdonal use only. My problem is I dont know if there is a plugin available to do this; in chrome or firefox. Is there any easy way to do this? How do I do it?
Any help is appreciated. Thanks in advance!
A: Stylebot is a chrome extension that does the very thing. Use this link or if it doesn't work, just go to chrome://extensions then get more extensions and search for Stylebot
But still it won't let you add your own CSS file. It would just allow you to change the CSS of the website and it will store them for you so that whenever you'll visit that site, it would show you the same styles.
A: There are several ways of doing this: 1. First, plugin as you ask for, there is one called User Stylesheet for Chrome and Stylish for Firefox
2. You can edit C:\Users*\AppData\Local\Google\Chrome\User Data\Default\User StyleSheets\Custom.css directly for Chrome
3. You can use dev tool in both Chrome and Firefox to temporary change the element styles.
Just saw you asked for custom javascript as well, you can use Greasemonkey for Firefox and Tampermonkey for Chrome.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20729725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Would updating Facebook Android SDK crash my apps on api level below 15? The new Facebook Android SDK requires android min API level 15 but almost all of my apps are at min API level 9. If I integrate new FB Android SDK would that crash my apps on devices with API level below 15?
Also would Share images on FB functionality on API level 9 devices stop working if I get the new SDK?
A: The minSdkVersion attribute means that the library was designed without considering the API levels lower than that value. The developers didn't pay attention if a method or a field is unavailable on API level lower than 15, and this is the method to inform you.
For example the field THREAD_POOL_EXECUTOR used in the method getExecutor is available only from API level 11:
public static Executor getExecutor() {
synchronized (LOCK) {
if (FacebookSdk.executor == null) {
FacebookSdk.executor = AsyncTask.THREAD_POOL_EXECUTOR;
}
}
return FacebookSdk.executor;
}
In version 4.5.1 the getExecutor method is different and supports also API level 9:
public static Executor getExecutor() {
synchronized (LOCK) {
if (FacebookSdk.executor == null) {
Executor executor = getAsyncTaskExecutor();
if (executor == null) {
executor = new ThreadPoolExecutor(
DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE, DEFAULT_KEEP_ALIVE,
TimeUnit.SECONDS, DEFAULT_WORK_QUEUE, DEFAULT_THREAD_FACTORY);
}
FacebookSdk.executor = executor;
}
}
return FacebookSdk.executor;
}
In conclusion you shouldn't use the last version of the Facebook SDK but you should stick with the last compatible version (4.5.0).
The change in minApk version is shown in the upgrade log below: -
https://developers.facebook.com/docs/android/upgrading-4.x.
and the release of interest is below
https://github.com/facebook/facebook-android-sdk/releases?after=sdk-version-4.8.1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33689058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: why does this make calls javascript Im creating a angular5 application and I have some problems with the services i use to make requests to a simple node backend server. I won't include the backend code because it doesn't matter if it works or not.
My idea was to have the Service remember if it already has the data and if so, don't make another call. I created a boolean called useCache to keep track of whether to make another call. Code shown below.
getPeople() {
console.log('before ', this.useCache);
if (this.useCache === false) {
console.log('after', this.useCache);
this.setPeople(this.api.get(this.url));
this.useCache = true;
}
return this.people;
}
useCache is initialized as false so the first time it should make a call.
The second+ times it prints useCache to be true.
This code will not log the ('after', this.useCache) when pressing a button that triggers the GET call multiple times. However my backend server is still registering calls.
people is a undefined variable at first with type any
I tried logging in the api.get function also, and that log isn't printed either.
public get(url: string) {
console.log('get');
return this.http.get(API_BASE_URL + url).map(response => {
return response;
}).catch(this.handleError);
}
Inside the component that im calling from i have this function to call the getPeople() function.
getPeople() {
this.personService.getPeople().subscribe(result => {
console.log(result);
this.people = result.result;
this.dataType = 'people';
});
}
Does anyone have any idea how/why my backend is still logging GET calls?
It shouldn't know I pressed that button inside the separate front-end application right?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48809263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I need to optimize my first T-SQL update trigger How do I rewrite this update trigger without using a lot of variables?
I wrote my first SQL Server trigger and it works fine, but I think, that there must be an easier solution.
If minimum one of 5 columns is changed I write two new rows in another table.
row 1 = old Fahrer (=Driver) and old dispodate and update-time
row 2 = new Fahrer and new dispodate and updatedatetime
My solution is just a copy of the foxpro-trigger, but there must be a easier solutions in T-SQL to check whether one colum is changed.
ALTER TRIGGER [dbo].[MyTrigger]
ON [dbo].[tbldisposaetze]
AFTER UPDATE
AS
SET NOCOUNT ON;
/*SET XACT_ABORT ON
SET ARITHABORT ON
*/
DECLARE @oldfahrer varchar(10)
DECLARE @oldbus varchar(10)
DECLARE @olddispodat date
DECLARE @oldvzeit decimal(4,0)
DECLARE @oldbzeit decimal(4,0)
DECLARE @oldbeschreibk varchar(255)
DECLARE @newfahrer varchar(10)
DECLARE @newbus varchar(10)
DECLARE @newdispodat date
DECLARE @newvzeit decimal(4,0)
DECLARE @newbzeit decimal(4,0)
DECLARE @newbeschreibk varchar(255)
SELECT @oldfahrer = fahrer,@oldbeschreibk=beschreibk,@oldbus=bus,@oldbzeit=bzeit,@olddispodat=dispodat,@oldvzeit=vzeit
FROM DELETED D
SELECT @newfahrer = fahrer,@newbeschreibk=beschreibk,@newbus=bus,@newbzeit=bzeit,@newdispodat=dispodat,@newvzeit=vzeit
FROM inserted I
if @oldbeschreibk <> @newbeschreibk or @oldbus <> @newbus or @oldbzeit <> @newbzeit or @oldfahrer <> @newfahrer or @oldvzeit <> @newvzeit
begin
IF (SELECT COUNT(*) FROM tbldispofahrer where fahrer=@oldfahrer and dispodat=@olddispodat) > 0
update tbldispofahrer set laenderung = GETDATE() where fahrer=@oldfahrer and dispodat=@olddispodat
else
INSERT into tbldispofahrer (fahrer,dispodat,laenderung) VALUES (@oldfahrer,@olddispodat,getdate())
IF (SELECT COUNT(*) FROM tbldispofahrer where fahrer=@newfahrer and dispodat=@newdispodat) > 0
update tbldispofahrer set laenderung = GETDATE() where fahrer=@newfahrer and dispodat=@newdispodat
else
INSERT into tbldispofahrer (fahrer,dispodat,laenderung) VALUES (@newfahrer,@newdispodat,getdate())
end
A: I'll assume you have SQL Server 2008 or greater. You can do this all in one statement without any variables.
Instead of doing all the work to first get the variables and see if they don't match, you can easily do that in as part of where clause. As folks have said in the comments, you can have multiple rows as part of inserted and deleted. In order to make sure you're working with the same updated row, you need to match by the primary key.
In order to insert or update the row, I'm using a MERGE statement. The source of the merge is a union with the where clause above, the top table in the union has the older fahrer, and the bottom has the new farher. Just like your inner IFs, existing rows are matched on farher and dispodat, and inserted or updated appropriately.
One thing I noticed, is that in your example newfahrer and oldfahrer could be exactly the same, so that only one insert or update should occur (i.e. if only bzeit was different). The union should prevent duplicate data from trying to get inserted. I do believe merge will error if there was.
MERGE tbldispofahrer AS tgt
USING (
SELECT d.farher, d.dispodat, GETDATE() [laenderung]
INNER JOIN inserted i ON i.PrimaryKey = d.PrimaryKey
AND (i.fahrer <> d.fahrer OR i.beschreibk <> d.beschreik ... )
UNION
SELECT i.farher, i.dispodat, GETDATE() [laenderung]
INNER JOIN inserted i ON i.PrimaryKey = d.PrimaryKey
AND (i.fahrer <> d.fahrer OR i.beschreibk <> d.beschreik ... )
) AS src (farher, dispodat, laenderung)
ON tgt.farher = src.farher AND tgt.dispodat = src.dispodat
WHEN MATCHED THEN UPDATE SET
laenderung = GETDATE()
WHEN NOT MATCHED THEN
INSERT (fahrer,dispodat,laenderung)
VALUES (src.fahrer, src.dispodat, src.laenderung)
A: There were a few little syntax errors in the answer from Daniel.
The following code is running fine:
MERGE tbldispofahrer AS tgt
USING (
SELECT d.fahrer, d.dispodat, GETDATE() [laenderung] from deleted d
INNER JOIN inserted i ON i.satznr = d.satznr
AND (i.fahrer <> d.fahrer OR i.beschreibk <> d.beschreibk or i.bus <> d.bus or i.bzeit <> d.bzeit or i.vzeit <> d.vzeit)
UNION
SELECT i.fahrer, i.dispodat, GETDATE() [laenderung] from inserted i
INNER JOIN deleted d ON i.satznr = d.satznr
AND (i.fahrer <> d.fahrer OR i.beschreibk <> d.beschreibk or i.bus <> d.bus or i.bzeit <> d.bzeit or i.vzeit <> d.vzeit)
) AS src (fahrer, dispodat, laenderung)
ON tgt.fahrer = src.fahrer AND tgt.dispodat = src.dispodat
WHEN MATCHED THEN UPDATE SET
laenderung = GETDATE()
WHEN NOT MATCHED THEN
INSERT (fahrer,dispodat,laenderung)
VALUES (src.fahrer, src.dispodat, src.laenderung);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27828749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I insert hash values in columns with Perl's DBI? I have a hash and I am trying to insert its values into database. Hash is defined as follows:
my %hash = (
1 => 'First Word',
2 => 'Second Word is correct',
0 => 'Third word does not exist',
);
I do not know how to insert values in a database using hashes. I notice my question is similar to this question. But, none of the answers seem to be correct. On using any of the listed answers, the values in hash are not inserted, instead reference to hash is inserted i.e. ARRAY(0x9e63b30). But when I print Dumper @values, values get printed and not reference values.
Any suggestions on how to insert values and not their reference? And, what is going wrong in the solutions listed in answers to question.
@values is defined same as this question i.e.
my @values = values %hash;
Edit:
Db structure:
T1:
sid sentence
1 First Word
2 Second Word is correct
0 Third word does not exist
in above sid is keys of hash and sentence is values of hash.
this is what I tried out (it is one of the answers to question):
my @keys = keys %hash;
my @values = values %hash;
my $sth = $dbh->prepare("INSERT INTO T1(sid, sentence) VALUES (?,?);");
$sth->execute_array({},\@keys, \@values);
again, while inserting @values reference values are getting inserted.
EDIT:
_ OUTPUT _
$VAR1 = 'First Word';
$VAR2 = 'Third word does not exist';
$VAR3 = 'Second Word is correct';
_ CODE _
this is how I am inserting values into %hash
my $x=0;
foreach my $file(@files){
if ($file =~ /regex/){
push(@{$hash{$x}}, "$1 $2 $3 $4 $5 $6 $7");
}
elsif ($file =~ /regex/){
push(@{$hash{$x}}, "$1 $2 $3 $4 $5 $6");
}
elseif ($file =~ /Hs_(.+)_(.+)_(.+)_(.+)_(.+)_W.+txt/){
push (@{$hash{$x}}, "$1 $2 $3 $4 $5");
}
$x++;
}
A: That's not what you originally posted!!! You have a hash of reference to arrays. Read the perl reference tutorial (perlreftut) to learn about them.
(Use the command
perldoc perlreftut
to access this tutorial)
A: This should work.
my $key;
my $value;
while (($key, $value) = each %hash) {
$sth->bind_param(1, $key);
$sth->bind_param(2, $value);
$sth->execute();
}
A: UPDATE:
I suggest that you grab one of the functional examples from the previous thread and get it working on your machine with your database. Once you can get one of these examples working then you should be able to fix your own code.
Previous answer:
My reply on the other thread that uses execute_array() also works, I tested it before posting it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1822109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Feeding Azure Event Hub data to ReactJS
I'm trying to read data from the Azure Event Hub and display it on a simple web app using ReactJS. I've used the code sample from Microsoft to read Azure data, and this works fine standalone. I have an IoT temperature sensor and every time the sensor sends I receive the value from the function in the console:
const consumerClient = new EventHubConsumerClient("$Default",
connectionString, clientOptions);
async function getTemperature() {
consumerClient.subscribe({
processEvents: async(events, context) => {
for(const event of events){
var temperature = event.body.temperature;
var humidity = event.body.humidity;
console.log(temperature);
console.log(humidity);
}
},
processError: async (err, context) => {
console.log(`Error : ${err}`);
}
});
}
getTemperature().catch((error) => {
console.error("Error running sample:", error);
});
I now wish to use this in ReactJS component, something like this:
const returnTemperature = () => {
return (
<div className="environment">
<p>The temperature is { temperature }° Celcius.</p>
</div>
);
}
export default returnTemperature;
I am new to ReactJS and I cannot get my head around how to update the value on the web page every time the temperature received by the Azure function is updated. I have looked into useState/useEffect but not got anything working.
Any suggestions?
Thanks in advance,
Jeff
A: I made assumptions that you can work with functional components.
const Temperature = () => {
const [temperature, setTemperature] = useState();
const consumerClient = new EventHubConsumerClient(
"$Default",
connectionString,
clientOptions
);
const getTemperature = async () => {
consumerClient.subscribe({
processEvents: async (events, context) => {
for (const event of events) {
var temperature = event.body.temperature;
var humidity = event.body.humidity;
setTemperature(temperature);
console.log(temperature);
console.log(humidity);
}
},
processError: async (err, context) => {
console.log(`Error : ${err}`);
},
});
};
useEffect(() => {
getTemperature().catch((error) => {
console.error("Error running sample:", error);
});
return () => {
// cleanUpFunction if applicable
// consumerClient.unsubscribe()
};
}, []);
return (
<div className="environment">
<p>The temperature is {temperature}° Celcius.</p>
</div>
);
};
The useEffect() with empty dependencies [] array acts like componentDidMount as in, it only runs once. i.e calls your getTemperature on first load.
After that, the setState() will keep the temperature value updated, and re-render the component whenever the temperature updates.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68045188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HOW to avoid completely showing data which is in another MySQL table? I am trying to avoid some data which is already in two tables... which means... I used the select statement to get an advertisement which is stored in MySql database using Member Id and I use JOIN tables... there is no problem... all advertisements are showing perfectly which are belong to the member package...
Now the problem is... after the member clicks on an advertisement... it's stored in a table which is called "view" with the date of click, ad_id, and member id. And again the same member should not be able to click that advertisement till the next day... I need to avoid showing that advertisement data using select statements with the condition...
can anyone help me, please? I paste my query below
SELECT `advertisements`.`Ads_ID`,`advertisements`.`AdsName`,`advertisements`.`code`,`advertisements`.`Ad_Value`,`advertisements`.`images`,`advertisements`.`date` FROM `advertisements` JOIN `package_ads` ON `package_ads`.`Ads_ID`=`advertisements`.`Ads_ID` JOIN `packages` ON `packages`.`Package_ID`=`package_ads`.`Package_ID` JOIN `member_package` ON `member_package`.`Package_ID`=`packages`.`Package_ID` JOIN `members2`ON `members2`.`Mem_ID`=`member_package`.`Mem_ID` JOIN `views`ON `views`.`Mem_ID`=`members2`.`Mem_ID` WHERE `member_package`.`Mem_ID`="M100" AND `views`.`clickeddate`!="2021-12-04" AND `views`.`Ads_ID`!=`advertisements`.`Ads_ID`
A: Whenever you want avoid showing a row based on it's existence in another table you can do that using one of two ways
*
*Use not exists or not in condition
*or use a left join and add IS NULL for the joining condition.
The below query will provide you the desired result. It removes from the select query the ads that have already been visited by a particular member on a particular date.
SELECT
advertisements.Ads_ID,
advertisements.AdsName,
advertisements.code,
advertisements.Ad_Value,
advertisements.images,
advertisements.date
FROM advertisements
JOIN package_ads ON package_ads.Ads_ID=advertisements.Ads_ID
JOIN packages ON packages.Package_ID=package_ads.Package_ID
JOIN member_package ON member_package.Package_ID=packages.Package_ID
JOIN members2 ON members2.Mem_ID=member_package.Mem_ID
LEFT JOIN views ON (views.Mem_ID=members2.Mem_ID and date(views.clickeddate) = current_date and views.Ads_ID=advertisements.Ads_ID)
WHERE
member_package.Mem_ID="M100"
AND views.Ads_ID IS NULL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70225125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do i write a jQuery input string so that it works with Django query string Am working on a name search app but having a challenge getting it to work with Django query string, the challenge which i observed comes from my JavaScript input type with ${input} string when added to Django query string eg. "address/get-name/?search=${input}" doesn't return the query object or the payload data, instead it return an empty list, but when i make search through the browser it return all search query data eg "address/get-name/?search=smith", Now how do i get input through my scripts without having to use the java scripts query input type ${input} with django so let i get a query string like this "address/get-name/?search=james" ? Here is my script, Am a novice in JavaScript
<script>
new Autocomplete('#autocomplete',{
search : input => {
console.log(input)
const url = "/address/get-names/?search=${input}"
return new Promise(resolve => {
fetch(url)
.then( (response) => response.json())
.then( data => {
console.log(data.playload)
resolve(data.playload)
})
})
},
renderResult : (result, props) =>{
console.log(props)
let group = ''
if (result.index % 3 == 0 ){
group = '<li class="group">Group</li>'
}
return '${group}<li ${props}><div class="wiki title">${result.name}</div></li>'
}
})
</script>
my view.py
def get_names(request):
search = request.GET.get('search')
payload = []
if search:
objs = Names.objects.filter(name__startswith=search)
for obj in objs:
payload.append({
'name' : obj.name
})
return JsonResponse({
'200': True,
'playload': payload
})
A: The problem is your javascript syntax, it's
const url = `/address/get-names/?search=${input}`
instead of
const url = "/address/get-names/?search=${input}"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70398362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Symfony sfWidgetFormInputFile deleted my file Sorry for the many questions but I'm new to Symfony. I made a form and all it working well. I a few fields for pictures (Picture1, Picture2, Picture3, etc). I used te sfWidgetFormInputFile and all is working well with that as well. It uploads the file where it needs to and it gives it a unique name.
The problem I'm having is that those fields are set in mySQL to have a default value of "no-pic.png" so that if the user doesn't upload a picture, it will still have something to show in the post. But every time someone uploads a picture, it deletes my no-pic.png file and the posts without a picture show with a blank square. I'm thinking it's because it's set to "delete previous image" before uploading the new one to reduce excess unused pictures on the server.
I'm wondering if there's a way to have it check to see if the value is "no-pic.png" before deleting it from the folder. In case it helps, this is the code I'm using in the form.class file.
$this->widgetSchema['picture1'] = new sfWidgetFormInputFile(array('label' => 'Pictures', ));
$this->validatorSchema['picture1'] = new sfValidatorFile(array('required' => false, 'path' => sfConfig::get('sf_upload_dir').'/car', 'mime_types' => 'web_images', ));
$this->widgetSchema['picture1'] = new sfWidgetFormInputFileEditable(array(
'label' => 'Pictures',
'file_src' => '/uploads/car/'.$this->getObject()->getPicture1(),
'is_image' => true,
'edit_mode' => !$this->isNew(),
'template' => '<div>%file%<br />%input%<br />%delete%%delete_label%</div>',
));
$this->validatorSchema['picture_delete'] = new sfValidatorPass();
A: Just for reference here is the code I used.
$this->setWidget('logo_image', new sfWidgetFormInputFileEditable(array(
'file_src' => 'uploads/logos/'.$this->getObject()->getFilename(),
'edit_mode' => !$this->isNew()
)));
$validatorOptions = array(
'max_size' => 1024*1024*10,
'path' => sfConfig::get('sf_upload_dir').'/logos',
'mime_type_guessers' => array(),
'required' => false
);
if ($this->isNew())
{
$validatorOptions['required'] = true;
}
$this->setValidator('logo_image', new sfValidatorFile($validatorOptions));
$this->setValidator('logo_image_delete', new sfValidatorString(array('required' => false)));
A: I found a workaround. I had the page check to see if it was set to no-pic.png and then it displays a no-pic.png in another location. That way when it goes to upload a picture, it won't delete it. :) Thanks for your help though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11378371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I write a function to revalue levels of a factor? I have a column 'lg_with_children' in my data frame that has 5 levels, 'Half and half', 'Mandarin', 'Shanghainese', 'Other', 'N/A', and 'Not important'. I want to condense the 5 levels down to just 2 levels, 'Shanghainese' and 'Other'.
In order to do this I used the revalue() function from the plyr package to successfully rename the levels. I used the code below and it worked fine.
data$lg_with_children <- revalue(data$lg_with_children,
c("Mandarin" = "Other"))
data$lg_with_children <- revalue(data$lg_with_children,
c("Half and half" = "Other"))
data$lg_with_children <- revalue(data$lg_with_children,
c("N/A" = "Other"))
data$lg_with_children <- revalue(data$lg_with_children,
c("Not important" = "Other"))
To condense the code a little I went back data before I revalued the levels and attempted to write a function. I tried the following after doing research on how to write your own functions (I'm rather new at this).
revalue_factor_levels <- function(df, col, source, target) {df$col <- revalue(df$col, c("source" = "target"))}
I intentionally left the df, col, source, and target generic because I need to revalue some other columns in the same way.
Next, I tried to run the code filling in the args and get this message:
warning message
I am not quite sure what the problem is. I tried the following adjustment to code and still nothing.
revalue_factor_levels <- function(df, col, source, target) {df$col <- revalue(df$col, c(source = target))}
Any guidance is appreciated. Thanks.
A: You can write your function to recode the levels - the easiest way to do that is probably to change the levels directly with levels(fac) <- list(new_lvl1 = c(old_lvl1, old_lvl2), new_lvl2 = c(old_lvl3, old_lvl4))
But there are already several functions that do it out of the box. I typically use the forcats package to manipulate factors.
Check out fct_recode from the forcats package. Link to doc.
There are also other functions that could help you - check out the comments below.
Now, as to why your code isn't working:
*
*df$col looks for a column literally named col. The workaround is to do df[[col]] instead.
*Don't forget to return df at the end of your function
*c(source = target) will create a vector with one element named "source", regardless of what happens to be in the variable source.
The solution is to create the vector c(source = target) in 2 steps.
revalue_factor_levels <- function(df, col, source, target) {
to_rename <- target
names(to_rename) <- source
df[[col]] <- revalue(df[[col]], to_rename)
df
}
Returning the df means the syntax is:
data <- revalue_factor_levels(data, "lg_with_children", "Mandarin", "Other")
I like functions that take the data as the first argument and return the modified data because they are pipeable.
library(dplyr)
data <- data %>%
revalue_factor_levels("lg_with_children", "Mandarin", "Other") %>%
revalue_factor_levels("lg_with_children", "Half and half", "Other") %>%
revalue_factor_levels("lg_with_children", "N/A", "Other")
Still, using forcats is easier and less prone to breaking on edge cases.
Edit:
There is nothing preventing you from both using forcats and creating your custom function. For example, this is closer to what you want to achieve:
revalue_factor_levels <- function(df, col, ref_level) {
df[[col]] <- forcats::fct_others(df[[col]], keep = ref_level)
df
}
# Will keep Shanghaisese and revalue other levels to "Other".
data <- revalue_factor_levels(data, "lg_with_children", "Shanghainese")
A: Here is what I ended up with thanks to help from the community.
revalue_factor_levels <- function(df, col, ref_level) {
df[[col]] <- fct_other(df[[col]], keep = ref_level)
df
}
data <- revalue_factor_levels(data, "lg_with_children", "Shanghainese")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61317735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to convert Mysqli results into an array in OO Php I want to retrieve data from a table in database and display the result in an array in the form below.
array("1"=>"Value 1", "2"=>"value2")
Here is the function I tried using but I get error when I try to display the array. Please I need help on this. I'm new to OO Php.
<?php
class query {
public function listfields (){
$result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
while($row=$result->fetch_assoc()){
$this->fields[$row["id"]] = $row["name"];
}
$result->free();
}
public function fields(){
return $this->fields;
}
}
$list = new query;
$list->listfields();
$field1 = $list->fields();
echo $field1;
?>
A: Try This.
<?php
class query {
public function listfields (){
$fields = array();
$rowcnt =1;
$result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
while($row=$result->fetch_assoc()){
$this->fields[$row["id"]] = $row["name"];
//$this->fields[$rowcnt] = $row["name"]; // if you want different indexing.
$rowcnt++;
}
$result->free();
}
public function fields(){
return $this->fields;
}
}
$list = new query();
$list->listfields();
$field1 = $list->fields();
var_dump($field1);
?>
A: Instead of your function fields, you will need a property fields, which you can access.
Furthermore i suggest using getters and setters instead of a public property, im sure you will find out how.
This will return the Data in form array("1"=>"Value 1", "2"=>"value2").
class query {
public $fields;
public function fillfields ()
{
$result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
while($row=$result->fetch_assoc()){
$this->fields[] = $row["name"];
}
$result->free();
}
$list = new query;
$list->fillfields();
$field1 = $list->fields[1];
echo $field1;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11929389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: After uninstalling JPfofiler ( from Ubuntu ) when i run my application in Netbeans,it shows Error I installed JProfiler, after 2 days i uninstall Jprofiler (in Ubuntu) but when i run my application Netbeans IDE shows following Error:
Error occurred during initialization of VM
Could not find agent library /home/bsoft/jprofiler7/bin/linux-x86/libjprofilerti.so in absolute path, with error: /home/bsoft/jprofiler7/bin/linux-x86/libjprofilerti.so: cannot open shared object file: No such file or directory
Please help me to solve this problem.
Finally i solved the problem.
i just removed two files(startup_jprofiler.sh, setenv.sh) from my tomcat installation directory(/var/lib/tomcat6/bin).**
A: Please first make sure that, your JVM is working or not. Try to start JVM from command prompt. It you are able to launch java.exe file then there are some problems with your project.
You are using netbeans. So before starting netBeans remove cache of netBeans. There are changes that your netBeans is pointing to old class path of jProfiler.
Regards,
Gunjan.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12816678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to run Gant targets from within a Grails controller? Suppose I have a block of Gant code:
target(echo:"test"){
ant.echo(message:"hi")
}
setDefaultTarget("echo")
This is usually run from a command line.
How could I place the block in a Grails controller and run it from there?
A: You can use AntBuilder for this:
class FooController {
def index = {
def ant = new AntBuilder()
ant.echo(message:"hi")
}
}
A: You can create a groovy script say DynaScript_.groovy that contains your Gant code and place this script file in the {grailsHome}/scripts folder.
And then you can invoke the script file from your controller like this:
class FooController {
def index = {
def process = "cmd /c grails dyna-script".execute()
def out = new StringBuilder()
process.waitForProcessOutput(out, new StringBuilder())
println "$out"
}
}
It's important that your script name ends with an underscore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3758863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error connect between PostgreSQL and XAMPP Can someone help me to fixing the problem about connecting PostgreSQL with XAMPP?
The error is :
Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; Misc has a deprecated constructor in C:\xampp\phpPgAdmin\classes\Misc.php on line 8
I use PostgreSQL version 9.6.2-3 and XAMPP 7.1.1.0
A: That (notice) message is based on changes to PHP 7.
So an old way of using a constructor is still in use, is what that message means. It will be ok at the moment, until the support is completely removed in the future. However, I don't believe that should/would cause any connection trouble ?
What is expected is instead of having a class with a constructor like this:
<?php
class foo {
function foo() {
echo 'I am the constructor';
}
}
?>
... would now be expected to look like this:
<?php
class foo {
function __construct() {
echo 'I am the constructor';
}
}
?>
See the first section section of this PHP 7 deprecation info.
You could apply that change yourself, just comment-out the old way, and use the other constructor form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42964654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I get the current date in Javascript, using an argument There are loads of questions about the current date in JavaScript in general, but in my scenario, I have to pass in something to the date object, because usually there is a valid date I'm looking for. However, my question is - assuming the argument is undefined, what should I pass to mimic new Date()?
As an example, my code will do something like this.
const date = '2019-11-26T19:10:12.000Z'
const diff = new Date(date).getTime() - new Date().getTime()
While my components are rendering, I need to give date an initial value (while it loads from the server). During this initial loading time, I expect the diff to equal 0.
I have tried the following
new Date(undefined) >> Invalid Date
new Date('') >> Invalid Date
new Date(null) >> Thu Jan 01 1970
new Date(0) >> Thu Jan 01 1970
I'm trying to solve it in a simple way, by passing in whatever value would match no argument for Date. It seems weird, but if it's the case, I'll just assume it's JavaScript date objects being weird.
A: You can define your date with another date object as parameter.
var params = new Date;
var date = new Date(params);
console.log(date)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55302038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React form: loop through event.target to create an object I have a rather long form to submit and would like to create an object containing the name of the input as a key and the value of the input as the value. I tried looping through the event.target and event.target.elements as shown below:
handleModify(event) {
let tempPlayer = {}
Object.entries(event.target.elements).forEach(([name, input]) => {
tempPlayer[name] = input;
});
}
But I got the TypeError about looping cyclic object value. It is probably not the right way to loop those values, as I saw by logging on the console event.target and event.target.elements actually contain html form elements. I don't know how else to get the form data. My form looks like that:
<form onSubmit={e=> props.onSubmit(e)}>
<label htmlFor="name">
Name:
<input type="text" name="name" placeholder="Estelle Nze Minko" />
</label>
<label htmlFor="poste">
Poste:
<input type="text" name="poste" placeholder="Back" />
</label>
<label htmlFor="number">
Number:
<input type="number" min="0" max="100" step="1" name="number" placeholder="27" />
</label>
<label htmlFor="height">
Height (m):
<input type="number" min="1.00" max="2.34" step="0.01" name="height" placeholder="1.78" />
</label>
<label htmlFor="selects">
Number of selects:
<input type="number" min="0" max="300" step="1" name="selects" placeholder="88" />
</label>
<button type="submit">Add</button>
</form>
I was using this method because it is the way I did it on the server side by fetching the form data and looping the req.body entries. However now that I have changed the ejs templates to React I can't send the form data. That is why I am trying to loop through the values directly in the React handle method. I was unable to send the form data with fetch to my node + express server. The req.body always ended up being empty. I think it is because I am using body-parser and I was sending a new FormData() (which isn't supported?) as such:
handleModify(event) {
event.preventDefault();
fetch(`/players/modify/${this.props.match.params.id}/confirm`, {
method: "POST",
headers: { "Content-Type": "application/json" },
mode: "cors",
body: JSON.stringify(new FormData(event.target))
});
}
However, if I create the object first and then send it with fetch, it works. So, does anyone know how to loop through the form elements or how to solve the fetch problem? Thank you :))
A: That's not how you should do it in ReactJS. Here's a good tutorial for handling forms: https://reactjs.org/docs/forms.html
Basically you need to set a value to each input and handling their respective onChange callback:
e.g.
<input type="text" name="name" value={this.state.name} onChange={onNameChange} placeholder="Estelle Nze Minko" />
Then in your component you have a method onNameChange which saves the new value to a state for example:
onNameChange(event) {
const name = event.target.value;
this.setState(s => {...s, name});
}
Finally when submitting the form you need to use the values inside this.state
handleSubmit(e) {
e.preventDefault(); // prevent page reload
const {name} = this.state;
const data = JSON.stringify({name});
fetch(`/players/modify/${this.props.match.params.id}/confirm`, {
method: "POST",
headers: { "Content-Type": "application/json" },
mode: "cors",
body: data
});
}
This is all just an example, I recommend you read the link I gave you first.
LE: Using an uncontrolled component:
https://codesandbox.io/s/dark-framework-k2zkj here you have an example I created for an uncontrolled component.
basically you can do this in your onSubmit function:
onSubmit(event) {
event.preventDefault();
const tempPlayer = new FormData(event.target);
for (let [key, value] of tempPlayer.entries()) {
console.log(key, value);
}
};
A: Is there a reason you don't use controlled components? You could keep the input values in the state, and when submitting the form, you just use the values from the state.
React Docs on Forms
A: The error seems to come from storing the input itself as value, you might have ended up performing an operation on it somewhere. Instead you can store the name and value of input with:
tempPlayer[input.name] = input.value;
Demo:
const root = document.getElementById("root");
const { render } = ReactDOM;
function App() {
const handleSubmit = (event) => {
event.preventDefault();
let tempPlayer = {}
Object.entries(event.target.elements).forEach(([name, input]) => {
if(input.type != 'submit') {
tempPlayer[input.name] = input.value;
}
});
console.log(tempPlayer)
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">
Name:
<input type="text" name="name" placeholder="Estelle Nze Minko" />
</label>
<label htmlFor="poste">
Poste:
<input type="text" name="poste" placeholder="Back" />
</label>
<label htmlFor="number">
Number:
<input
type="number"
min="0"
max="100"
step="1"
name="number"
placeholder="27"
/>
</label>
<label htmlFor="height">
Height (m):
<input
type="number"
min="1.00"
max="2.34"
step="0.01"
name="height"
placeholder="1.78"
/>
</label>
<label htmlFor="selects">
Number of selects:
<input
type="number"
min="0"
max="300"
step="1"
name="selects"
placeholder="88"
/>
</label>
<button type="submit">Add</button>
</form>
);
}
render(<App />, root);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" />
PS: Uncontrolled forms are known to have performance improvements and reduced rerenders as shown in React hook form. You don't have to use a controlled component.
You may not need Controlled Components - swyx Blog
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61008250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Message: Uninitialized string offset: 0 in coideigniter I want to insert multiple rows by one click. I have an add button called add. When I click add button it loads another row. In my case when, I submit a single row it saves to data base and gives an error:
A PHP Error was encountered
Severity: Notice
Message: Uninitialized string offset: 0
Filename: controllers/boq_controller.php
Line Number: 46
and this will occurs when I click add button also. Please help me to fix those problems.
controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Boq_controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('boq_model');
}
public function index(){
$this->load->view('admin_include/header');
$this->load->view('project/boq');
}
public function create(){
if ($_POST)
{
$work_product_id=$this->input->post('work_product_id');
$work_item_description=$this->input->post('work_item_description');
$quentity=$this->input->post('quentity');
$rate=$this->input->post('rate');
$laboure_hrs=$this->input->post('laboure_hrs');
$laboure_cost=$this->input->post('laboure_cost');
$others=$this->input->post('others');
$txtmultTotal=$this->input->post('txtmultTotal');
$txtgrandTotal=$this->input->post('txtgrandTotal');
$data = array();
for ($i = 0; $i < count($this->input->post('work_product_id')); $i++)
{
$data[$i] = array(
'work_product_id' => $work_product_id[$i],
'work_item_description' => $work_item_description[$i],
'quentity' => $quentity[$i],
'rate' => $rate[$i],
'laboure_hrs' => $laboure_hrs[$i],
'laboure_cost' => $laboure_cost[$i],
'others' => $others[$i],
'txtmultTotal' => $txtmultTotal[$i],
'txtgrandTotal' => $txtgrandTotal[$i],
);
}
$this->boq_model->create($data);
}
}
}
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Boq_model extends CI_Controller{
function create($data) {
$this->db->insert_batch('boq', $data);
}
}
?>
view
<?php include 'header.php'; ?>
<div class="row clear_fix" style="width:1990px;">
<div class="col-md-12">
<div id="response"></div>
<div class="well">
<form class="form-inline" role="form" id="frmadd" action="<?php echo base_url() ?>index.php/boq_controller/create" method="POST">
<table class="table" id="boq_tbl">
<thead>
<th>Work Product Id</th>
<th>Work Item Description</th>
<th>Quentity</th>
<th>Unit</th>
<th>Rate</th>
<th>Laboure-Hrs</th>
<th>Labour Cost</th>
<th>Others</th>
<th>Total</th>
<thead>
<tbody>
<tr class="txtMult">
<td><input type="text" name="work_product_id" class="form-control" id="work_product_id" placeholder=""></td>
<td><input type="text" name="work_item_description" class="form-control" id="work_item_description" placeholder=""></td>
<td><input type="text" name="quentity" id="" class="form-control val1" /></td>
<td><select style=" height: 33px; width: 102px; border-radius: 2px;" >
<option value=""selected> </option>
<option value="cube">cube</option>
<option value="sq.ft">sq.ft</option>
<option value="Cwts">Cwts</option>
<option value="Gal" >Gal</option>
</select></td>
<td><input type="text" name="rate" class="form-control val2"/></td>
<td><input type="text" name="laboure_hrs" id="" class="form-control val3" /></td>
<td><input type="text"name="laboure_cost" id="" class="form-control val4"/></td>
<td><input type="text" name="others" class="form-control" id="others" placeholder=""></td>
<td>
<span class="multTotal">0.00</span><input type="text" id="txtmultTotal" name="txtmultTotal">
<!-- <input type="text" class="multTotal" placeholder="0.00">-->
</td>
</tr>
</tbody>
</table>
<p align="right">
Grand Total# <span id="grandTotal">0.00</span> <input type="text" id="txtgrandTotal" name="txtgrandTotal">
<button id="insert-more" class="btn btn-primary">ADD</button>
</p>
<div class="form-group">
<input type="submit" class="btn btn-success" id="btn btn-success" value="submit">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
$("#insert-more").click(function () {
$("#boq_tbl").each(function () {
var tds = '<tr class="txtMult">';
jQuery.each($('tr:last td', this), function () {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$("#boq_tbl").on("keyup", ".txtMult input", multInputs);
function multInputs() {
var mult = 0;
$("tr.txtMult").each(function () {
var val1 = $('.val1', this).val();
var val2 = $('.val2', this).val();
var val3 = $('.val3', this).val();
var val4 = $('.val4', this).val();
var total = (val1 * val2 ) + (val3 * val4);
$('.multTotal',this).text(total);
$('#txtmultTotal',this).val(total);
mult += total;
});
$("#grandTotal").text(mult);
$('#txtgrandTotal').val(mult);
}
</script>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32067216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: syntax error near unexpected token `newline' for my simple if statement? #include <stdio.h>
int main(void)
{
char input;
printf("Enter a character: ");
scanf("%c", &input);
if (input == 'a') {
printf("A\n");
} else {
printf("B\n");
}
return (0);
}
What am I doing wrong? this should be easy. I don't understand.
A: Your program is perfectly correct.
The error message -bash: syntax error near unexpected token 'newline' is produced by bash, the command line interpreter, not the compiler.
There are a few potential reasons for this, but here is the most likely:
*
*You are running the program with bash instead of having the system execute the binary, which is what happens if you typed . ./prog or . prog instead of ./prog.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41782969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: prevent yeoman.io from minifying images So I've been using yeoman.io for my projects and I have a set folder structure for my images. But when I build it changes the file name of my files.
I even use:
$ yeoman build:text
because I want to only minify my css,js and html templates, yet it still minifies the images.
Not sure if im doing something wrong.
EDIT:
I commented out all instances of img in the gruntfile and that seemed to work, but I dont think thats the right way.
A: You mean image optimization or revisioning? There is no problem to configure GruntFile.js to your own needs. It makes Yeoman/Grunt very powerful, because it is highly adaptable.
If you don't want image optimization, remove the configuration in the img task.
// Optimizes JPGs and PNGs (with jpegtran & optipng)
img: {
},
If you dont want the renaming of image files, remove the img line from the rev task:
// renames JS/CSS to prepend a hash of their contents for easier
// versioning
rev: {
js: 'scripts/**/*.js',
css: 'styles/**/*.css'
},
A: If you remove the image revving it will bust your cache, you should try to keep the revving and update your JS files instead.
Try updating your usemin block to something like this:
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
js: '<%= yeoman.dist %>/scripts/{,*/}*.js',
options: {
assetsDirs: [
'<%= yeoman.dist %>',
'<%= yeoman.dist %>/images',
'<%= yeoman.dist %>/styles'
],
patterns: {
js: [
[/(images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images']
]
}
}
}
You should already have the usemin method, just add the js attribute with you js path regex and add the pattern attribute.
This will replace all occurrences of the image in your JS files with the new revved version, so that the clients' browsers don't use a cached image instead of a new one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14262460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Svg icon not working on desktop but work fine on mobile Hello my svg icons are not working on desktop i get only a white space but the icon work fine on mobile devices this is my code :
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="none"><g clip-path="url(#a)" fill="#000"><path d="M13.079 49.653H5.137v1.682h7.942v-1.682ZM25.476 49.653h-7.942v1.682h7.942v-1.682ZM37.873 49.653H29.93v1.682h7.942v-1.682ZM50.27 49.653h-7.942v1.682h7.942v-1.682Z"></path><path d="M0 0v56h56V0H0Zm54.255 1.744v9.968H1.745V1.744h52.51Zm0 11.712v31.89H10.997l-3.346-3.4H1.745v-28.49h52.51Zm-52.51 40.8V43.69H6.92l3.347 3.4h43.989v7.164H1.744Z"></path><path d="M8.095 5.557H5.944v1.745h2.15V5.557ZM49.807 5.557h-7.35v1.745h7.35V5.557ZM17.354 39.71l1.095-1.358-9.569-7.718 8.864-7.396-1.118-1.34-10.496 8.76 11.224 9.052ZM34.54 38.371l1.142 1.319 10.483-9.08-11.236-8.73-1.07 1.377 9.557 7.425-8.877 7.69ZM30.347 16.43l-9.5 26.172 1.64.595 9.5-26.171-1.64-.596ZM5.66 45.448a.765.765 0 1 0-1.53 0 .765.765 0 0 0 1.53 0Z"></path></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h56v56H0z"></path></clipPath></defs></svg>
and this is my website :
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74040288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: can't return observable of customError in network call I want to use catchError for getting back my error as custom type.
At first, I want my network layer return Observable and then in ViewModel I subscribed it for .OnNext, .OnError, .OnCompleted events, But I don't know how should I handle Errors such as 4xx, 5xx network status code and then, them return my Custom Error Object!
My Login ViewModel :
func getAccessToken() {
let network = NetworkRequest()
network.logInRequest(tokenType: .guest, token: "cce577f6021608", secondKey: "09128147040", client: "cce577f6021608bc31424d209cbf5120c3683191").subscribe(onNext: { loginData in
self.token.onNext(loginData.access_token)
}, onError: { error in
print("The Error is: \(error.localizedDescription)")
}, onCompleted: {
print("Its Completed")
}).disposed(by: bag)
}
My network layer function:
class NetworkRequest: NSObject {
var rxProvider: MoyaProvider<WebServiceAPIs>
override init() {
rxProvider = MoyaProvider<WebServiceAPIs>( plugins: [ NetworkLoggerPlugin(verbose:true) ])
}
func logInRequest(tokenType: accessTokenTypeEnum, token: String, secondKey: String, client: String) -> Observable<LoginModel> {
return rxProvider.rx
.request(WebServiceAPIs.getAccessToken(tokenType: tokenType.rawValue, token: token, secondKey: secondKey, client: client))
.filterSuccessfulStatusCodes()
.catchError({ error -> Observable<NetworkError> in
return //Observable.just() => I want to return a custom network error as obserable
})
.map(LoginModel.self, atKeyPath: nil, using: JSONDecoder(), failsOnEmptyData: true).asObservable()
}
}
thanks for any help
A: Moya returns MoyaError enum in error block which you can handle by extracting the error type using switch on MoyaError and then using statusCode to convert to NetworkError enum
func logInRequest(tokenType: accessTokenTypeEnum, token: String, secondKey: String, client: String) -> Observable<LoginModel> {
return sharedProvider.rx
.request(WebServiceAPIs.getAccessToken(tokenType: tokenType.rawValue, token: token, secondKey: secondKey, client: client))
.filterSuccessfulStatusCodes()
.catchError({ [weak self] error -> Observable<NetworkError> in
guard let strongSelf = self else { return Observable.empty() }
if let moyaError = error as? MoyaError {
let networkError = self?.createNetworkError(from: moyaError)
return Observable.error(networkError)
} else {
return Observable.error(NetworkError.somethingWentWrong(error.localizedDescription))
}
})
.map(LoginModel.self, atKeyPath: nil, using: JSONDecoder(), failsOnEmptyData: true).asObservable()
}
func createNetworkError(from moyaError: MoyaError) -> NetowrkError {
switch moyaError {
case .statusCode(let response):
return NetworkError.mapError(statusCode: response.statusCode)
case .underlying(let error, let response):
if let response = response {
return NetworkError.mapError(statusCode: response.statusCode)
} else {
if let nsError = error as? NSError {
return NetworkError.mapError(statusCode: nsError.code)
} else {
return NetworkError.notConnectedToInternet
}
}
default:
return NetworkError.somethingWentWrong("Something went wrong. Please try again.")
}
}
You can create your custom NetworkError enum like below which will map statusCode to custom NetworkError enum value. It will have errorDescription var which will return custom description to show in error view
enum NetworkError: Swift.Error {
case unauthorized
case serviceNotAvailable
case notConnectedToInternet
case somethingWentWrong(String)
static func mapError(statusCode: Int) -> NetworkError {
switch statusCode {
case 401:
return .unauthorized
case 501:
return .serviceNotAvailable
case -1009:
return .notConnectedToInternet
default:
return .somethingWentWrong("Something went wrong. Please try again.")
}
}
var errorDescription: String {
switch self {
case .unauthorized:
return "Unauthorised response from the server"
case .notConnectedToInternet:
return "Not connected to Internet"
case .serviceNotAvailable:
return "Service is not available. Try later"
case .somethingWentWrong(let errorMessage):
return errorMessage
}
}
}
A: In my experience, '.materialize()' operator is the perfect solution for handling HTTP errors.
Instead of separate events for success and error you get one single wrapper event with either success or error nested in it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52815543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create a Server using ServerSocket to connect two or more client device via wifi Am trying to connect (using ServerSocket for server) to android device via wifi. But the problems seems to be the ip of the server. what ip can i use, or is there some other way round.
-Code Sample
//ServerSide
WifiManager wmanager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
String addr = String.valueOf(wmanager.getConnectionInfo().getIpAddress());
ServerSocket server = ServerSocket(3000, 3, InetAddress.getByName(addr));
Socket s = server.accept();
//ClientSide
//Howerver testing with terminal<telnet: open wifiIp 3000> returns connection error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29771308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: gcc cross compilation for powerpc7448 I want to cross compile the gcc for powerpc7448, and after this I want to run one simple program and get the elf from the cross compiled gcc for powerpc7448,I am using the linux OS,could anyone please suggest me the steps, cross compilation gcc for powerpc7448(any link) and what are all the components are required for cross compilation,Thanks in advance.
A: Try ELDK cross compiler toolchain (linux distributions) for PowerPC:
ftp://ftp.denx.de/pub/eldk/4.2/ppc-linux-x86/distribution/README.html
Check Eldk version 4.2.
Help: https://www.denx.de/wiki/ELDK-5/WebHome
ppc_74xx-gcc from eldk can be used to compile for your platform.
`
$ ppc_74xx-gcc -c myfile.c
`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60389225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble understanding a specific C implementation of Merge Sort I'm trying to follow this code step by step but still I can't understand certain steps it's taking.
void merge (int *a, int n, int m) {
int i, j, k;
int *x = malloc(n * sizeof (int));
for (i = 0, j = m, k = 0; k < n; k++) {
x[k] = j == n ? a[i++]
: i == m ? a[j++]
: a[j] < a[i] ? a[j++]
: a[i++];
}
for (i = 0; i < n; i++) {
a[i] = x[i];
}
free(x);
}
void merge_sort (int *a, int n) {
if (n < 2)
return;
int m = n / 2;
merge_sort(a, m);
merge_sort(a + m, n - m);
merge(a, n, m);
}
Here's a simple example so that you can see what the issues are. It's sorting the integer array {4,3,2,1} .
#include <stdio.h>
#include <stdlib.h>
void merge (int *a, int n, int m) {
int i, j, k;
int *x = malloc(n * sizeof (int));
for (i = 0, j = m, k = 0; k < n; k++) {
x[k] = j == n ? a[i++]
: i == m ? a[j++]
: a[j] < a[i] ? a[j++]
: a[i++];
}
for (i = 0; i < n; i++) {
a[i] = x[i];
}
free(x);
}
void merge_sort (int *a, int n) {
if (n < 2)
return;
int m = n / 2;
int g;
printf("a before merge_sort(a,m) %i\n",a);
printf("m %i\n",m);
printf("n %i\n",n);
printf("\n");
for(g=0;g<m;++g) printf("%i\n", a[g]);
merge_sort(a, m);
printf("a after merge_sort(a,m) %i\n",a);
printf("m %i\n",m);
printf("n %i\n",n);
printf("\n");
for(g=0;g<m;++g) printf("%i\n", a[g]);
merge_sort(a + m, n - m);
printf("a after merge_sort(a+m, n-m) %i\n",a);
printf("m %i\n",m);
printf("n %i\n",n);
printf("\n");
for(g=0;g<m;++g) printf("%i\n",a[g]);
merge(a, n, m);
printf("a after merge(a,n,m) %i\n ",a);
printf("m %i\n",m);
printf("n %i\n",n);
for(g=0;g<m;++g) printf("%i\n",a[g]);
}
int main(){
int test[4] = {4,3,2,1};
int i;
merge_sort(&test[0],4);
printf("\nFinal result:\n");
for(i=0;i<4;++i){
printf("%i ",test[i]);
}
printf("\n");
}
And here's the output.
Begin of if
End of if(no return)
a before merge_sort(a,m) 0xbfadcebc
m 2
n 4
4
3
Begin of if
End of if(no return)
a before merge_sort(a,m) 0xbfadcebc
m 1
n 2
4
Begin of if
a after merge_sort(a,m) 0xbfadcebc
m 1
n 2
4
Begin of if
a after merge_sort(a+m, n-m) 0xbfadcebc
m 1
n 2
4
a after merge(a,n,m) 0xbfadcebc
m 1
n 2
3
a after merge_sort(a,m) 0xbfadcebc
m 2
n 4
3
4
Begin of if
End of if(no return)
a before merge_sort(a,m) 0xbfadcec4
m 1
n 2
2
Begin of if
a after merge_sort(a,m) 0xbfadcec4
m 1
n 2
2
Begin of if
a after merge_sort(a+m, n-m) 0xbfadcec4
m 1
n 2
2
a after merge(a,n,m) 0xbfadcec4
m 1
n 2
1
a after merge_sort(a+m, n-m) 0xbfadcebc
m 2
n 4
3
4
a after merge(a,n,m) 0xbfadcebc
m 2
n 4
1
2
Final result:
1 2 3 4
This is what's puzzling me:
Begin of if
a after merge_sort(a+m, n-m) 0xbfadcebc
m 1
n 2
4
a after merge(a,n,m) 0xbfadcebc
m 1
n 2
3
I'd expect a+m to change the address of a from 0xbfadcebc to something else, but it simply produces the number 4 as an output again. It's as if merge(a+m,n-m) didn't have any effect and produced the same as if I had written merge(a,n-m).
Furthermore, merge(a,n,m) is not a recursive function, so I'd just expect the function to end after running it.
I don't get how this:
a after merge_sort(a,m) 0xbfadcebc
m 2
n 4
3
4
...can be the next step after merge(a,n,m).
A: Commented code:
/* a = ptr to sub-array */
/* 0 = starting index */
/* m = mid point index */
/* n = ending index */
/* left half indices = 0 to m-1 */
/* right half indices = m to n */
void merge (int *a, int n, int m) {
int i, j, k;
int *x = malloc(n * sizeof (int)); /* allocate temp array */
for (i = 0, j = m, k = 0; k < n; k++) {
x[k] = j == n ? a[i++] /* if end of right, copy left */
: i == m ? a[j++] /* if end of left, copy right */
: a[j] < a[i] ? a[j++] /* if right < left, copy right */
: a[i++]; /* else (left <= right), copy left */
}
for (i = 0; i < n; i++) { /* copy x[] back into a[] */
a[i] = x[i];
}
free(x); /* free temp array */
}
/* a = ptr to sub-array */
/* n = size == ending index of sub-array */
void merge_sort (int *a, int n) {
if (n < 2) /* if < 2 elements nothing to do */
return;
int m = n / 2; /* m = mid point index */
merge_sort(a, m); /* sort a[0] to a[m-1] */
merge_sort(a + m, n - m); /* sort a[m] to a[n-1] */
merge(a, n, m); /* merge the two halves */
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45782884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling mulltiple methods of the same class In my class Helper() I have 2 methods which look like this:
public function is_active_page($page) {
$url = explode("/",$_SERVER["REQUEST_URI"]);
if (end($url) === $page) {
return true;
}
}
public function go_to_dashboard() {
if (isset($_SESSION['login'])) {
header('Location: http://example.com');
}
}
I would now like to call them like this: $helper->is_active_page('page')->go_to_dashboard(); instead of using 2 lines for each method.
For some reason this is not working for me. Why?
A: In order to be able to chain methods, those methods need to return the original Helper instance. Try returning $this from inside the methods. Like RomanPerekhrest commented however, I dont think the methods you listed here are suitable for chaining. You would be better off with adding another method to your class that combines the two you stated here.
I'm not exactly sure what you are trying to do, but something along the lines of below might be what you are looking for:
public function redirect($page){
if($this->is_active_page($page)){
$this->go_to_dashboard();
}
}
Lastly, you could think about reducing the scope of your is_active_page and go_to_dashboard functions, if they no longer need to be called from outside the Helper class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42332265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I get Symbolic-Name of an Osgi bundle which is using one of my exported packages? Inside one of my implementation libraries I want to know from which user library request is coming from?
Bundle A
ClientCode -- > ServiceInterface
Bundle B
ClientCode -- > ServiceInterface
Bundle C
ServiceInterface
ServiceImpl.
And those interfaces are resolved by one of impl. bundles (Bundle C). Inside that bundle I want to know from which bundle request is coming from (A or B)?
Thanks.
A: You could add a parameter for the BundleContext to your interface methods. Then, when the client code calls into your service, passing in its bundle context, you can call context.getBundle().getSymbolicName() or other methods to get information about the bundle from which the call came.
A: The correct way to do this is to use a ServiceFactory, as explained in the OSGi specification. If you register your service as a service factory, you can supply an implementation for each "client" (where "client" is defined as bundle, invoking your service). This allows you to know who is invoking you, without the client having to specify anything as it's clearly not good design to add a parameter called BundleContext (unless there is no other way).
Some "pseudo" code:
class Bundle_C_Activator implements BundleActivator {
public void start(BundleContext c) {
c.registerService(ServiceInterface.class.getName(),
new ServiceFactory() {
Object getService(Bundle b, ServiceRegistration r) {
return new ServiceImpl(b); // <- here you hold on to the invoking bundle
}
public void ungetService(Bundle b, ServiceRegistration r, Object s) {}
}, null);
}
}
class ServiceImpl implements ServiceInterface {
ServiceImpl(Bundle b) {
this.b = b; // <- so we know who is invoking us later
}
// proceed here with the implementation...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2600900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to restrict input values and save it separately jQuery? I am a jquery beginner working on a input as shown in the picture where the user has to follow proper syntax like "name=value". I want to make validations if the entered data is in the correct format or if there any white spaces on the right or left side of "=". For that, I can use trim(). The part I am struggling with is how to break the user input into 3 parts "name", "=" and "value" because later on, I want to sort the list by name and by value. Please, someone, point me in the right direction.
Image Link
My code
$("#add-pair").on("submit", function(e) {
e.preventDefault();
const addItem = $('#add-pair > input[type="text"]').val();
if (!addItem || addItem === null) {
$("#add-pair").append(
'<div class="error">Cannot post empty string. Please add Name=Value!</div>'
);
setTimeout(function() {
$(".error").fadeOut();
}, 4000);
} else {
$li = $("<li>");
$textSpan = $("<span>")
.addClass("name")
.text(addItem);
$deleteSpan = $("<span>")
.addClass("btn delete")
.text("Delete");
$listItem = $li.append($textSpan).append($deleteSpan);
$("#list")
.hide()
.prepend($listItem)
.fadeIn(500);
}
});
<form id="add-pair">
<input type="text" name="addPair" id="input" placeholder="Name=Value..." />
<button class="btn">Add</button>
</form>
A: Try using split to split along the string before the = and after the =:
const inputStr1 = ' name = value ';
const inputStr2 = ' name value ';
function validate(str) {
if (!str.includes('=')) {
console.log('no = found, returning');
return;
}
const [cleanedName, cleanedValue] = str.split('=').map(uncleanStr => uncleanStr.trim());
console.log('returning values "' + cleanedName + '" "' + cleanedValue + '"');
return [cleanedName, cleanedValue];
}
const results1 = validate(inputStr1);
const results2 = validate(inputStr2);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49524517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get the values of the params from a form I need to work with the inputs from a form before storing the records. I'm stuck at simply reading the params.
In my create controller, I have
def create
@document_history = DocumentHistory.new(document_history_params)
$temp1 = params[:by]
$temp2 = params[:sent_to]
In my show, I have
<hr>
<%= $temp1 %>
<hr>
<%= $temp2 %>
On the show, $temp1 and $temp2 are blank. How can I read the params and store the value to a variable?
A: I am assuming that your fields are named in the standard rails way.That is,If your input fields are named like this document_history[name] then the correct way to access them would be params[:document_history][:name].
To verify if they have been copied to your variable you can print to log.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35461528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Implement Linked list where data is separate In C, can a Linked list be implemented and modified so that rather having the data stored within each node of the list, it is separated from the node. And a pointer within the node points to the data?
A: The answer is yes. Just instead of keeping keys in the nodes, you store pointers to keys:
#include <stdio.h>
#include <stdlib.h>
typedef struct s_ListNode {
struct s_ListNode *next;
int *pointer;
} ListNode;
main() {
int a = 3, b = 5;
ListNode *root = malloc(sizeof(ListNode));
ListNode *tail = malloc(sizeof(ListNode));
ListNode *iter;
root->next = tail;
root->pointer = &a;
tail->next = NULL;
tail->pointer = &b;
for(iter=root; iter!=NULL; iter=iter->next) {
printf("%d\n", *iter->pointer);
}
return 0;
}
A: A. Yes, it is possible.
B. Why doing it ? the node is already a pointer by itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19843970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery post to the same PHP page I am creating a jQuery search bar, that will asynchronously send the inputted value from a form from the client side to the same page on the server side (in PHP). Then I can search my database with the value. Unfortunately when I send this value, using $.ajax, and attempt to echo out the value, I don't get the value at all. How can I receive my value? I've tried print_r, var_dump, echo but to no avail.
Here is my form:
<form method = 'POST'>
<input id="myInput" type ="text" name ="value"
placeholder="press enter when finished" >
</form>
And here is my script to make the call. I get the value in my console when I press enter (key===13), but it seems to be the furthest my variable (value) seems to go.
$(document).ready(function(){
$('#myInput').bind('keypress', function(e){
if(e.keyCode ===13){
let value = $(this).val().toLowerCase();
console.log(value);
e.preventDefault(); //stops the damn page refreshing
$.ajax({
type: "POST",
data: value
});
};
});
});
I haven't put the URL in the AJAX call for a reason: I'm sending to the same page.
Here is the code (further up the page) that I'm using to echo out the posted value, on the same page.
if(isset($_POST['value'])) { echo $_POST['value']; exit; }
No matter what I seem to do, my value isn't sent to the page! I've tried to add in the URL, I've added "success" to the call.... nothing seems to work.
How can I successfully send my data?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73318747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I play an animation, wait, then fade out? (In unity) Basically what the title asks. I want to play my animation, then after the animation is finished playing, I want there to be a small delay before it fades out of the scene in about 2 seconds. After it fades out, it should be disabled and reset.
Here's my code so far, but when I set unlocking to true, it does nothing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationController : MonoBehaviour
{
public Animator anim;
public SpriteRenderer sr;
public bool unlocking;
Sprite unlockSprite;
Sprite lockSprite;
Color temp;
// Start is called before the first frame update
void Start()
{
unlocking = false;
unlockSprite = Resources.Load<Sprite>("unlock");
lockSprite = Resources.Load<Sprite>("lock");
}
// Update is called once per frame
void Update()
{
if (unlocking) {
anim.Play("unlock");
unlocking = false;
sr.sprite = unlockSprite;
System.Threading.Thread.Sleep(1000);
StartCoroutine(FadeTo(0.0f, 2.0f));
temp = new Color(sr.color.r, sr.color.g, sr.color.b, 0f);
sr.color = temp;
gameObject.SetActive(false);
sr.sprite = lockSprite;
temp = new Color(sr.color.r, sr.color.g, sr.color.b, 1f);
sr.color = temp;
}
}
IEnumerator FadeTo(float aValue, float aTime)
{
float alpha = sr.color.a;
for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / aTime)
{
Color newColor = new Color(sr.color.r, sr.color.g, sr.color.b, Mathf.Lerp(alpha, aValue, t));
sr.color = newColor;
yield return null;
}
}
}
UPDATED CODE:
anim.Play("unlock");
unlocking = false;
if (animInfo.normalizedTime >= 1)
{
anim.enabled = false;
sr.sprite = unlockSprite;
StartCoroutine(FadeTo(0.0f, 2.0f));
temp = new Color(sr.color.r, sr.color.g, sr.color.b, 0f);
sr.color = temp;
gameObject.SetActive(false);
sr.sprite = lockSprite;
temp = new Color(sr.color.r, sr.color.g, sr.color.b, 1f);
sr.color = temp;
}
A: One of ways to pull it off, is to make another coroutine, something like that:
IEnumerator UnlockSequence()
{
while (animInfo.normalizedTime < 1.0f)
{
yield return null;
}
anim.enabled = false;
sr.sprite = unlockSprite;
yield return new WaitForSeconds(1.0f);
yield return StartCoroutine(FadeTo(0.0f, 2.0f));
// everything else
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59903159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: REPLACE INTO, does it re-use the PRIMARY KEY? The REPLACE INTO function in MySQL works in such a way that it deletes and inserts the row. In my table, the primary key (id) is auto-incremented, so I was expecting it to delete and then insert a table with id at the tail of the database.
However, it does the unexpected and inserts it with the same id! Is this the expected behaviour, or am I missing something here? (I am not setting the id when calling the REPLACE INTO statement)
A: That is expected behavior. Technically, in cases where ALL unique keys (not just primary key) on the data to be replaced/inserted are a match to an existing row, MySQL actually deletes your existing row and inserts a new row with the replacement data, using the same values for all the unique keys. So, if you look to see the number of affected rows on such a query you will get 2 affected rows for each replacement and only one for the straight inserts.
A: This is an expected behavior if you have another UNIQUE index in your table which you must have otherwise it would add the row as you would expect. See the documentation:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, “INSERT Syntax”.
https://dev.mysql.com/doc/refman/5.5/en/replace.html
This really also makes lot of sense because how else would mySQL find the row to replace? It could only scan the whole table and that would be time consuming. I created an SQL Fiddle to demonstrate this, please have a look here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12205158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: What is role of #!usr/bin/perl -n? What is the role of #!usr/bin/perl -n? I am tried to refer to the books and other sources but i am not get the better idea. It behave like the STDIN, for example my @array = <> many input is store into the @array. -n also behave like this but how to store the input value in data types.? And which is the original function?
A: It essentially provides you the plumbing of wrapping what you put on the command line inside:
while (<>) { ... What you have on cmd line here ... }
So:
perl -e 'while (<>) { if (/^(\w+):/) { print "$1\n"; } }'
and this:
perl -n -e 'if (/^(\w+):/) { print "$1\n" }'
are equivalent.
A: with the -n option, the code in the script will be interpreted as if you writed this :
while (<>) {
<code>
}
for example, the following script, called with a file as an argument will replace all the end of line of the file and send the result on the standard output:
#!usr/bin/perl -n
~s/\n//;
print ;
it must be called like this:
perl script.pl <file>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25916529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Can LINQ support this simple algorithm? I've been trying to learn LINQ, and I'm wondering if there is a way for LINQ to perform the following:
I have a list of objects that consume data from an array in a serial fashion. I am trying to do two things with one loop:
*
*Use the input array to populate the objects serially with data where each object consumes a different amount of data.
*Keep track of "Index" which tells me how much data has been consumed.
Here is an example with code:
class MyBase {
virtual int ReadData(int[] array, int StartingIndex) { }
}
class Derived1 : MyBase {
int a;
public override int ReadData(int[] array, int StartIndex) {
a = array[StartingIndex];
return StartingIndex + 1;
}
}
class Derived2 : MyBase {
int a, b;
public override int ReadData(int[] array, int StartIndex) {
a = array[StartingIndex];
b = array[StartingIndex + 1];
return StartingIndex + 2;
}
}
class Program {
public static void Main() {
MyBase[] array = new MyBase[] {
new Derived1(),
new Derived2(),
new Derived1()
}
int[] input = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int Index = 0
for (int i = 0; i < input.Length; i++) {
Index = array[i].ReadData(input, Index);
}
}
}
The end result is that these objects have the following values:
Object 0 has the val 1
Object 1 has the val 2 and 3
Object 2 has the val 4
But I can't figure out how to do this with LINQ.
A: A LINQish way to do this (rather than just a LINQish way to write the for loop) is to pass the array on to each method and have it take what it needs and return the rest. You won't have the final index in hand, but you will have the remainder:
MyBase[] array = new MyBase[] { new Derived1() , new Derived2(), new Derived1()}
int [] input = new int[] { 1,2,3,4,5,6,7,8,9};
IEnumerable<int> unusedInputs = input;
foreach (MyBase entity in array)
{
unusedInputs = entity.ReadData(unusedInputs);
}
and your ReadData code goes like this:
public override IEnumerable<int> ReadData( IEnumerable<int> data)
{
a = data.Take(1).Single();
return Data.Skip(1);
}
public override IEnumerable<int> ReadData( IEnumerable<int> data)
{
var dataRead = data.Take(2);
a = dataRead.First();
b = dataRead.Skip(1).First();
return data.Skip(2);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24967656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kali Linux update-alternatives --config java I am attempting to use L3MON to build an apk. It requires me to select Java 1.80 OpenJDK as I am currently running, however when I use sudo update-alternatives --config java it does not supply me with the option to select 1.80. See below.
I have installed Java 8 OpenJDK and it reflects in my /usr/lib/jvm file structure. I just can't seem to get the option to select it to use for L3MON.
A: To switch between installed JDKs:
*
*List Java alternatives:
update-java-alternatives -l
*Find the line with the Java version that you want to select.
*The output of update-java-alternatives -l will look something like this if Java 8 was installed by sudo apt install openjdk-8-jdk which also matches the 2nd screenshot in your question.
java-1.11.0-openjdk-amd64 1111 /usr/lib/jvm/java-1.11.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1081 /usr/lib/jvm/java-1.8.0-openjdk-amd64
The first part of the second line there is java-1.8.0-openjdk-amd64.
*Set the first part of the line you want as the Java alternative.
sudo update-java-alternatives -s java-1.8.0-openjdk-amd64
To sum it all up the key thing to watch for here is that you have installed both of the Java versions that you want to switch between with apt so that both Java versions will be recognized.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71716697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What type of behaviour is this? This question is looking for a standardese quote explicitly explaining why this behavior is wrong.
The code below including <stdio.h> inside main ,
int main()
{
#include <stdio.h>
printf("hello , world \n");
return 0;
}
On gcc -Wall in.c -o in.out It successfully compiles and prints hello , world.
But on clang in.c -o in.out It gives me this error :
/usr/include/stdio.h:353:12: error: implicit declaration of 'fprintf' requires
inclusion of the header <stdio.h>
extern int fprintf (FILE *__restrict __stream,
^
1 error generated.
My doubt is what kind of behaviour is this ? Is this undefined behaviour or what ?
Also I am not able to find the documentation related to it.
EDIT : The problem is that I found this code somewhere similar to it but I can't post that code exactly so I posted this kind of Demo code.I know the Placing stdio.h outside the main.
A: C99, 7.1.2/4:
[...] If
used, a header shall be included outside of any external declaration or definition, and it
shall first be included before the first reference to any of the functions or objects it
declares, or to any of the types or macros it defines.
4/2:
If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint is violated, the
behavior is undefined.
6.9/4:
As discussed in 5.1.1.1, the unit of program text after preprocessing is a translation unit,
which consists of a sequence of external declarations. These are described as ‘‘external’’
because they appear outside any function (and hence have file scope).
So I think this is undefined behavior.
A: In C++11: 17.6.2.2/3:
A translation unit shall include a header only outside of any external declaration or definition, and shall
include the header lexically before the first reference in that translation unit to any of the entities declared
in that header.
main() is extern, so is not a proper context for include.
A: Try including the header file outside of the main method. Like this.
#include <stdio.h>
int main()
{
printf("hello , world \n");
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13678028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Update object in List affecting specific fields only. (Merge) I have a List of objects:
@Getter
@Setter
class Cat {
int id;
int legs;
int head;
}
List<Cat> catsLegs = new ArrayList<>();
I fill this list with some data:
for (int i = 0; i < 10; i++) {
Cat cat = new Cat();
cat.setId(i);
cat.setLegs(i + i);
cats.add(cat);
}
Then I have another list
List<Cat> catsHeads = new ArrayList<>();
I fill this list with some data:
for (int i = 0; i < 10; i++) {
Cat cat = new Cat();
cat.setId(i);
cat.setHead(i*i);
cats.add(cat);
}
Then I want to merge this two lists and if id is equal, then Cats are equal.
@Override
public boolean equals(Object o) {
if (!(o instanceof Cat)) {
return false;
}
Cat that = (Cat) o;
return this.id.equals(that.id);
}
There are more that 3 fields, but this is a basic principle.
Thanks a lot.
A: *
*Put your cats into a Map<Integer, Cat>
*Get the values of the resulting Map
*If you really need a List create a new List from the values of the Map
Here is how to merge the lists as you want to be able to over write:
Map<Integer, Cat> map = new HashMap<>();
for (Cat cat : catsLegs) {
map.put(cat.getId(), cat);
}
for (Cat cat : catsHeads) {
map.put(cat.getId(), cat);
}
Collection<Cat> cats = map.values();
// If you really need a List, you create a new one as next
List<Cat> catsList = new ArrayList<>(cats);
A: The simplest way is to loop through the List of cats and check if (catHead.id == catTail.id) but that's not really cool.
A better solution is to store your data inside a HashMap instead of a List. This way you can use the Hash Key to be the ID and the Hash Value to be the Cat object. Retrieving the object is much easier this way and it is of course much faster.
A: This is what I made. It transfers all the objects heads and I have fresh catList.size() because I don't want old currentCats objects be in final list.
public static void updateCats(List<Cat> catsFromServer) {
setAllCatsLegs(catsFromServer);
List<Cat> currentCats = getAllCats();
for (Cat currentCat : currentCats) {
for (Cat fromServer : catFromServer) {
if (currentCat.equals(fromServer)) {
fromServer.setHeads(currentcat.getHeads());
}
}
}
Contact.saveMultiple(contactsFromServer);
}
upd:
List<Cat> currentCats = getAllCats();
for (Cat cat : catsFromServier) {
int index = currentCats.indexOf(cat);
if (index != -1) {
cat.setHeads(currentCats.get(index).getHeads);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37455889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: p:autocomplete always return null in bean on ItemSelect I'm having some issues with p:autocomplete, Primefaces , the auto complete is ok, but when the user select some value, I force an ajax request to handle the selected item, but the item always return null.
How can i solve this?
Here's the view:
<h:outputLabel value="Cliente: " />
<p:autoComplete value="#{autoCompleteCliente.clienteSelecionado}"
converter="ClienteConverter" style="margin-left: 8px;width: 200px;"
id="clientecomplete"
completeMethod="#{autoCompleteCliente.completeCliente}"
var="cliente" itemLabel="#{cliente.nome}" itemValue="#{cliente}"
forceSelection="true">
<f:facet name="itemtip">
<h:panelGrid columns="2" cellpadding="5">
<f:facet name="header">
<p:graphicImage value="resources/images/chamadosIcon.png"
width="40" height="50" />
</f:facet>
<h:outputText value="Codigo: " />
<h:outputText id="codigo" value="#{cliente.codigo}" />
<h:outputText value="CNPJ " />
<h:outputText id="CNPJ" value="#{cliente.cnpj}" />
</h:panelGrid>
</f:facet>
<p:ajax listener="#{autoCompleteCliente.handleSelect}" event="itemSelect"
process=":chamadoEdicao:clientecomplete" />
</p:autoComplete>
and Here's the bean:
@ManagedBean(name = "autoCompleteCliente")
@ViewScoped
public class ClienteAutoComplete {
private Cliente clienteSelecionado;
private List<Cliente> clientes;
public ClienteAutoComplete() {
clientes = ClienteConverter.todosClientes;
}
@PostConstruct
public void construct() {
System.out.println("Iniciou autoCompleteCliente");
}
@PreDestroy
public void destroy() {
System.out.println("Fechou autoCompleteCliente");
}
public Cliente getclienteSelecionado() {
return clienteSelecionado;
}
public void setclienteSelecionado(Cliente clienteSelecionado) {
this.clienteSelecionado = clienteSelecionado;
}
/**
* Método para autocompletar o nome do cliente para disponibilizar na view
* de cadastro de chamado.
*
* @author helios-kob
* @param query
* String
* @return complete List<String>
*
*/
public List<Cliente> completeCliente(String query) {
ArrayList<Cliente> resultados = new ArrayList<Cliente>();
for (Cliente cliente : clientes) {
if (cliente.getNome().contains(query)) {
resultados.add(cliente);
}
}
return resultados;
}
public void handleSelect(SelectEvent event) {
String value = (String) event.getObject();
System.out.println("selected "+value);
}
}
A: Resolved, the main problem was on ClienteConverter, It was returning null by a if that compared one of attributes of cliente, didnn't match any.
If Help anyone, The converter comes first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18541035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: jQuery Change all names of div's children elements after clone So, I have the following jquery code that clones an element when the input value in a certain field increases.
$(document).ready(function(){
$("#nmovimentos").change(function () {
var direction = this.defaultValue < this.value
this.defaultValue = this.value;
if (direction)
{
var $div = $('div[id^="novomov"]:last');
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
var $clone = $div.clone().prop('id', 'novomov'+ num)
$clone.insertAfter('[id^="novomov"]:last');
}
else $('[id^="novomov"]:last').remove();
});
});
However, it clones a div that contains part of a form with lots of input fields.
<div id="novomov1" class="novomov">
<table id="tab">
<tr name="linear1" id="linear1">
<td>
Cardinalidade:<input type="text" name="card1" id="card1" value=""><br>
Angulo 1:<input type="text" name="param1" id="angulo1" value=""><br>
Angulo 2:<input type="text" name="param2" id="angulo2" value=""><br>
Tamanho:<input type="text" name="param3" id="tamanho1" value=""><br>
Descricao:<input type="text" name="descricao1" id="descricao1" value=""><br>
Tempo:<input type="text" name="tempo1" id="tempo1" value=""><br>
</td></tr></table></div>
I need to change the names of all the cloned div's descendents, in order to pass these paramaters to a data base. I thought of incrementing the names by 1, using the var num in the jquery function. However I'm I little lost.. so, any clues on how to do that? thank you very much!
A: Code changed to retrieve all the inputs inside the cloned div and change its name/id.
<script>
$(document).ready(function(){
$("#nmovimentos").change(function () {
var direction = this.defaultValue < this.value
this.defaultValue = this.value;
if (direction)
{
var $div = $('div[id^="novomov"]:last');
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
var $clone = $div.clone().prop('id', 'novomov'+ num)
$clone.insertAfter('[id^="novomov"]:last');
// get all the inputs inside the clone
var inputs = $clone.find('input');
// for each input change its name/id appending the num value
$.each(inputs, function(index, elem){
var jElem = $(elem); // jQuery element
var name = jElem.prop('name');
// remove the number
name = name.replace(/\d+/g, '');
name += num;
jElem.prop('id', name);
jElem.prop('name', name);
});
}
else $('[id^="novomov"]:last').remove();
});
});
</script>
A: Instead of parsing the id of the element to get the number you should use the data attribute. Also since you are using jQuery you can use .last() to get the last element with that id. Hope this helps.
$('#nmovimentos').on('change', function () {
var direction = this.defaultValue < this.value,
$last = $('#novomov').last(),
$clone,
num;
this.defaultValue = this.value;
if (direction) {
// add id in a data attribute instead of parsing the id
num = parseInt($last.data('id'), 10) + 1;
// set clone id data attribute to have the latest number
$clone = $last.clone().data('id', num);
// add clone after the last div
$last.after($clone);
} else {
$last.remove();
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31677068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: return value from datepickerCallback function I am new to Angular js, and for my application i am using a datePickerCallback function to get the date selected. How can i return the value of this function ? i actually want to get the date selected and pass it in a http request to get the data corresponding to this date.
self.datePickerCallbackFrom = function(val) {
if (typeof(val) === 'undefined') {
console.log('Date not selected');
} else {
console.log('Selected date is : ', val);
self.dateFrom = val;
}
};
HTML:
<ionic-datepicker date="exCtrl.dateFrom"
disablepreviousdates="false"
disablefuturedates="true"
callback="exCtrl.datePickerCallbackFrom"
title="exCtrl.titleFrom">
A: It looks like you have to pass callback as an option not a html attribute.
https://github.com/rajeshwarpatlolla/ionic-datepicker#readme
var options = {
callback: function (val) { //Mandatory
if(typeof(val) === 'undefined') {
console.log('Date not selected');
} else {
console.log('Selected date is : ', val);
self.dateFrom = val;
}
}
};
$scope.openDatePicker = function(){
ionicDatePicker.openDatePicker(options);
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38330732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: tutorials for developing facebook applications in android Can any one please suggest me good tutorials (other than official) for learning basics to develop Facebook apps in Android.
I am searching in internet but I am failing to get good ones.
A: checkout this: http://developers.facebook.com/docs/guides/mobile/#android
This will surely help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6108918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Echo command doesn't do anything I've been started studying PHP in my spare time, and the first code example I was given was this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
From what I understand, this should write out "Hello World". However, all I see is a blank webpage. Any ideas why this is and how I should go about fixing it?
A: Here's a checklist
*
*What server are you running? Does it support php?
*Is PHP enabled?
*Is your file named with the extension .php?
*When you use View Source can you see the code in the php tags? If so PHP is not enabled
As a test try saving this as info.php
<?php
phpinfo();
?>
and see if it displays information about your server
A: Make sure the file that contains that code is a PHP file - ends in '.php'.
A: You might want to enable your error reporting in .htacess file in public_html folder and try to diagnose the issue depending upon the error message.
A: The code seems fine, certainly it should do what you intend.
Probably what happened is that you named the file with something like example.html, so you have to check the extension. It must look like example.php. With the extension .php at the end of the file you are telling the webserver that this file contains php code in it. That way the <?php echo "Hello World"; ?> is going to be interpreted and do you intend it to do.
A: If you don't see the html tags in the source, it means there is a PHP error. Check your view source, and if nothing is shown, check your error logs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3078070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: R Markdown - link text to figure in appendix I am using \ref{fig:figure1_appendix} in R Markdown to link the text to the actual figure but instead of linking to Figure A1 in appendix, it links to Figure 1 whose name is not "figure1_appendix" but "figure1". Any ideas?
This is the way I am creating figures in appendix:
# Appendix {-}
\normalsize
\setcounter{figure}{0}
\renewcommand{\thefigure}{A\arabic{figure}}
```{r figure1_appendix, message=FALSE, warning=FALSE, echo=FALSE, out.width='91%', fig.align='center', fig.cap="Text."}
knitr::include_graphics('./figure1_appendix_name.pdf')
```
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74680864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does Collections.unmodifiableCollection allow you to change the collection? Suppose I have to following set:
Set<String> fruits = new HashSet<String>()
fruits.add("Apple")
fruits.add("Grapes")
fruits.add("Orange")
Set<String> unmodifiableFruits = Collections.unmodifiableSet(new HashSet<String>(fruits))
unmodifiableFruits.add("Peach") // -- Throws UnsupportedOperationException
Set<String> fruitSet = Collections.unmodifiableCollection(fruits)
fruitSet.add("Peach")
println(fruitSet)
If I were to use Collections.unmodifiableSet() it throws an exception when I attempt to use the add() method, but that isn't the case for Collections.unmodifiableCollection(). Why?
According the the documentation it should throw an error:
Returns an unmodifiable view of the specified collection. This method
allows modules to provide users with "read-only" access to internal
collections. Query operations on the returned collection "read
through" to the specified collection, and attempts to modify the
returned collection, whether direct or via its iterator, result in an
UnsupportedOperationException.
All the code is written using Groovy 2.5.2
A: Short answer: adding Peach to this collection is possible, because Groovy does dynamic cast from Collection to Set type, so fruitSet variable is not of type Collections$UnmodifiableCollection but LinkedHashSet.
Take a look at this simple exemplary class:
class DynamicGroovyCastExample {
static void main(String[] args) {
Set<String> fruits = new HashSet<String>()
fruits.add("Apple")
fruits.add("Grapes")
fruits.add("Orange")
Set<String> fruitSet = Collections.unmodifiableCollection(fruits)
println(fruitSet)
fruitSet.add("Peach")
println(fruitSet)
}
}
In statically compiled language like Java, following line would throw compilation error:
Set<String> fruitSet = Collections.unmodifiableCollection(fruits)
This is because Collection cannot be cast to Set (it works in opposite direction, because Set extends Collection). Now, because Groovy is a dynamic language by design, it tries to cast to the type on the left hand side if the type returned on the right hand side is not accessible for the type on the left side. If you compile this code do a .class file and you decompile it, you will see something like this:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
public class DynamicGroovyCastExample implements GroovyObject {
public DynamicGroovyCastExample() {
CallSite[] var1 = $getCallSiteArray();
MetaClass var2 = this.$getStaticMetaClass();
this.metaClass = var2;
}
public static void main(String... args) {
CallSite[] var1 = $getCallSiteArray();
Set fruits = (Set)ScriptBytecodeAdapter.castToType(var1[0].callConstructor(HashSet.class), Set.class);
var1[1].call(fruits, "Apple");
var1[2].call(fruits, "Grapes");
var1[3].call(fruits, "Orange");
Set fruitSet = (Set)ScriptBytecodeAdapter.castToType(var1[4].call(Collections.class, fruits), Set.class);
var1[5].callStatic(DynamicGroovyCastExample.class, fruitSet);
var1[6].call(fruitSet, "Peach");
var1[7].callStatic(DynamicGroovyCastExample.class, fruitSet);
}
}
The interesting line is the following one:
Set fruitSet = (Set)ScriptBytecodeAdapter.castToType(var1[4].call(Collections.class, fruits), Set.class);
Groovy sees that you have specified a type of fruitSet as Set<String> and because right side expression returns a Collection, it tries to cast it to the desired type. Now, if we track what happens next we will find out that ScriptBytecodeAdapter.castToType() goes to:
private static Object continueCastOnCollection(Object object, Class type) {
int modifiers = type.getModifiers();
Collection answer;
if (object instanceof Collection && type.isAssignableFrom(LinkedHashSet.class) &&
(type == LinkedHashSet.class || Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers))) {
return new LinkedHashSet((Collection)object);
}
// .....
}
Source: src/main/org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation.java#L253
And this is why fruitSet is a LinkedHashSet and not Collections$UnmodifableCollection.
Of course it works just fine for Collections.unmodifiableSet(fruits), because in this case there is no cast needed - Collections$UnmodifiableSet implements Set so there is no dynamic casting involved.
How to prevent similar situations?
If you don't need any Groovy dynamic features, use static compilation to avoid problems with Groovy's dynamic nature. If we modify this example just by adding @CompileStatic annotation over the class, it would not compile and we would be early warned:
Secondly, always use valid types. If the method returns Collection, assign it to Collection. You can play around with dynamic casts in runtime, but you have to be aware of consequences it may have.
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52103639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Error: unreachable because it has no entry points Using Swift I got the error that my "TableViewController" is unreachable because it has no entry points and no runtime access via [UIStoryboard instantiateViewControllerWithIdentifier].
In my View Controller class there is the suggestion to fix it while changing instantiateViewController(withIdentfier...) in instantiateViewController(withIdentifier).
Shall I do this or how do I fix this?
A: Set Your TableViewController an Initial View Controller from the Storyboard
A: You need to mark a viewController in your Storyboard and set it to the initial viewController. You do this under the Attributes Inspector. This means that you set which viewController shall open when you start your application.
A: I fixed this by renaming the default "ViewController.swift" as "MainViewController.swift". Perhaps this is a warning to the user to insure everything is defined as you expect it to be.
I experienced this issue again and backtracked, eventually clearing the storyboard and then deleting it entirely from the project and the issue was still present. Relaunching Xcode fixed the issue.
A: For me I just had a view controller that wasn't attached to anything, i.e. I had a UITabBar Controller, and a few View Controllers attached to the TabBar, but there was one View Controller that was stranded, with out any connection to another view.
From my experience, the error message was,
“View Controller“ is unreachable because it has no entry points, and no identifier for runtime access via -[UIStoryboard instantiateViewControllerWithIdentifier:].
The View controller name was the text in quotes, i.e. “View Controller“.
Hope this helped someone!
A: Just add an ID in Storyboard ID (and restoration ID in case)
A: I solved my issue as follows:
*
*Make sure the storyboard is Initial View Controller
*In Custom Class, the selected class is ViewController
A: I'd reached the same error. This answer would be useful, I think:
Xcode: "Scene is unreachable due to lack of entry points" but can't find it
The problem was that because of some experiments and copy-pasting I had an actual copy of a view controller located outside the visible part of the screen or it could be stacked exactly on top of its twin. So I just deleted unwanted one :-) You should open Document Outline and сheck for copies :-)
A: In my case I accidentally deleted Storyboard Entry Point without knowing, and app wasn't starting,
After several undo's, I saw the problem and corrected it
A: When you have 2 or more navigation controllers(embedded UIVIewcontrollers) or 2 or more UIViewcontrollers in your storyboard. Xcode may be looking for a startup view controller. You can mark either of one of them as startupviewcontroller, just by selecting the "is initial viewcontroller"
OR you can give a unique storyboard id for each and every UInavigationcontrollers or UIViewcontrollers or UITabviewcontrollers in your storyboard.
A: This is my error.
warning: Unsupported Configuration: “View Controller“ is unreachable
because it has no entry points, and no identifier for runtime access
via -[UIStoryboard instantiateViewControllerWithIdentifier:].
I delete the code in ViewController , but I don't disconnect the connect in ViewController of Main.storyborad.
A: I had the same problem. I figured out that I had forgotten to add an "ID" to my Tab Bar Controller. Hope this help somebody.
A: I had same issue that to solve this problem I opened the Document Outline then realized that I have accidentally deleted the Segue between two pages.
Steps:
1) Editor> Show Document Outline
document outline
2) Check the Document Outline for any copy-paste, segue error or etc.
screenshot
A: The problem is exactly as the warning says: this View Controller is unreachable because it has no entry points.
If you have only one View Controller then this controller is missing its entry point. You can fix this by setting this View Controller as "Is Initial View Controller".
If you have several View Controllers and this View Controller is not in the beginning of your storyboard sequence, then you are missing a segue which should display this View Controller. You can fix this by adding a segue which should show this View Controller.
In general, Xcode tells you that this View Controller is not connected to the storyboard sequence because it has no incoming connections.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39847365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: My files aren't read by my java program I have some Java code like this :
Map<Map<String,String>,String> map = new HashMap<>();
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader("properties.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
i++;
String[] parts = sCurrentLine.split(",");
System.out.println(parts[2]);
Map<String,String> tempMap = new HashMap<>();
tempMap.put("issuing_bank",parts[1]);
tempMap.put("card_switch",parts[2]);
tempMap.put("card_Type",parts[3]);
map.put(tempMap,parts[0]);
}
} catch (IOException e) {
e.printStackTrace();
}
It looks strange that my map contains only first 12 elements that are stored from my text file. For debugging purpose I have used the variable i and print that out, which is printing the value of 22, which is the exact count in my text file.
My text file looks like this:
447747,ICCI,Visa,Credit
421323,ICCI,Visa,Debit
421630,ICCI,Visa,Debit
455451,ICCI,Visa,Debit
469375,ICCI,Visa,Debit
523951,ICCI,MasterCard,Credit
5399,ICCI,MasterCard,Debit
517652,HDFC,MasterCard,Credit
558818,HDFC,MasterCard,Credit
512622,SBI,MasterCard,Credit
526468,SBI,MasterCard,Credit
400975,Citi,Visa,Credit
402856,Citi,Visa,Credit
461726,Citi,Visa,Credit
552004,Citi,MasterCard,Debit
468805,Axis,Visa,Debit
418157,ICCI,Visa,Debit
524133,Citi,MasterCard,Credit
528945,HDFC,MasterCard,Credit
437748,SBI,MasterCard,Credit
524111,HDFC,MasterCard,Credit
431757,SBI,Visa,Credit
I'm very much confused, why only 12 elements are read into my map. Am I missing something here?
Thanks in advance.
A: The solution is simple: you have the wrong argument order in this line:
map.put(tempMap,parts[0]);
it should say
map.put(parts[0],tempMap);
You must change the type parameters of your variable declaration accordingly. Where you have
Map<Map<String,String>,String> map = new HashMap<>();
you must put
Map<String,Map<String,String>> map = new HashMap<>();
Altogether, after these changes I believe you will have the structure you really want to have: a map from parts[0] to the map of the rest of the record fields.
I should add that your solution (in addition to your nick :) gives you away as a developer who primarily codes in a dynamic language like Groovy; this style is not a good match for Java's language features. In Java you'd be better off defining a specialized bean class:
public class CardHolder {
public final String cardNumber, issuingBank, cardSwitch, cardType;
public CardHolder(String[] record) {
int i = 0;
cardNumber = record[i++];
issuingBank = record[i++];
cardSwitch = record[i++];
cardType = record[i++];
}
}
First, this approach is nicer since your reading loop becomes simpler and more to the point:
while ((sCurrentLine = br.readLine()) != null) {
final CardHolder ch = new CardHolder(sCurrentLine.split(","));
map.put(ch.cardNumber, ch);
}
Also this will allow you finer control over other aspects of your record; for example a nice custom toString and similar. Note also that this has hardly resulted in more code: it just got reorganized by the separation-of-concerns principle.
(A minor observation at the end: in Java the s-prefix to String variables is not customary because it is redundant in statically-typed languages; rest assured that you will never encounter a bug in Java due to an Integer occuring where a String was expected.)
A: You should change, how you have created your Map.. In place of your below declaration: -
Map<Map<String,String>,String> map = new HashMap<>();
Rather than this, you should have a : -
Map<String, Map<String,String>> map = new HashMap<>();
You should always have an immutable type as a key in your Map..
And after this change, you should change: -
map.put(tempMap,parts[0]);
to: -
map.put(parts[0], tempMap);
A: I think you have the arguments in
map.put(tempMap,parts[0]);
reversed. You are mapping tempMap to the number, where you probably want to be mapping the number to tempMap:
map.put(parts[0], tempMap);
Using
Map<String, Map<String,String>> map = new HashMap<>();
A: You should use Map as value since HashMap equality is based on key value pairs it has..
map.put(parts[0],tempMap);
A simple program below will illustrate this fact
Map<String, String> tempMap1 = new HashMap<String, String>();
tempMap1.put("issuing_bank", "ICICI");
tempMap1.put("card_switch", "Visa");
tempMap1.put("card_Type", "Debit");
Map<String, String> tempMap2 = new HashMap<String, String>();
tempMap2.put("issuing_bank", "ICICI");
tempMap2.put("card_switch", "Visa");
tempMap2.put("card_Type", "Debit");
System.out.println(tempMap1.equals(tempMap2));//Prints true
Output:
true
So your declaration should like below. Remember you should always use immutable object as key in HashMap.
Map<String,Map<String,String>> map = new HashMap<String,Map<String,String>>();
A: That's because you're using a map (the tempMap) as a key.
This is wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12819570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.