text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: how to take more than one photo in QML? I have to take 4 continues pictures using the webcamera in QML i can take only one picture after that
I get an error from the QML debugger which states "Camera not ready for capture" how do i get the camera to be in ready state after the first capture this is the code i have tried
even if i set the ready state to true: it does not seem to be working? is there an easy way to get my way around this?
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle{
width: parent.width
height: parent.height
ColumnLayout{
width: parent.width;height: parent.height
spacing: 15;
Camera{
id:cam
captureMode: Camera.CaptureStillImage
imageCapture {
onImageCaptured: {
ready:true
console.log(ready)
}
}
}
VideoOutput{
id:vid1
source: cam
height:parent.height
width: 800
Layout.fillWidth: true
Layout.fillHeight: true
}
Rectangle{
id:rect1
width: 100
height: 30
Layout.fillWidth: true
Layout.alignment:bottom
color: "#365688"
Text {
id: text1
anchors.centerIn: parent
text:"capture"
font.pointSize: 10
}
MouseArea{
anchors.fill:parent
onClicked: {
console.log("clicked");
for(var i=0;i<=3;i++){
cam.start()
cam.imageCapture.captureToLocation("C:/Users/vinay/Documents")
console.log(cam.cameraStatus)
}
}
}
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58705505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: History.js bookmark support for HTML5 (pushState) and HTML4 (#) I've have the back and foward buttons working via History.js in both HTML5 and HTML4 browsers.
I'm now attempting to add bookmark support by parsing the url, and loading the content in the querystring. The code I normally use to do this is:
var urlParams = {};
(function () {
var match,
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
This works great for the HTML5, but obviously does not work for the HTML4. Whats a good way to parse the hash in HTML4, and the substring in HTML5?
A: found a solution on this page: https://getsatisfaction.com/balupton/topics/history_js_and_retrieving_state_from_a_url
"You can use this function however from one of my utility projects called jQuery Sparkle to do what you need: https://github.com/balupton/jquery-sparkle/blob/master/scripts/resources/core.string.js#L164
So you would do this:
var State = History.getState(), dataQuery = State.url. queryStringToJSON();"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13477739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I search, display, and retrieve file using C manually by inputing the value first? #include <stdio.h>
#include <stdbool.h>
#define HASH_SIZE 10
int hash(int value);
void dfs(FILE *file, int value);
int main()
{
FILE *file = fopen("DATA_FILE.csv", "r");
if (file == NULL)
{
perror("Error while opening the file");
return 1;
}
int value = -685434;
dfs(file, value);
fclose(file);
return 0;
}
void dfs(FILE *file, int value)
{
bool visited[HASH_SIZE] = { false };
// Read the first value from the file
int currentValue;
fscanf(file, "%d", ¤tValue);
while (currentValue != value && !feof(file))
{
int key = hash(currentValue);
visited[key] = true;
fscanf(file, "%d", ¤tValue);
if (visited[hash(currentValue)])
{
fscanf(file, "%d", ¤tValue);
}
}
if (currentValue == value)
{
printf("Value found in file: %d\n", currentValue);
}
}
int hash(int value)
{
return value % HASH_SIZE;
}
While the instruction says,
"The data file has two pairs of columns, the first of which has the number you're seeking for and the second of which contains the paired numbers you need to retrieve and show.
In this instance, you need to use data scanning for the file by reading row by row to find the data
Here is what is expected to work from the code:
Your code receives input from command line arguments.
The format in command line as follow
find [-s | -t] number
description:
number : is the number that you must find inside the data file
[ … | …. ] : is the searching techniqye option that you need to choose one of the
parameters.
-s : you will search inside data file using file scanning row by row.
-t : you will search using your solution
Here is the input and output:
*
*find -s 12345
Found 12345 with data on second column is 987234
Time elapsed 200 ms
or
*find -t 12345
Found 12345 with data on second column is 987234
Time elapsed 1 ms
if an error occurs, it will say:
No method defined
Proper Syntax is
find [ -s | -t ] number
A: From my top comments ...
*
*From the problem description, the input [.csv] file is a series of lines of the form: key,value.
*Your code should be doing (e.g.): fscanf(file,"%d,%d",&curkey,¤tValue), so you are reading the file incorrectly.
*What you call value, I would call desired_key as it needs to match the key [and not the value] and if a match is found on the key, you want to print the value.
*You have to do this line-by-line if given -s as a command line arg.
*If given -t, you have to reading the file and store the key/value pairs in an array. You need a struct such as: struct row { int key; int value; };
*The problem statement doesn't mention a hash.
*I don't see a need for visited at all. To me, that's some extraneous code from a shortest path algorithm (e.g. Dijkstra's or A*).
*Your code doesn't look at argc/argv at all. So, you can't select the method from -s or -t and get the desired key value to search for.
Here is the corrected code. It is annotated:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int opt_s;
int opt_t;
// key/value item
struct keyval {
int key;
int val;
};
struct keyval *csvdata; // array of all pairs in file
int csvcount; // number of pairs in array
// method_s -- match on a line-by-line basis
int
method_s(FILE *file,int desired_key,int *retval)
{
int curkey;
int curval;
int found = 0;
// read all lines of the form:
// key,val
while (fscanf(file,"%d,%d",&curkey,&curval) == 2) {
found = (curkey == desired_key);
if (found)
break;
}
// return the value if a match
if (found)
*retval = curval;
return found;
}
// load_t -- load up CSV array
int
load_t(FILE *file)
{
int cap = 0;
int curkey;
int curval;
struct keyval *pair;
csvdata = NULL;
csvcount = 0;
while (fscanf(file,"%d,%d",&curkey,&curval) == 2) {
if (csvcount >= cap) {
cap += 10;
csvdata = realloc(csvdata,sizeof(*csvdata) * cap);
if (csvdata == NULL) {
perror("realloc");
exit(1);
}
}
pair = &csvdata[csvcount++];
pair->key = curkey;
pair->val = curval;
}
// trim array to actual size used
csvdata = realloc(csvdata,sizeof(*csvdata) * csvcount);
if (csvdata == NULL) {
perror("realloc");
exit(1);
}
}
// method_t -- match on a stored array basis
int
method_t(FILE *file,int desired_key,int *retval)
{
struct keyval *pair;
int found = 0;
// load up the array
load_t(file);
// loop through the stored array, looking for a match
for (int idx = 0; idx < csvcount; ++idx) {
pair = &csvdata[idx];
found = (pair->key == desired_key);
if (found)
break;
}
// return the value if a match
if (found)
*retval = pair->val;
return found;
}
int
timems(void)
{
struct timespec ts;
long long nsec;
static long long timebase = 0;
clock_gettime(CLOCK_MONOTONIC,&ts);
nsec = ts.tv_sec;
nsec *= 1000000000;
nsec += ts.tv_nsec;
if (timebase == 0)
timebase = nsec;
nsec -= timebase;
nsec /= 1000000;
return nsec;
}
int
main(int argc,char **argv)
{
int err = 0;
--argc;
++argv;
for (; argc > 0; --argc, ++argv) {
char *cp = *argv;
if (cp[0] != '-')
break;
if ((cp[1] == '-') && (cp[2] == 0))
break;
cp += 2;
switch (cp[-1]) {
case 's':
opt_s = 1;
break;
case 't':
opt_t = 1;
break;
default:
err = 1;
break;
}
}
if (opt_s && opt_t)
err = 1;
if (! (opt_s || opt_t))
err = 1;
int desired_key = -1;
if (argc != 1)
err = 1;
else
desired_key = atoi(*argv);
if (err) {
printf("No method defined Proper Syntax is find [ -s | -t ] number\n");
exit(1);
}
FILE *file = fopen("DATA_FILE.csv", "r");
if (file == NULL) {
perror("Error while opening the file");
return 1;
}
int found = 0;
int retval = 0;
int msbeg = timems();
do {
if (opt_s) {
found = method_s(file,desired_key,&retval);
break;
}
if (opt_t) {
found = method_t(file,desired_key,&retval);
break;
}
} while (0);
int msend = timems();
fclose(file);
if (found)
printf("Found %d with data on second column is %d Time elapsed %d ms\n",
desired_key,retval,msend - msbeg);
return 0;
}
Here is the sample input (DATA_FILE.csv) file I used:
46079,96649
71463,62685
81995,47037
50876,79762
95492,88344
45272,72553
41950,80235
81543,99066
67329,78252
79563,36472
63549,83972
94173,58525
81532,25036
39514,94603
90454,25278
33306,95455
85052,5202
49451,58592
69333,80996
94039,34855
Here is the output for ./find -s 67329:
Found 67329 with data on second column is 78252 Time elapsed 0 ms
Here is the output for ./find -t 67329:
Found 67329 with data on second column is 78252 Time elapsed 0 ms
A: /* find_value.c */
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("DATA_FILE.csv", "r");
if (!file)
{
perror("DATA_FILE.csv");
return 1;
}
int n;
int find_value = 32;
while(fscanf(file, "%d", &n) == 1) {
if(n == find_value) {
printf("%d\n", n);
}
}
fclose(file);
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74753331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Add Google login to OpenIddict Authorization Server - who provides the client_id and how? Starting with the Zirku Sample of OpenIddict, I wanted to add Google Accounts as login provider (nuget: Microsoft.AspNetCore.Authentication.Google).
My changes include adding the google auth provider after AddOpenIddict(...):
services.AddAuthentication()
.AddGoogle("Google", options =>
{
options.CallbackPath = "/signin-google";
options.ClientId = "0000000000000-redacted.apps.googleusercontent.com";
options.ClientSecret = "redacted";
options.SignInScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
});
Adding /signin-google as valid authorization endpoint to allow calling SignIn:
options.SetAuthorizationEndpointUris("/connect/authorize", "/signin-google")
.SetLogoutEndpointUris("/connect/logout")
.SetIntrospectionEndpointUris("/connect/introspect")
.SetUserinfoEndpointUris("/connect/userinfo");
However, when coming back from google, the OpenIddict Server always complans, that the client_id is missing:
fail: OpenIddict.Server.OpenIddictServerDispatcher[0] The authorization request was rejected because the mandatory 'client_id' parameter was missing.
Tried these config options already without any change:
options.AcceptAnonymousClients();
options.Configure(op => op.AcceptAnonymousClients = true);
What am I doing wrong?
complete log can be found here.
(and yes, I changed the port to 6001 to reuse an existing redirect-url registered at google)
A: options.AcceptAnonymousClients() has no effect on the code flow as client_id is a mandatory parameter in this case (it only affects the token, introspection and revocation endpoints).
options.SignInScheme cannot be set to a scheme belonging to OpenIddict. In most cases, it must correspond to a cookie handler (typically the one registered by Identity).
You will also want to remove /signin-google from the endpoints managed by OpenIddict, as it will prevent the Google authentication handler from working properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67169047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Core animation (size change) with autolayout challenge I have a piece of core animation by use of 2 methods in order to give appearance that the object is growing in size from the centre-outwards from the existing location...
(1) viewDidLayoutSubviews()
self.imageView.frame = CGRectMake(187, 249, 0, 0)
which is in the centre of the screen for this imageView object
(2) viewDidAppear()
- with animation block of duration 1 second. e.g.
UIView.animateWithDuration(1.0, delay: 1.5, options: [], animations: {
self.imageView.frame = CGRectMake(16, 70, 343, 358)
}, completion: nil)
which puts object where I want it to show in full size, for the specific screen size.
When I use the x and y coordinates for CGRectMake(...) on the iPhone size I'm looking for they work fine, But when I try on simulator with different screen sizes, it doesn't work in conjunction with the Autolayout constraints, but overrides the existing Constraints.
Question(s)...
Is there a way of making this animation work by centering it proportional to the screen size somehow, rather than explicit coordinates and sizes? via CGRectMake...? (...which seems to show a clash between use of Autolayout and Animation)
Ideally I'm looking for an elegant simple solution? or am I at the limits of the tech?
Many thanks in advance!
A: You can set imageView location using autolayout constraints & give it a size constraint and by taking an outlet from it you can animate height to increase leaving all other constraints working
@IBOutlet var myViewHeight: NSLayoutConstraint!
UIView.animateWithDuration(0.3, delay: 0.0, options: [], animations:
{
() -> Void in
self.myViewHeight.constant = 300
self.view.layoutIfNeeded()
}, completion:nil)
You should take the outlet from the constraint itself like control+drag on Label.top = topMargin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37499946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Integrating Lucene Index and Amazon AWS I have a an existing index of lucene index files and the java code to perform search functions on it.
What I would like to do is perform the same thing on a server so users of an app could simply pass a query that will be taken as an input parameter by the java program and run it against the existing index to return the document in which it occurs.
All the implementation has been tested on my local pc,but what I need to do is implement it in an Android app.
So far I have read around and concluded that porting the code in AWS lambda and using S3 to store the files and calling the s3 objects from lambda.
Is this the right approach?Any resources that point to the this approach or alternative suggestions are also appreciated.
Thanks in advance.
A: Every time your Android app sends a request to AWS Lambda (via AWS API Gateway I assume) the Lambda function will have to download the entire index file from S3 to the Lambda /tmp directory (where Lambda has a 512MB limit) and then perform a search against that index file. This seems extremely inefficient, and depending on how large your index file is, it might perform terribly or it might not even fit into the space you have available on Lambda.
I would suggest looking into the AWS Elasticsearch Service. This is a fully managed search engine service, based on Lucene, that you should be able to query directly from your Android application.
A: As you already have your index files in S3, you can direct your Lucene Index reader to point to a Location on S3.
String index = "/<BUCKET_NAME>/<INDEX_LOCATION>/";
String endpoint = "s3://s3.amazonaws.com/";
Path path = new com.upplication.s3fs.S3FileSystemProvider().newFileSystem(URI.create(endpoint), env).getPath(index);
IndexReader reader = DirectoryReader.open(FSDirectory.open(path))
You can either pass in client credentials in env or you can assign role to your Lambda function.
Ref:
https://github.com/prathameshjagtap/aws-lambda-s3-index-search/blob/master/lucene-s3-searcher/src/com/printlele/SearchFiles.java
A: For Lucene indices less than 512MB you can experiment with lucene-s3directory.
As Mark said, on AWS Lambda you are limited to 512MB on /tmp. I think having a completely serverless search service is very desirable but until that limit is gone, we're stuck with EC2 for production deployments. Once you go with running Lucene on EC2, storing the index on S3 becomes pointless as you have access to EBS or ephemeral storage.
In case you want to try out S3Directory, here's how to get started:
S3Directory dir = new S3Directory("my-lucene-index");
dir.create();
// use it in your code in place of FSDirectory, for example
dir.close();
dir.delete();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38817050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sequelize validation throwing error I'm trying to check that a username is unique, and I gather that I'd need a custom validation for that. I've written the following code, but instead of returning the error in the array returned by .validate(), it just throws the error, which isn't the behaviour described in the docs and isn't what I want.
var User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
validate: {
isUnique: function (username) {
User.find({ where: { username: username }})
.done(function (err, user) {
if (err) {
throw err;
}
if (user) {
throw new Error('Username already in use');
}
});
}
}
},
A: The validation you are doing is asynchronous. You call the User.find method, and after that the validation method returns. Sequelize has no way of knowing that you are doing something async in your validation, unless you tell it so. Once your find call is done you throw the error, but the validation has completed, so there is no code to catch that error, which means the error is thrown and crashes the app
The way to tell sequelize that you are doing something async is to take a second argument to your function, which is a callback. If you call the callback without any arguments, the validation succeeded, if you give it an argument, the validation failed.
var User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
validate: {
isUnique: function (username, done) {
User.find({ where: { username: username }})
.done(function (err, user) {
if (err) {
done(err);
}
if (user) {
done(new Error('Username already in use'));
}
done();
});
}
}
},
Could you point me to the part of the documentation that mislead you, then we can hopefully correct it :)
A: Sequelize supports Promise style async operations. Specifically the Bluebird.js lib. Just change your function to specifically use the Promise -> next() pattern.
var User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
validate: {
isUnique: function (username) {
User.find({ where: { username: username }})
.then(function (user) {
if (user) {
throw new Error('Username already in use');
}
});
}
}
},
This will also handle any errors on User.find() for you.
See this example in their codebase
Of course the easiest way to handle unique constraints is by setting unique: true on the field definition itself:
var User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
unique: true
},
But this requires that you are either creating the table using Sequelize or already have a table with the unique constraint set.
A: This question got a valid answer which explains how the validation option works. But in this situation you don't have to check if a user exists on your own.
Sequelizejs has a findOrCreate() method, that checks if somethings exists before doing anything.
Very useful method :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22932447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: matplotlib says libpng16.so.16: cannot open shared object file: No such file or directory I am trying to install matplotlib version 2.0.0. I don't have root access, hence can't use sudo/apt-get When I tried installing matplotlib, it showed dependencies on freetype and libpng. So, I executed the following steps:
wget http://prdownloads.sourceforge.net/libpng/libpng-1.6.34.tar.gz
tar -xzf libpng-1.6.34.tar.gz
cd libpng-1.6.34/
./configure --prefix=/home/$username$/
make
make check
make install
cd ..
wget http://download.savannah.gnu.org/releases/freetype/freetype-2.5.3.tar.gz
tar xzf freetype-2.5.3.tar.gz
cd freetype-2.5.3
./configure --prefix=/home/$username$ --without-png
make && make install
export PKG_CONFIG_PATH=/home/$username$/lib/pkgconfig
pip install matplotlib==2.0.0
Which worked perfectly fine. But when I do import matplotlib.pyplot as plt it throws the following error:
ImportError: libpng16.so.16: cannot open shared object file: No such file or directory
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50632550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to ensure that UINavigationController has finished animating before poping up another one? I make a program that push uinavigationcontroller. Once done it pop things back and then do something.
One of the thing it wanna do is wait until it finishes poping up before doing that something.
That's because one of the thing that it may do is to push another viewcontroller.
How should I do so?
I already create a category
-(void)SafelyPushController:(UIViewController *) pushee
{
AssertMainThread;
if([self.viewControllers lastObject]!=pushee){
[self pushViewController:pushee animated:YES];
while (false);
}
else{
//DLog(@"Dont need to pushview");
}
while (false);
//[self pushViewController:pushee animated:YES];
}
To prevent some of the cases.
I need more general solution.
Something like:
If navigationController is still animating, wait till it finish in background and do this block at current thread.
That kind of thing.
A: You need to use UINavigationController's delegate:
@property(nonatomic, assign) id<UINavigationControllerDelegate> delegate;
Set it to an object of a class that conforms to this protocol, which implements this method:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
In this method you'll know when you have finished showing a view controller, thus if it was animated the animation has ended. Notice that if you push multiple view controllers you have to keep track of them.
Documentation:
UINavigationController
UINavigationControllerDelegate
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15969171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: http_negotiate_language issue Perhaps I missed something but when I call
$result='';
$langs = array(
'en-US',
'fr',
);
var_dump(http_negotiate_language($langs,$result));
I have an 500 error message. Should I add some extensions, should I parametrize something on my php.ini ?
A: It is require PECL pecl_http >= 0.1.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13762333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: xcode How to show $ value in a Label and a Text Box. Example 125000 as 125,000.00 I need to show $value on a Label.
currently it appears as 125000 but i need it to be 125,000.00
thanks in advance to all supporters.
A: Drag the Number Formatter (found in the object library) object onto the field/label. Change the behavior (be sure your in the attributes inspector for the number formatter) to 'OS X 10.4+ Custom' (that's what it was in Xcode 4.5.2).
In the 'Integer Digits' field, change the minimum to 1 and leave the maximum whatever you need. For the 'Fraction Digits' fields set the minimum and maximum to 2.
Near the top of the field, stick a dollar sign in front of the 'Format (+)' and '(-)' fields.
Check the group separator box then change the primary and secondary grouping fields to 3.
A: The solution of your problem is NSNumberFormatter
Some code to get you started:
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSLog(@"%@", [currencyFormatter stringFromNumber:[NSNumber numberWithInt:10395209]]);
[currencyFormatter release];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14168232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sending mail with embedded image in Ruby I want to send a mail with an attached image and embed this image in html. As a source for tag , What should I write and is there any missing header parts such a content_type ?
When I am doing real test, I send to a mail to my gmail account. I can see there is an attachment with name "unnamed" and I could not display image even when I download.
Gem: Pony
require 'pony'
Pony.override_options = { :via => :test }
Pony.mail(
:to => 'foo@bar',
:from => 'abc@abc.com',
:subject => 'test123',
:body => "<h1><strong>Dear X, check the newsletter ,<br></strong></h1> <img src='attached image' />",
:attachments => {"happy_image.jpg" => File.read("happy_image.jpg")}
)
puts Mail::TestMailer.deliveries
output:
Date: Tue, 06 Dec 2016 17:23:05 +0300
From: abc@abc.com
To: foo@bar
Message-ID: <5846c9ca183d6_5983c9fd899060@MW7BIQ12TKYHQC.mail>
Subject: test123
Mime-Version: 1.0
Content-Type: multipart/mixed;
boundary="--==_mimepart_5846c9caf15a_5983c9fd8989e5";
charset=UTF-8
Content-Transfer-Encoding: 7bit
----==_mimepart_5846c9caf15a_5983c9fd8989e5
Content-Type: text/plain;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<h1><strong>Dear X, check the newsletter ,<br></strong></h1> <img src='' />
----==_mimepart_5846c9caf15a_5983c9fd8989e5
Content-Type: image/jpeg;
filename=happy_image.jpg
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename=happy_image.jpg
Content-ID: <happy_image.jpg@MW7BIQ12TKYHQC>
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQE
BQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/
2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU
FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAHiAuMDASIAAhEBAxEB/8QA
HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF
BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK
FhcYGQ==
----==_mimepart_5846c9caf15a_5983c9fd8989e5--
A: You should be able to BASE64 encode the image, and use the resulting string as the src of the img tag.
For example:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWQAAAD8CAYAAAB..."/>
Also make sure that your content type is set as text/html instead of text/plain. Looking at the mail, it seems that it's set to the latter, hence why images don't render and tags render as text. Add the following to your arguments to use text/html content type:
:headers => { 'Content-Type' => 'text/html' }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40998085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: delete a DataTable row bound to a datagridview I have a DataTable bound to a dataGridView using the following code :
dataGridView1.DataSource = ReducedColTable;
At some point i would like to move the selected rows into another Table.
So here is the loop :
List<DataGridViewRow> rows = (from DataGridViewRow row in dataGridView1.SelectedRows
where !row.IsNewRow
orderby row.Index
select row).ToList<DataGridViewRow>();
foreach (DataGridViewRow item in rows)
{
DataRow newRow = dtarget.Rows.Add();
newRow.SetField("artiste", item.Cells[0].Value);
newRow.SetField("album", item.Cells[1].Value);
newRow.SetField("song", item.Cells[2].Value);
newRow.SetField("year", item.Cells[3].Value);
newRow.SetField("file_path", item.Cells[4].Value);
newRow.SetField("file_size", item.Cells[5].Value);
dataGridView1.Rows.RemoveAt(item.Index);
}
Ps : I didnt find a way to copy the row into the new table (dtarget) which is declared globally hence the approach col by col.
DataTable dtarget = new DataTable();
My issue is that the last line is removing the row from the DataGridView but not from the original table (ReducedColTable)
Any hint how to achieve this ?
A: I found that the DataTable’s ImportRow works well for this. If you set the grids SelectionMode to FullRowSelect then you should be able to loop through the grids SelectedRows collection and “import” the selected row(s) into the other DataTable. Below is a simple example.
dt and dt2 are two DataTables with similar schemas. dt is a data source for datagridview1 and dt2 is a data source to datagridview2. Initially, dt is filled with some data and dt2 is empty. Once the user selects one or more rows, a button's click event initiates moving the selected rows from dt to dt2.
To start, a simple loop through the selected rows. A check if the “new row” is selected which we do not want to copy, therefore we ignore it. Next, get the “data bound” row from the data table in the form of a DataRowView object. Then we “import” that row into dt2, and finally removing the copied row from dt. I did not do a lot of testing on this however it appears to work as expected.
private void button1_Click(object sender, EventArgs e) {
DataRowView drv;
foreach (DataGridViewRow row in dataGridView1.SelectedRows) {
if (!row.IsNewRow) {
drv = (DataRowView)row.DataBoundItem;
dt2.ImportRow(drv.Row);
dt.Rows.Remove(drv.Row);
}
}
}
To make the example complete, drop two grids and button onto a form.
DataTable dt;
DataTable dt2;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
dt = GetTable();
dt2 = GetTable();
FillTable(dt);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt2;
}
private DataTable GetTable() {
DataTable dt = new DataTable();
dt.Columns.Add("Col1", typeof(string));
dt.Columns.Add("Col2", typeof(string));
dt.Columns.Add("Col3", typeof(string));
return dt;
}
private void FillTable(DataTable dt) {
for (int i = 0; i < 10; i++) {
dt.Rows.Add("C0R" + i, "C1R" + i, "C2R" + i);
}
}
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62823269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Chrome on Windows triggers d3.zoom behavior on click I'm creating an interactive map using dc.js and d3.js. The map should support zooming and panning, so I'm using the d3.zoom behavior. I also want a function to run when I click areas on the map. The code works as expected in Firefox (Linux and Windows), IE, and Chrome (Linux), but Chrome version 47 on Windows interprets the clicks as attempts to zoom, which suppresses the click events. Is there any way to avoid this?
I created a simplified jsfiddle to demonstrate the issue. The code is below:
HTML
<div id="container"></div>
JS
var container = d3.select('#container');
var fmt = d3.format('.2f');
var svg = container.append('svg')
.attr('width', 400)
.attr('height', 400)
.append('g');
var colors = ['#444488', '#448844', '#884444'];
svg.selectAll('circle')
.data(colors)
.enter()
.append('circle')
.attr('cx', function(d, i) { return 50 + 100*i; })
.attr('cy', function(d, i) { return 50 + 100*i; })
.attr('r', function(d, i) { return 10 + 10*i; })
.style('fill', function(d) { return d; })
.on('click', function(d, i) {
// Skip the click handler if preventDefault was called. This prevents the click
// handler from running at the end of a drag.
if (!d3.event.defaultPrevented) {
console.log('clicked circle #' + i);
}
});
var zoomBehavior = d3.behavior.zoom()
.scale(1)
.scaleExtent([1, 15])
.translate([0, 0])
.on('zoom', function() {
console.log('got zoom: scale = ' + fmt(d3.event.scale) + ', translate = [' + fmt(d3.event.translate[0]) + ',' + fmt(d3.event.translate[1]) + ']');
svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
});
container.call(zoomBehavior);
The demo adds three circles to the SVG and gives each one a click handler. It also adds the d3.zoom behavior to the container element. I want it to do the following:
*
*Clicking a circle runs the cirlce's click handler.
*Using the mousewheel zooms in and out, whether the mouse is over a circle or the background.
*Clicking and dragging pans the area, whether the click/drag starts over a circle or over the background. If it starts over a circle, the circle's click handler shouldn't be run.
All these requirements are met by the demo in Firefox and IE. In Chrome, when I click a circle, the zoom handler runs instead of the click handler. Does anyone have suggestions for how to deal with this?
As another approach, I tried putting a rectangle either above or below the rest of the SVG elements and attaching the zoom behavior to the rectangle instead of the container, but I ran into various issues with events not reaching the correct element. I'm willing to explore that further if people think that's the way to go.
A: I experienced the same problem with an old version of d3 (3.3.3). I'm not sure if it's been fixed since. The problem, as you said, is that Chrome gets in a weird state where a mouse click triggers a mousemove event. Completely closing Chrome and reopening it seems to get it out of this state.
I was able to resolve the issue by checking in d3's mousemove function for actual movement. I added two lines to the moved() function within mousedowned() in d3:
function moved() {
if(d3.event.movementX === 0 && d3.event.movementY === 0) // new
return false; // new
dragged = 1;
translateTo(d3.mouse(target), l);
zoomed(event_);
}
That seems to resolve the problem without having to restart Chrome.
A: My Chrome instance must have gotten into some strange state while I was developing and debugging. I restarted Chrome and tried again, and now it's working fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34560616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is get_current_user_id() returning 0 when used in woocommerce_login_redirect hook I was searching now for a while to find a solution for my problem, where the function get_current_user_id() returns 0 when hooked to woocommerce_login_redirect.
Right after the login-redirect there should always be an user-id, or am I getting s.th wrong here?
In my function.php file I have follwoing code:
add_action( 'woocommerce_login_redirect', 'ffaces_register_customer' );
add_filter( 'woocommerce_registration_redirect', 'ffaces_register_customer' );
function ffaces_register_customer( $user ) {
$customerid = get_current_user_id();
if ( $customerid == 0 ) {
$redirection_url = get_permalink( wc_get_page_id( 'myaccount' ) );
return $redirection_url;
exit();
}
// more code working with $customerid
return home_url("my-account/my-projects");
exit();
}
A: There are some mistakes in your code (the first function argument is not the user, but the url redirection to be filtered). Try the following instead:
add_filter('woocommerce_login_redirect', 'ffaces_register_customer', 10, 2 );
add_filter( 'woocommerce_registration_redirect', 'ffaces_register_customer', 10, 2 );
function ffaces_register_customer( $redirect, $user = '' ) {
if( isset($user) && is_a( $user, 'WP_User' ) && $user->ID > 0 ) {
return home_url("my-account/my-projects");
} else {
return get_permalink( wc_get_page_id( 'myaccount' ) );
}
}
Code goes in functions.php file of your active child theme (or active theme). It should work.
A: I don't think its set yet when this fires.
The hook passes the user object of the user that logged in try to change
$customerid = get_current_user_id();
to
$customerid = $user->ID;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62154776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google Calendar API Sharing Example I am looking for examples of share calendar and share event using google calendar API in any programming language java, .net, java script.
Thanks,
Aqeel
A: I'm not sure how much this will help, but I have an example here using scala with the ical4j library to read a shared/public google calendar:
http://github.com/kevinwright/lsug-website/tree/master/src/main/scala/org/lsug/ical4scala/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2014453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can I DeserializeWithLengthPrefix a c# class into a Python class? I have a lot of data Serialized with ProtoBuf in c#.
A colleague would like read these files with Python.
Can this be achieved as Python classes not same as c#.
Here is the c# class:
[ProtoContract]
public class TickRecord
{
[ProtoMember(1, DataFormat = DataFormat.FixedSize, IsRequired = true)]
public DateTime DT;
[ProtoMember(2, DataFormat = DataFormat.FixedSize, IsRequired = true)]
public double BidPrice;
[ProtoMember(3, DataFormat = DataFormat.FixedSize, IsRequired = true)]
public double AskPrice;
[ProtoMember(4, DataFormat = DataFormat.FixedSize, IsRequired = true)]
public int BidSize;
[ProtoMember(5, DataFormat = DataFormat.FixedSize, IsRequired = true)]
public int AskSize;
}
A: That looks like protobuf-net; fortunately, the library includes a tool to spit out the .proto schema for what it thinks of your model:
var schema = Serializer.GetProto<TickRecord>();
which comes out as:
message TickRecord {
required bcl.DateTime DT = 1;
required double BidPrice = 2 [default = 0];
required double AskPrice = 3 [default = 0];
required sfixed32 BidSize = 4 [default = 0];
required sfixed32 AskSize = 5 [default = 0];
}
where bcl.DateTime is a protobuf-net complex data type described in "bcl.proto".
Frankly, I suggest changing your date-time to a long using unix time - it'll make things a lot simpler here. That gives you:
message TickRecord {
required sfixed64 DT = 1 [default = 0];
required double BidPrice = 2 [default = 0];
required double AskPrice = 3 [default = 0];
required sfixed32 BidSize = 4 [default = 0];
required sfixed32 AskSize = 5 [default = 0];
}
which you can give to your colleague, and they can run protoc or whatever other platform/library tool they need for protocol buffers in their environment, and they should be set. The serialization format is intentionally cross-platform, so the data should work fine.
Note: *WithLengthPrefix works by wrapping the data in an outer shell. I need to see the exact parameters you are using to advise on how to advise your colleague.
Note: changing the DateTime to long is a breaking change; if you can't do that your colleague will have to look at bcl.proto (just Google it) and translate it into python.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38147223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use JavaScript create a damping function? I'm writing a scrollbar plugin. When dragging, I want to simulate the function of Safari(IOS), that is, overflow is allowed after dragging to the edge. In fact, Safari (IOS) has an edge decreasing effect when dragging, that is, it will become more and more immobile. This effect seems to be realized by damping function ? I tried to search, but I didn't find a particularly suitable function. I found some relevant contents in this article : How UIScrollView works, but I don't understand OC and Swift, and I'm not very good at math. Can anyone help me. ಥ_ಥ
Here is the damping function provided by another article : drag damping, but in fact, it uses a piecewise function to achieve the damping effect. Although it will be faster, it is found after the test that it does not meet my needs. I hope to set the maximum target value clearly, but in this function, it cannot explicitly control the maximum value.
This is a screenshot of the project. At present, the dragged part has not been completed, but the wheel control part has been realized, and the overflow can also be realized. However, because there is no appropriate damping function, the increment after overflow seems very rigid.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72031440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How I can print 'process status' in Django? In one of my views I have several steps and they use 5 or 7 minutes to finish totally, so I was wondering if there is a way to print the status of the view in the browser, like:
"Calculating models..."
"Post processing models..."
"Making DB..."
"Cleaning old tables..."
Is there a way to do that?
Thanks!
A: Such heavy duty should probably not be part of a django view. You might want to look into django celery for asynchronous task management.
However you can do something like that just fine by polling your server. The easy setup, use short polling (basically a javascript loop that triggers an ajax request to the server every i seconds, retrieving a status response* which you can use to show your user anything).
*You'll have to setup an url and function that calculates the status somehow or if you're using celery you can use it's asynchronous result
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12472789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I either post or pass data from website to object element inside it? I'm trying to pass data somehow from website to an object element which is contained inside it.
A brief example:
This is a test1.html example which is in https://domain.tld/folder1/test1.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
$( document ).ready ( function () {
$("#templates").on("change", function () {
[.... here I want to pass data to object element ...]
$("#test").show();
});
}
);
</script>
</head>
<body>
<label>Open object </label>
<select id="templates name="templates">
<option value="1">Template1</option>
<option value="2">Template2</option>
<option value="3">Template3</option>
</select>
<div id="test" style="display: none;">
<object type="text/html" data="https://domain.tld/folder2/editor.php">
</object>
</div>
</body>
</html>
test div element is opened full screen when select element is changed. I want to pass selected value to "https://domain.tld/folder2/editor.php" html code, because I need to make some custom details to it according to selected value. Is it possible?
Hope you can understand me.
Thank you so much for your help.
John
A: yes it is, you can use AJAX :
var dataIn = { someKey : "someValue" };
$.ajax({
url : "https://domain.tld/folder2/editor.php",
data : dataIn,
success : function ( result ) {
// do something with the response
}
});
or $.get or $.post depending on what you need in your backend.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42491824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: LinkedIn API OAuth issue This is my first time using the LinkedIn API. I am using Python.
I am exactly following the steps listed here: https://developer.linkedin.com/documents/getting-oauth-token-python
Everything goes well until I try to get the PIN for the access token. I type into my browser: "https://www.linkedin.com/uas/oauth/authorize?oauth_token=" + oauth_token , and then I get the error "We were unable to find the authorization token."
I also tried to download the full code linked at the top of the page, but that goes to a "page not found".
Anyone have any insight as to why I can't get the access token PIN? Thank you.
A: I apologize for not seeing this sooner. The code on that page has been restored and you can download it now without issue.
https://developer.linkedin.com/documents/getting-oauth-token-python
If it's still not working, please let us know (I'll check back here, or you can post in our forums). I use essentially that exact code whenever I test our API so it should work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8015934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: System.Data.SqlClient.SqlException: Incorrect syntax near ')' I am getting an error in my SQL command with which I am trying to retrieve values from a SQL Server database. It is showing a error in browser as mentioned in title. If I remove the brackets it shows error in AND operator
string jdate = (string)Session["jdate"];
string clas = (string)Session["class"];
string scode = (string)Session["scode"];
string dcode = (string)Session["dcode"];
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ToString());
// error shows up on this line
string slct = "SELECT Route.Route_Source, Route.Route_Destination, Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time, Schedule.Route_rate_Ad , Seats." + jdate +
"Schedule.Sch_id FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id INNER JOIN Route ON Schedule.Route_id = Route.Route_id INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id WHERE (Route.Route_Source =" + scode + ") AND (Route.Route_Destination =" + dcode + ") AND (Seats.Class=" + clas + ") ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(slct, cn);
DataSet ds = new DataSet();
da.Fill(ds);
SearchView.DataSource = ds;
SearchView.DataBind();
A: You should use a parameterized query.
This would allow a more understandable query text, avoid simple syntax errors
(like the missing comma at the end of the first line (jdate)),
avoid Sql Injections and parsing problems with strings containing quotes or decimal separators
string slct = @"SELECT Route.Route_Source, Route.Route_Destination,
Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time,
Schedule.Route_rate_Ad, Seats." + jdate + ", Schedule.Sch_id " +
@"FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id
INNER JOIN Route ON Schedule.Route_id = Route.Route_id
INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id
WHERE (Route.Route_Source = @scode)
AND (Route.Route_Destination =@dcode)
AND (Seats.Class=@class)
ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";
cn.Open();
SqlCommand cmd = new SqlCommand(slct, cn);
cmd.Parameters.AddWithValue("@scode", scode);
cmd.Parameters.AddWithValue("@dcode", dcode);
cmd.Parameters.AddWithValue("@class", clas);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22731593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Count cells by their color in Excel This question is simple: How can I update a total number count in Excel that decreases based on how many red X's there are in a given column.
Where this becomes too complicated for me: I have made macros to sort cells based on numbers or color. There are five different colors, each representing a different county in my area. I have a total for each county. (ex. yellow = 41, blue = 15, red...) and want to update each colors total respectively (by subtracting 1 for each X) IF there is an X in the completed column.
So issues:
*
*How to keep track of a row of cells, though they may be sorted three
different ways at any given time (Is there a permanent cell ID?).
*How to update a number count for just a certain range of cells of the
same color.
Attached is a picture of the top of the spreadsheet to better understand how this looks:
any help is greatly appreciated, my unfamiliarity with excel functions is probably the root cause of this problem.
A: Solution: This can be done without VBA if you can add the county name for each entry. Let's say, you are putting them into column J (see yellow cells in below picture).
Then, to count totals, simply use the COUNTIF function to get the total number of rows for a county and substract those who are marked "X" using the COUNTIFS function. In cell N2, I entered:
=COUNTIF(J:J,L2)-COUNTIFS(J:J,L2,H:H,"X")
Add the other county names below the existing ones in column L and copy the formula from N2 to the cells below.
Explanation: COUNTIF counts the number of rows that match one criterion. Here, we are setting the county name (L2 for the first county) and we are looking for it in column J. Next, we need the number of rows that match both the county and the completion state of "X". COUNTIFS will do the trick as it counts the number of rows that match two or more criteria. In this case, we want the number of rows of a given county (column J) and we want them to be the value of a value in column L ("Bronx" for N2, "Manhattan" for N3 etc.). The second criterion is their completion state (column H) which you want to be X (specified in the formula as "X"). You then substract the second from the first number.
Edit: By the way, sorting does not affect these formulas, they will continue to work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31027679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can Deferred object chains be used on event handlers? I'm somewhat new to Javascript / jQuery (but not to programming), so please excuse any ignorance on this matter. I've already looked at this question and this one, but neither one solved my problem.
My scenario: I have a slideshow written in Javascript / jQuery. In this slideshow, I would like show the controls (play button, backward, forward) when the user hovers over the slide and hide them when the mouse leaves the slide area. The buttons show and hide as expected, but when I hover over one of the buttons (which are also over the slideshow) it disappears (which I know is because of "mouseleave" on the slide).
I tried adding hover event handlers to my buttons to change a global boolean so that the slideshow controls will only be hidden if that boolean is false (meaning the "mouseenter" for one of the buttons wasn't fired). I then registered the "mouseenter" event before the "mouseleave", but it didn't work.
Here's the problem: Despite the "mouseenter" event for the button being fired before the "mouseleave" event for the slide, the event handler callbacks are executed in the opposite order. I'm not entirely sure why this is happening, but I know that it has to do with how hover events are handled in Javascript.
I read a little bit about Deferred objects and I'm wondering if this might be the right way to go about this?
The syntax is incorrect, but I'm thinking something along the lines of:
function isMouseOverButton() {
if(mouseEnteredButtonEvent()) {
window.isOverButton = true;
} else {
window.isOverButton = false;
}
function hideControls() {
if(!window.isOverButton) {
//hide buttons
}
}
$.when($("#slide").mouseleave()).then(isMouseOverButton()).then(hideControls());
Is there anyway to combine event handlers and deferred objects like this? Or, is there a better way than deferred objects?
EDIT: I just came across this, but I would prefer not to use a plugin to accomplish this.
A: Nope, this is not the way to do it!
When the mouse enters the slides, you show the controls, and when the mouse leaves the slides, you hide the controls, except if the mouse enters the controls.
To do this you'll use a small timeout and check if the mouse entered the controls before they are hidden away.
var timer;
$('#slide').on({
mouseenter: function() {
clearTimeout(timer);
$('.controls').show();
},
mouseleave: function() {
timer = setTimeout(function() { //don't hide them right away
$('.controls').hide();
}, 400); // set a timeout
}
});
$('.controls').on({
mouseenter: function() {
clearTimeout(timer); // if the mouse entered the controls,
}, // clear the timeout, keeping the controls visible,
mouseleave: function() {
timer = setTimeout(function() {
$('.controls').hide();
}, 400);
}
});
FIDDLE
A much easier way to do the same thing, would be to place the controls inside the #slide element in the HTML, that way they won't trigger the mouseleave event, but that's not always possible, or convenient.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16500820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Link binary with static library in xcconfig I have an Xcode project that is essentially a single app that gets built into several almost identical targets. I have moved nearly all build configuration settings in central places, but I cannot figure out how to move linking against a static library (libMantle.a) to the xcconfig. I have tried the -framework and -l flags, like I'm using for various other libraries, but they don't work. Is there a way to get .a files out of the Link Binary with Libraries pane, so I don't need to keep all the targets in sync manually?
A: Figured it out...
Let's say you want to link against the file libGoogleAnalyticsServices.a. There are basically three things you should have in your .xcconfig to get it working.
First you want to make sure you have the path to the library in your search path. Then you need to pass two flags to make the linker happy -L with the path to the directory, and -l with the library.
Putting it all together will get you something like:
LIBRARY_SEARCH_PATHS = $(inherited) "$(SRCROOT)/Vendor/Google Analytics"
OTHER_LDFLAGS = $(inherited) -L"$(SRCROOT)/Vendor/Google Analytics" -lGoogleAnalyticsServices
(You would need to adjust for your relative paths)
The most helpful thing in getting this sorted out was the Log Navigator (command+8 in Xcode). By putting the static library in the Build Phases Link Binary With Libraries panel and doing a successful build, you can look details of the linker step in the logs, and see how it was passing the Analytics library to the compiler. From there it's just replicating those flags in the xcconfig.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19102565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Indentation after chain of method calls Even though I should have the same setup as the rest of my team, Eclipse's formatter has one small anomaly in my setup.
You can see the difference in the attached picture.
On the left is my formatting.
On the right is the rest of the team's formatting.
I want to have the same formatting as the rest of the team.
The difference arises when there is an empty line after a chain of method calls.
Question: How do I achieve the formatting on the right?
A: I expect you are using the same formatter definition and have already tried to export the formatter on one of your team members machine and import it on yours.
Another thing you should check are the Save Actions in the preferences (Java -> Editor -> Save Actions). Maybe the settings for removing whitespaces differs here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50097881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to print messages on console in Laravel? How do laravel print out some string on console when running php artisan serve?
I tried Log::info but it isn't working.
A: It's very simple.
You can call it from anywhere in APP.
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("Hello from Terminal");
A: You've to config where laravel to store the logs. Default Log::info() put the log in the log file not the console. you can use tail -f logpath to see the log.
A: Try with
error_log('message here.');
Read More
If You ant add LOG
Log::info('message');
If LOG with an array
Log::info(json_encode($array));
Import Illuminate\Support\Facades\Log;
A: Laravel 5.6 simplified this because you now have a logging.php config file you could leverage.
The key thing to know is that you want to output to stdout and php has a stream wrapper built-in called php://stdout. Given that, you could add channel for that wrapper. You would add the stdout "channel" to your channels that you will be logging to.
Here's how the config will basically look:
<?php
return [
'default' => env('LOG_CHANNEL', 'stack'),
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single','stdout'],
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'stdout' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'with' => [
'stream' => 'php://stdout',
],
],
];
I have more information here - Laravel 5.6 - Write to the Console
A: You can call info() method
$this->info("Your Message");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42324438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: What does 'G' do with sed command? I have tried two different sed commands against a text file called "file1.txt".
I have received the same result or output. What I don't understand is the meaning or use of "G" option! I have searched online, but I couldn't find a good answer!
Here are two commands:
sed 'G' file1.txt
sed '/^$/d;G' file.txt
Both commands give the same output! They create a one line gap between each line in the text file!
I know that'^$' refers to line containing nothing, but what does 'G' do. For example if I put 'd' instead of 'G' all blank lines will be deleted!
A: Get with g or G
Instead of exchanging the hold space with the pattern space, you can copy the hold space to the pattern space with the "g" command. This deletes the pattern space. If you want to append to the pattern space, use the "G" command. This adds a new line to the pattern space, and copies the hold space after the new line.
That is, instead of swapping the current contents of the hold and pattern space (current line, etc) you can take the pattern space and copy it into the hold space (either replacing or appending to the hold space in the process).
Those two sed commands are among the idiomatic sed one-liners that you can find online and they do the same thing only for certain files (those without blank lines in them).
# double space a file
sed G
# double space a file which already has blank lines in it. Output file
# should contain no more than one blank line between lines of text.
sed '/^$/d;G'
A: According to the man sed:
*
*g
Replace the contents of the pattern space with the contents of the hold space.
*G
Append a newline to the contents of the pattern space, and then
append the contents of the hold space to that of the pattern space.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29435598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: TypeError: Cannot read property 'uid' of undefined This is my first javascript function for firebase.
TypeError: Cannot read property 'uid' of undefined
I got this error in firebase cloud function.How to resolve it?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.grantSignupReward = functions.database.ref('/users/{uid}/last_signin_at')
.onCreate(event => {
const uid = event.params.uid;
admin.database().ref(`users/${uid}/referred_by`)
.once('value').then((data) => {
var referred_by_somebody = data.val();
if (referred_by_somebody) {
var moneyRef = admin.database().ref(`/users/${uid}/earned`);
moneyRef.transaction((current_value)=> {
return (current_value || 0) + 10;
});
}
return console.log('reddem updated')
}).catch(error => {
console.log("Got an error: ",error);
});
});
A: The cloud functions were updated, therefore you need to change this:
exports.grantSignupReward = functions.database.ref('/users/{uid}/last_signin_at')
.onCreate(event => {
const uid = event.params.uid;
into this:
exports.grantSignupReward = functions.database.ref('/users/{uid}/last_signin_at')
.onCreate(snap,context) => {
const uid = context.params.uid;
more info here:
https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50085894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# .net serial port receive buffer always emtpy I am trying to receive some data from a microcontroller connected to a windows PC through USB. I am doing this with the .net SerialPort functionality as you can see in my code below. I know the sleep is not very elegant but this is just my test code since I cannot get this to work.
Basically I have an Arduino sending some data which I can receive with the Arduino Serial Monitor, my c# program only outputs emtpy lines though, and the receive buffer is always emtpy. (the exact code you see here will output a zero and an emtpy line every second, even though a random number is sent every 200ms)
I already confirmed the baudrate is correct on both ends, I also switched over to a raspberry pi pico which had the same result.
I would really appreciate it if someone could help out here, as far as google is aware I must be the first one to run into this :D
using System;
using System.IO.Ports;
using System.Threading;
namespace serial_test
{
class Program
{
static void Main(string[] args)
{
SerialPort testPort = new SerialPort("COM9", 9600);
testPort.Open();
while (true)
{
Thread.Sleep(1000);
Console.WriteLine(testPort.BytesToRead);
Console.WriteLine(testPort.ReadExisting());
}
}
}
}
A: Instead of running an endless loop you may want to subscribe to the port's DataReceived event. You can then create a variable within the handler to read the data.
var port = (SerialPort)sender;
// Retrieve and write your data here
This may be easier to debug since you can place a breakpoint in the handler. If you never receive any data then you may have a handshake problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69429287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript function calling syntax (function($,window,undefined) {
$.fn.simplyScroll = function(options) {
return this.each(function() {
new $.simplyScroll(this,options);
});
};
var defaults = {
customClass: 'simply-scroll',
frameRate: 30, //No of movements per second
speed: 2, //No of pixels per frame
orientation: 'horizontal', //'horizontal or 'vertical' - not to be confused with device orientation
auto: true,
autoMode: 'loop', //auto = true, 'loop' or 'bounce',
manualMode: 'end', //auto = false, 'loop' or 'end'
direction: 'forwards', //'forwards' or 'backwards'.
pauseOnHover: false, //autoMode = loop|bounce only
pauseOnTouch: true, //" touch device only
pauseButton: false, //" generates an extra element to allow manual pausing
startOnLoad: false //use this to delay starting of plugin until all page assets have loaded
};
Hi I'm pretty new to javascript and the syntax, especially function wise. How would I get the value of auto in the defaults object when it's wrapped in a function like this?
I know to get auto would just be defaults.auto, but since the function isn't named I'm not sure how to even get into it. I'm planning on changing the value at a later point in an external javascript file.
A: You cannot obtain this value if your code is outside of the function, unless this function stores the object in the defaults variable somewhere where it can be reached through a global variable. This is due to the way that JavaScript functions work -- code external to the function has no access to that function's local variables. (This is not very different from other programming languages.)
If your goal is only to change the value rather than obtain the default value, most jQuery plugins will allow you to pass in an object whose properties will override the default settings. Based on the name of the plugin, you could do so like this:
$("#something").simplyScroll({
auto: false
});
A: In my opinion, there are 2 ways that allows you to access to defaults object outside this function scope
1. In function scope, defaults object will be assigned to a propery of global object (= window)
...
// In the function scope
window.defobject = defaults;
...
For example:
(function($, window, undefined) {
var defaults = {
foo : "bar"
};
window.defobject = defaults;
})(jQuery, this);
console.print(defobject); // This is valid with no error
2. The function finally return this object as output
...
// In the function scope
return defaults;
For example:
var defobject = (function($, window, undefined) {
var defaults = {
foo : "bar"
};
return defaults;
})(jQuery, this);
console.print(defobject); // This is also valid with no error
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25018080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot get websocket connection working with ec2 + application load balancer I am having trouble establishing a websocket connection. I have an aws ec2 instance that is running an SSL websocket server on a subdomain: api.example.com, on port 9999. My client application is running at www.example.com, the client sets up a listener:
new WebSocket('wss://api.example.com:9999');
This results in the browser giving me:
net::ERR_CONNECTION_REFUSED
So my next idea was since my application load balancer already has an https listener setup on port 443 going to my api server, I changed my websocket listener setup to:
new WebSocket('wss://api.example.com/socket');
Then I made my nodejs (restify) webserver on the ec2 instance catch /socket with plans to redirect it to localhost:9999... However, I put a console.log in that /socket endpoint prior to redirecting, and there is no logging happening-- I also tried wss://api.example.com:443/socket, neither seems to hit the endpoint in my webserver.
Yet if I use curl, it works fine:
~>curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: api.example.com" -H "Origin: https://www.example.com" https://api.example.com/socket
HTTP/2 301
date: Tue, 26 Jun 2018 02:27:07 GMT
content-type: application/json
content-length: 4
location: https://localhost:9999/localhost
server: restify
access-control-allow-origin: https://www.example.com
vary: origin
access-control-expose-headers: api-version, content-length, content-md5, content-type, date, request-id, response-time
although https://localhost:9999/localhost seems a little weird-- but regardless, when I use curl, it hits the endpoint and I see the log.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51034212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Web API, API Controller and how to update a model? I'm trying out the API controller in MVC 4 and have a question about best practice when using put, updating an object.
I'm using RavenDB as data storage and I have created a custom MediaTypeFormatter that has a converter of type JsonDynamicConverter that can serialize and deserialize json to a dynamic object. With that said my API controllers Put method looks like this
public void Put(string id, dynamic model) {}
this dynamic object looks sorta like this:
pageModel = {
"id": "pages-2",
"metadata": {
"changed": "2012-02-28T17:16:27.323Z"
},
"parent": {
"id": "pages-1",
"slug": null
},
"children": []
}
so, so far so good but now I need to update my entity with id pages-2.
The UpdateModel does not exist in the ApiController so my question is what is the best/preferred way of doing this?
A: Simply call RavenDB to load the object with the appropriate ID, make the changes to its contents and persist it again.
No need to worry about any UpdateModel calls. It doesn't apply here.
Be aware of one potential issue since you are including the id in the model. If I sent a PUT command to http://server/controller/pages-3 with that body what would happen? You should probably send me a bad request response or something similar depending on how you want your API to work.
A: Is there any reason not to be explicit in your parameters? I would define an UpdateModel and take that as parameter instead of the dynamic. Then it also would be able to model validation.
ASP.NET WebApi includes handling of converting from both JSON and XML as input to your controller methods. I'm guessing your combination of custom mediatypeformatter and use of dynamic would be unneccesary in this case, if there is not something I'm missing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9486745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Route generator for 'item' was not included in parameters error Screenshot of error:
plunker (currently not working):
plnkr.co/edit/ft9Z4mq8C1llpAxA0Z1v?p=catalogue
Link to full project:
https://www.dropbox.com/s/0579y250pq5eti5/Project33.zip?dl=0
Full code of wiki.component.ts (code of page that causes error):
import { Component } from 'angular2/core';
import { JSONP_PROVIDERS } from 'angular2/http';
import { Observable } from 'rxjs';
import { WikipediaService } from './wikipedia.service';
import {Router, RouteParams, RouterLink, ROUTER_DIRECTIVES} from 'angular2/router';
@Component({
selector: 'Wikithing',
template: `
<h1>Search and Display Page</h1>
<p><i>Fetches after each keystroke</i></p>
<input #term (keyup)="search(term.value)"/>
<ul>
<li *ngFor="#item of items | async">{{item}} <br> <p>
</p> Price (in USD): $ {{item.price}} <br> <p>
</p> Availability: 24 hours <br> <p>
</p> Quantity currently in stock: {{quantity}}
<br> <p>
</p> Image of item: <img src="http://weknowyourdreamz.com/images/apple/apple-05.jpg" alt="Apple" style="width:100px;height:100px;">
<br> <p>
</p>
<p>
</p>
<a [routerLink]="['BiddingPage']">Click here to bid on this item.</a>
<button (click)="gotoItem(item)">Click here to bid on this item.</button>
<p>
</p>
<br> <p>
</li>
</ul>
`,
providers:[JSONP_PROVIDERS, WikipediaService],
directives: [ROUTER_DIRECTIVES, RouterLink],
})
export class WikiComponent {
constructor (private wikipediaService: WikipediaService, private router:Router) {}
items: Observable<string[]>;
// item: Item[] = [];
search (item: string) {
this.items = this.wikipediaService.search(item);
this.items.map((items) => items.map(() => ({
name: items,
prices: Math.random(),
quantity: Math.random(),
availability: Math.random()
})));
var Prices = Math.random() + Math.random();
var quantity = Math.random();
}
gotoItem (item: any) {
this.router.navigate(['BiddingPage', {item: item}]);
}
}
More information and context of problem:
stackoverflow.com/questions/37422205/displaying-data-that-is-consistent-with-search-results-on-a-different-webpage-t
A: Disclaimer: My english can be bad, sorry :c.
That is because in your @RouteConfig you have declarated that you need a item parametter like this:
{path: '/BiddingPage/:item', name: 'BiddingPage', component: BiddingPageComponent},
And in your template you doesn't have that parametter:
<a [routerLink]="['BiddingPage']">Click here to bid on this item.</a>//the "item" is missing
Your template should be like this:
<a [routerLink]="['BiddingPage',{item:item}]">Click here to bid on this item.</a>
Enjoy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37449851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Set size 'gridcolumn' by content in ExtJS I have a gridview with columns. Here example :
{
xtype: 'gridcolumn',
header: '№',
dataIndex: 'number'
},
Is there any way to autosize column by content?
Thanks!
A: Yes just use the flex property.
Example:
column1 flex: 1 column2: flex: 1
|-----Column 1-----|-----Column 2-----|
column1 flex: 2 column2: flex: 1
|--------Column 1--------|--Column 2--|
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12639073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make Graph like below image in angular As I am New To Angular i am facing issue in Graph , I don't now how to make this in angular
Tried with Chart.js and Canvasjs In both i am facing problem
1. With Chart.js i was able to create static graph like below image, but i am not getting how to get data from API for this graph.
Note: I am Able to display any kind of data Using API , except Graph So, Please Help me with this Graph thing.
LineChart = {};
ngOnInit() {
// Line chart:
this.LineChart = new Chart('lineChart', {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: 'Number of Items Sold in Months',
data: [9, 7, 3, 5, 2, 10, 15, 16, 19, 3, 1, 9],
fill: false,
lineTension: 0.2,
borderColor: 'white',
borderWidth: 1
}]
},
options: {
title: {
text: 'Line Chart',
display: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Note: I am Able to display any kind of data Using API , except Graph So, Please Help me with this Graph thing.
Graph should Come
A: Before Initialising the Chart Object, fetch the data from the API and create the data array, then initialise the Chart Object.
If you want the graph to be continually changing, use Observables to get the data continuously and keep updating the charts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55378595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting component of stock market index from YQL Currently, I can get stock quote by returning xml and json using YQL console like
select symbol, price from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=IBM,YHOO,GOOG,MSFT&f=sl1d1t1c1ohgv&e=.csv' and columns='symbol,price,date,time,change,col1,high,low,col2'
I would like to get the complete component list from
http://download.finance.yahoo.com/d/quotes.csv?s=@^HSI&f=sl1d1t1c1ohgv&e=.csv
using YQL console, so I input the statement below in YQL console
select symbol, price from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=@^HSI&f=sl1d1t1c1ohgv&e=.csv' and columns='symbol,price,date,time,change,col1,high,low,col2'
but it said my link is invalid. Any thoughts and alterative solutions?
A: Your query was very nearly correct, but the URL was considered "invalid" as you noted. The solution is to properly escape the query string values.
http://download.finance.yahoo.com/d/quotes.csv?s=@^HSI&f=sl1d1t1c1ohgv&e=.csv
becomes
http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EHSI&f=sl1d1t1c1ohgv&e=.csv
Changing just those two characters into their %-encoded values allows YQL to pull back the CSV data.
select * from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EHSI&f=sl1d1t1c1ohgv&e=.csv'
Aside: YQL doesn't like that the CSV has an empty line at the end of the file, this will cause issues when you try to use the columns where clause. If you're okay with having the columns called col<number> and want to skip the last (empty) row then use and col8 is not null at the end of your query.
A: This is the correct url:
http://quote.yahoo.com/d/quotes.csv?s=<symbol>&f=sl1d1t1c1ohgv&e=.csv
For Coca Cola:
http://quote.yahoo.com/d/quotes.csv?s=KO&f=sl1d1t1c1ohgv&e=.csv
Result: "KO",69.74,"9/2/2011","4:00pm",-0.71,69.7201,69.99,69.50,8765529
For HSI:
http://quote.yahoo.com/d/quotes.csv?s=^HSI&f=sl1d1t1c1ohgv&e=.csv
"^HSI",19616.40,"9/5/2011","4:01am",-596.51,19830.50,19830.50,19567.77,0
Here is an API document:
http://www.gummy-stuff.org/Yahoo-data.htm
A: The above solutions don't fully answer the question unfortunately, you will only get the first 51-52 results (the first page) and not the full index.
I don't think this is possible in raw YQL but you will need to write some code to get the HTML and then loop through each page of components and build your own datatable up from it.
I have tried a few ways and have a C# script that can do it, it would also be trivial to do this in Python and just load it into a pandas dataframe as you go along or just a plain list/tuple if all you want is the symbols to build up a component list for testing a portfolio against.
If people are still interested in this solution I can post the link to it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7303445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Angular2 CLI Socket.io (3rd Party Library import) angular-cli: 0.0.39
node: 6.2.2
os: win32 x64
I tried to import socket.io-client into an angular2 app generated with the angular-cli but i can't get it to work.
chat.component.ts
import * as io from "socket.io-client";
@Component({
...
})
export class ChatAppComponent {
...
}
system-config.ts
/** Map relative paths to URLs. */
const map: any = {
"socket.io-client": "vendor/socket.io-client/socket.io.js"
};
/** User packages configuration. */
const packages: any = {
"socket.io-client": {"defaultExtension": "js"}
};
angular-cli-build.js
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/*.js',
'es6-shim/es6-shim.js',
'reflect-metadata/*.js',
'rxjs/**/*.js',
'@angular/**/*.js',
'socket.io-client/socket.io.js'
]
});
};
package.json
{
"dependencies": {
...
"socket.io-client": "^1.4.8",
"systemjs": "0.19.26"
},
"devDependencies": {
...
"typescript": "^1.8.10",
"typings": "
}
}
typings.json
{
"ambientDevDependencies": {
"angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
"jasmine": "registry:dt/jasmine#2.2.0+20160412134438",
"selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
},
"ambientDependencies": {
"es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654",
},
"globalDependencies": {
"socket.io-client": "registry:dt/socket.io-client#1.4.4+20160317120654"
}
}
Error and stacktrace
Error: Typescript found the following errors:
C:/Users/Christian/Desktop/prototypes/chat-client/tmp/broccoli_type_script_compiler-input_base_path-5WNagLgm.tmp/0/src/app/chat.component.ts (4, 21): Cannot find module 'socket.io-client'.
at BroccoliTypeScriptCompiler._doIncrementalBuild (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\lib\broccoli\broccoli-typescript.js:115:19)
at BroccoliTypeScriptCompiler.build (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\lib\broccoli\broccoli-typescript.js:43:10)
at C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\index.js:152:21
at lib$rsvp$$internal$$tryCatch (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\node_modules\rsvp\dist\rsvp.js:1036:16)
at lib$rsvp$$internal$$invokeCallback (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\node_modules\rsvp\dist\rsvp.js:1048:17)
at lib$rsvp$$internal$$publish (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\node_modules\rsvp\dist\rsvp.js:1019:11)
at lib$rsvp$asap$$flush (C:\Users\Christian\Desktop\prototypes\chat-client\node_modules\angular-cli\node_modules\broccoli-caching-writer\node_modules\rsvp\dist\rsvp.js:1198:9)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
A: 1) Install socket.io-client
npm install socket.io-client --save
2) Install socket.io-client typings
npm install @types/socket.io-client --save-dev
3) Import socket.io-client in your app/code
import * as io from "socket.io-client";
A: Is this file present node_modules/socket.io-client/socket.io.js.
Check dts file is present in typings folder for socket-io.
Since you already specified the extension in map no need to specify it again in defaultExtension of package.
Try adding format: 'cjs' OR format: 'amd' based on library in the package -> socket.io-client
A: system-config.ts
/** Map relative paths to URLs. */
const map: any = {
"socket.io-client": "vendor/socket.io-client/"
};
/** User packages configuration. */
const packages: any = {
"socket.io-client": {
format: 'cjs',
defaultExtension: 'js',
main: 'socket.io.js'
}
};
angular-cli-build.js
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'socket.io*/**/*.js'
]
});
};
Working like a charm angular-cli: "1.0.0-beta.10"
A: This works for me:
npm install --save @types/socket.io-client
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38191549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: RSA decrypt incorrect parameter For our program we do some preprocessing to validate the integrity of some data files. We do this by calculating a hash encrypted with a private key and on runtime decrypt the hash using the public key and check it against the hash of the data files.
We have created a precompiler that automatically generates a new keypair. The public key gets put in a .cs-file somewhere and will be used by the program. The private key information is stored in a temporary file to be used later by a program that calculates the hash and encrypts it.
This is the code that generates the keypair and stores it.
// make keys
var rsa = new RSACryptoServiceProvider(384);
var key = rsa.ExportParameters(true);
// store public key in generated cs file
File.WriteAllText(Program.keyFileName, string.Format(Program.keyFileTemplate, Convert.ToBase64String(key.Exponent), Convert.ToBase64String(key.Modulus)));
// store private key in temporary file
File.WriteAllText("private-key.temp", rsa.ToXmlString(true));
After this, the actual program is compiled and we run a postcompiler. The RSA parameters are imported again as follows:
// read private key
string keyXml = File.ReadAllText("private-key.temp");
File.Delete("private-key.temp");
var rsa = new RSACryptoServiceProvider(384);
rsa.FromXmlString(keyXml);
We then process the data files and calculate a hash which is then saved to a variable called hashBytes (a byte array). Because I want to use the private key pair, I now decrypt this string using RSA (because encryption would use the public key pair and that is not what we want here) with the previously created instance as follows:
var toEncrypt = new byte[rsa.KeySize / 8];
hashBytes.CopyTo(toEncrypt, 0);
try
{
rsa.Decrypt(toEncrypt, false);
}
catch (CryptographicException e)
{
Console.WriteLine("whoops: " + e.Message);
}
However, this results in a CryptographicException "The parameter is incorrect." After looking around I have not even found the exact meaning of this error, but I suggest there is something wrong with the RSA parameters, which is surprising because I would assume using the XML string would just work.
What am I doing wrong?
EDIT:
I have removed the fixed key size and now encrypt the hashBytes directly. It seems I understood it wrong that the key and plaintext do not have to be the same size. However, I now get a "Bad Data." exception instead of the incorrect parameter one. Encryption does not give any errors though.
A: I have solved the problem by using the Sign methods provided by the RSACryptoProvider I did not know about. The last code block has become the following:
try
{
var hashBytes = rsa.SignData(stream, new SHA256CryptoServiceProvider());
File.WriteAllBytes(Program.modPath + "default.rf-modsignature", hashBytes);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21801975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Flutter semantic label does not work with VoiceOver on iOS This is an app specifically for blind and partially sighted users and rely heavily on VoiceOver who mainly use the iPhone. Upgraded to Flutter 3.0.2 did a flutter clean, pub upgrade and pub get but the issue still persists. Running on an iPhone SE 2nd Gen with iOS 15.5
Any possible workaround would be much appreciated. Thanks.
Steps to Reproduce
*
*Execute flutter run on the code sample
*Enable VoiceOver on iOS
*Tap on any or all of the 3 displayed icons "compose", "camera" & "chat"
Expected results:
Expected the VoiceOver to read out the semantic labels: edit profile, camera screen & chat screen
Actual results:
VoiceOver instead reads out: compose, camera button, chat button
Even tried it with the "Semantics" widget with a label and excluding the children but the same issue (This works perfectly on Android 11 (OnePlus Nord2 CE) though)
Code sample:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'VoiceOver Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'VoiceOver Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: InkWell(
onTap: () {},
child: IconButton(
icon: const Icon(Icons.edit, semanticLabel: "edit profile",),
tooltip: 'edit profile tooltip', onPressed: () { },
),
),
),
bottomNavigationBar: BottomAppBar(
color: Theme.of(context).colorScheme.secondary,
elevation: 5,
child: Row(
children: [
IconButton(
icon: Icon(
Icons.camera_alt_outlined,
size: 36,
color: _currentIndex == 0 ? Colors.white:Colors.grey,
semanticLabel: "camera screen",
),
onPressed: () {
_currentIndex = 0;
print("Page 1");
}
),
const Spacer(),
IconButton(
icon: Icon(
Icons.chat_outlined,
size: 36,
color: _currentIndex == 1 ? Colors.white:Colors.grey,
semanticLabel: "chat screen",
),
onPressed: () {
_currentIndex = 1;
print("Page 2");
}
),
],
),
),// This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Few others I tried:
body: Center(
child: Semantics(
label: "edit profile",
excludeSemantics: true,
child: IconButton(
icon: const Icon(
Icons.edit,
size: 36,
color: Colors.blue,
),
onPressed: () {
}
),
)),
body: Center(
child: Semantics(
onDidGainAccessibilityFocus: () {
SemanticsService.announce("edit profile", TextDirection.ltr);
},
label: "edit profile label",
excludeSemantics: true,
child: IconButton(
icon: const Icon(
Icons.edit,
size: 36,
color: Colors.blue,
),
onPressed: () {
}
),
)),
Logs:
/Users/me/Projects/voiceoverdemo/voiceoverdemo_test_flutter/ios/Runner/Info.plist
[ ] <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>VoiceOver Test Flutter</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>voiceoverdemo_test_flutter</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
{
"simulator" : false,
"operatingSystemVersion" : "15.5 (19F77)",
"interface" : "usb",
"available" : true,
"platform" : "com.apple.platform.iphoneos",
"modelCode" : "iPhone12,8",
"identifier" : "XXXXXXXX-XXXXXXXXXXXXXXXX",
"architecture" : "arm64e",
"modelUTI" : "com.apple.iphone-se-1",
"modelName" : "iPhone SE",
"name" : "Me's iPhone"
},
flutter analyze:
Analyzing voiceoverdemo_test_flutter...
No issues found! (ran in 2.5s)
flutter doctor -v
[✓] Flutter (Channel stable, 2.10.5, on macOS 12.3.1 21E258 darwin-x64, locale en-GB)
• Flutter version 2.10.5 at /Users/me/software/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 5464c5bac7 (8 weeks ago), 2022-04-18 09:55:37 -0700
• Engine revision 57d3bac3dd
• Dart version 2.16.2
• DevTools version 2.9.2
[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
• Android SDK at /Users/me/Library/Android/sdk
• Platform android-31, build-tools 31.0.0
• Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• CocoaPods version 1.11.2
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 2021.2)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
[✓] IntelliJ IDEA Community Edition (version 2021.3.3)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
• Flutter plugin version 66.0.3
• Dart plugin version 213.7371
[✓] VS Code (version 1.68.0)
• VS Code at /Users/me/Software/Visual Studio Code.app/Contents
• Flutter extension version 3.42.0
[✓] Connected device (2 available)
• Me's iPhone (mobile) • XXXXXXXX-XXXXXXXXXXXXX • ios • iOS 15.5 19F77
• Chrome (web) • chrome • web-javascript • Google Chrome 102.0.5005.115
[✓] HTTP Host Availability
• All required HTTP hosts are available
• No issues found!
https://user-images.githubusercontent.com/5812030/174106131-a6be4e0c-e650-46cf-87ea-0c635c0d04c5.jpg
This works fine in the simulator with the Accessibility Inspector:
https://user-images.githubusercontent.com/5812030/174129522-29ff6a1f-38a4-4593-93c5-4f34e08e891e.png
Recording:
https://user-images.githubusercontent.com/5812030/174270320-159d3fb7-135a-417b-b9d1-c3a8e2f526f1.MP4
A: Found the issue. For some reason a setting was enabled on my iPhone. When I switched it off it worked perfectly.
Settings -> Accessibility -> Voice Over -> VoiceOver Recognition -> Screen Recognition -> Apply to Apps
This setting had the app added to it. When I removed the app from this list it worked fine
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72656555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is a proper way to inject an object that needs parameter inside servlets in java ee? I'm making a java application using jsp and servlets. I want to store some data in HTTP session but I want to use the session only inside a RepositoryImpl class. I also have an interface called Repository with methods like addItem() and getData(). So my RepositoryImpl class implements these methods and uses HTTP session to store the data.
I want to inject the RepositoryImpl class into different servlets to use it as an instance of Repository interface. The problem is I don't know how to pass the session to the RepostioryImpl instance with ejb or cdi. What is the best way to handle my problem?
A: Let me see if i understand.
You want to store data in session, like a shopping cart?
If you want to store in session an entire object you can set it in a usebean.
<jsp:useBean id="objectname" scope="session" class="com.mypackage.myclass"/>
This way you can call the object and it's methods wherever the usebean is.
I hope this could help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73868478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: facebook login issue in ios9 In my app i integrated facebook login , and put all the settings required. But when i was trying to login , i get this error
-canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"
But i have put the
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
in the .plist file , is there anyway that i can find the issue ??
edited
self.loginButton.delegate = self;
if (FBSDKAccessToken.currentAccessToken() != nil)
{
// User is already logged in, do work such as go to next view controller.
}
else
{
loginButton.center = self.view.center
loginButton.readPermissions = ["public_profile", "email", "user_friends"]
loginButton.delegate = self
}
//MARK : facebook integration
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
print(result);
if ((error) != nil)
{
// Process error
self.showCancelAlert("Error", message: "Error occured")
}
else if result.isCancelled {
// Handle cancellations
}
else {
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
if result.grantedPermissions.contains("email")
{
// Do work
self.returnUserData();
}else{
self.showCancelAlert("Error", message: "Cannot process with your email address")
}
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
}
// accessToken is your Facebook id
func returnUserProfileImage(accessToken: NSString) -> String
{
let userID = accessToken as NSString
let facebookProfileUrl = NSURL(string: "http://graph.facebook.com/\(userID)/picture?type=large")
if facebookProfileUrl?.absoluteString != nil{
return (facebookProfileUrl?.absoluteString)!;
}else{
return "";
}
}
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("error \(error)")
}
else
{
let userName : NSString = result.valueForKey("name") as! NSString
UserDefaults.sharedInstace.setUsername(userName as String)
if result.valueForKey("email") != nil{
let userEmail : NSString = result.valueForKey("email") as! NSString
if let id: NSString = result.valueForKey("id") as? NSString {
print("ID is: \(id)")
self.showLoading("Signin...")
WebClient.sharedInstace.socialLogin(SocialLogin(uid:String(id) , name: userName as String, imageUrl: self.returnUserProfileImage(id), email: userEmail as String, provider: "facebook"))
} else {
print("ID es null")
self.showCancelAlert("Error", message: "Cannot process with your email address")
self.loginButtonDidLogOut(self.loginButton)
}
}else{
FBSDKLoginManager().logOut()
self.loginButtonDidLogOut(self.loginButton)
print("email es null")
self.showCancelAlert("Error", message: "Cannot process with your email address")
}
}
})
}
A: I think there are a couple things that could cause your problem.
1) Are you sure that you have added the most recent FBSDKCoreKit and FBSDKLoginKit and added these lines to the top of your swift file:
import FBSDKCoreKit
import FBSDKLoginKit
2) I have read that this is just an error on the simulator and should be ignored. Make sure that you are testing on a real device for this feature.
3) Have you included the FBSDKLoginButtonDelegate in the heading of your class declaration?
4) I would make sure that your info.plist source code is all included and correct. Here is what I have added for Facebook in my app:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string> fb + FACEBOOKAPPIDFROMTHEFACEBOOKDEVCONSOLE </string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>FACEBOOKAPPIDFROMTHEFACEBOOKDEVCONSOLE</string>
<key>FacebookDisplayName</key>
<string>NAME OF YOUR APP</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>facebook.com</key>
<dict>
<key>NSIncludesSubdomains</key> <true />
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/>
</dict>
<key>fbcdn.net</key>
<dict>
<key>NSIncludesSubdomains</key> <true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/>
</dict>
<key>akamaihd.net</key>
<dict>
<key>NSIncludesSubdomains</key> <true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/>
</dict>
</dict>
</dict>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38749463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: display hierarchy in django I am using Django to store and display the hierarchy of an organisation. I am struck with displaying the hierarchy of an organisation.
For example:
*
* Priya (CEO)
*
* Harry (Manager)
*
*Rekha (Tester)
I was able store the hierarchy using a single model and referencing to itself as below:
class Emp(models.Model):
name=models.CharField(max_length=30)
manager=models.ForeignKey('self',null=True,blank=True)
designation=models.CharField(max_length=10)
def __unicode__(self):
return self.name
I had an idea to display detail view of each employee when the employee name is clicked but I don't know how to write a view for this and render it to the webpage. Is there a way to directly the hierarchy without using detail view ? Could someone please help.
A: I'd recommend using django-mptt - no need to reinvent the wheel. You'll find everything at https://github.com/django-mptt/django-mptt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42447603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can a Tridion command extension find out the command it extends? Tridion's user interface allows you to extend specific commands, which is a great way to modify the behavior of certain existing commands. In the configuration file of the editor this is done with a section like this:
<ext:commands>
<ext:command name="TextUnderline" extendingcommand="MyTextUnderline"/>
<ext:command name="TextStrikethrough" extendingcommand="MyTextStrikethrough"/>
I am working on a generic command extension class that can be used to modify the behavior of a number of commands:
<ext:commands>
<ext:command name="TextUnderline" extendingcommand="MyCommandExtension"/>
<ext:command name="TextStrikethrough" extendingcommand="MyCommandExtension"/>
So in this second configuration fragment, we have the same MyCommandExtension extending both TextUnderline and TextStrikethrough.
But now in the JavaScript for my MyCommandExtension, how can I determine which command was originally fired?
MyCommandExtension.prototype.isAvailable = function (selection, pipeline) {
...
console.log(this.properties.name);
...
};
In this scenario the this.properties.name will be logged as a less-than-useful-but-completely-correct:
"DisabledCommand"
I suspect that the information is available somewhere in the pipeline parameter, but haven't found it yet.
How can I find out the original command from MyCommandExtension?
A: Short answer: I couldn't.
I had to do something similar, and ended up having to extend various commands and set the "current" command as part of my "_execute" call (so I would now call _execute(selection, pipeline, originalCommand) for my command.
N
A: You cannot find out what the original command is. The assumption is that an extending command is specific to the command it extends and so would know which one it is extending. When creating generic extensions that work on different commands, I can see how it might be useful to know what the configuration would be.
Maybe you could add this as an Enhancement Request?
To work around it for now, you could create a base command with your logic - which takes the name of the command that it extends as a parameter. And then create specific classes for each command you which to extend, which just call the base command and pass in the name.
To put it differently, create a BaseExtendingCommand with all of the required methods - and then both a TextUnderlineExtendingCommand and TextStrikethroughExtendingCommand which call the methods on BaseExtendingCommand (and pass in "TextUnderline" and "TextStrikethrough", respectively, as arguments)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12410599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: AWS DynamoDB SDK 2.x - can I reuse DynamoDbMapper's annotations? We have quite a few entities written for AWS DynamoDbMapper.
I have found that 2.x offers "DynamoDbEnhancedClient".
However that does not seem to have some features, for instance, automatic table creation from a class, like generateCreateTableRequest(clazz). Or am I mistaken?
Reference: https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/dynamodb/model/CreateTableRequest.Builder.html
Ideally, I would like to feed this "enhanced client" the old class with unchanged annotations and get the same table created as with generateCreateTableRequest() from SDK 1.x.
Note that I do not mean just the mapping, like this:
private static final DynamoDbTable<Customer> CUSTOMER_TABLE =
client.table("customers_table", TableSchema.fromBean(Customer.class));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63803022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Subquery becomes column in Mysql query in Magento I have a query in Magento ($Collection) in which I joined a table to have the result I wanted.
This is my $Collection
protected function _prepareCollection()
{
$collection = Mage::getResourceModel($this->_getCollectionClass());
$stmp = "(SELECT GROUP_CONCAT(comment SEPARATOR '----' ) FROM mgmx_sales_flat_invoice_comment a WHERE a.parent_id = `main_table`.`entity_id` group by parent_id)";
$collection->getSelect()->join( array('a'=> mgmx_sales_flat_invoice_comment), 'a.parent_id = main_table.entity_id', $stmp);
$this->setCollection($collection);
echo $collection->getSelect();die();
return parent::_prepareCollection();
}
This $Collection, if you notice I echoed it. It will print this Query.
SELECT
`main_table`.*,
(SELECT
GROUP_CONCAT
(comment SEPARATOR '----' )
FROM
mgmx_sales_flat_invoice_comment a
WHERE
a.parent_id = main_table`.`entity_id
GROUP BY
parent_id)
FROM
`mgmx_sales_flat_invoice_grid`
AS
`main_table`
INNER JOIN
`mgmx_sales_flat_invoice_comment`
AS
`a`
ON
a.parent_id = main_table.entity_id
This Query, on the other hand is working if I can remove some of the "things" in it like '`' so it will function normally.
Here's what will happen Step by Step.
*
*Upon running the query in Mysql it will return an error
1054 - Unknown column '(SELECT GROUP_CONCAT(comment SEPARATOR '----' )
FROM mgmx_sales_flat_invoice_comment a WHERE a.parent_id =
main_table.entity_id group by parent_id)' in 'field list'
if I remove the `` before and after the (SELECT statement) like the one below
SELECT `main_table`.*,
(SELECT
GROUP_CONCAT(comment SEPARATOR '----' )
FROM
mgmx_sales_flat_invoice_comment a
WHERE a.parent_id = main_table`.`entity_id
group by parent_id)
FROM `mgmx_sales_flat_invoice_grid`
AS `main_table`
INNER JOIN `mgmx_sales_flat_invoice_comment`
AS `a` ON a.parent_id = main_table.entity_id
It will show this error instead
right syntax to use near '.entity_id group by parent_id) FROM
mgmx_sales_flat_invoice_grid AS `main_ta' at line 1
because of this
WHERE a.parent_id = main_table`.`entity_id
how do I remove that `` and how do I group by the final $collection Query.
A: Here the separator ---- in GROUP_CONCAT function is creating an issue.
If you use a different separator like ==== then the issue will be resolved.
Like,
$stmp = "(SELECT GROUP_CONCAT(comment SEPARATOR '====' ) FROM mgmx_sales_flat_invoice_comment a WHERE a.parent_id = `main_table`.`entity_id` group by parent_id)";
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47119430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Abstract class properites does not work in typescript I have this abstract class:
export abstract class Builder {
static data: MyClass = {};
get data(): MyClass {
return Builder.data;
}
set data(value: MyClass) {
Builder.data = value;
}
static member1() {}
static member2() {}
...
}
I consume this class like so:
Builder.data = {...} however, it seems that getter and seetter does not make any effect.
In that case Builder.data referencing the static member.
Any ideas how to fix that?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69568244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Save instance layout in activities How I can implement part of layout which will beuse in three or four activities, but I want to save look this layout. I mean In first layout I add button to my part, In second Activity I will see my part with button. In second activity I add second button and in third activity I want to see both buttons, etc. I want to add this buttons in code, not xml. How I can do one instance layout for all activities which will be keep all changes added in previous activities?
A: In theory you could create the layout with all the buttons available - if they are only a few -, and hide the selectable ones with android:visibility="gone" in xml.
Later on you keep track of the selections in an internal Object or ArrayList, and change visibility for the selected buttons in each subsequent Activity's onCreate or onResume.
Another solution is to create an xml with the spare space for the additional buttons, and add them from code. In this case you have to keep track of all information about the added buttons in code, not just the states, but the theory is the same.
If you want to save the layout over application restarts as well, you will have to save that information yourself, Android does not have this built-in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14643299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does my dynamically allocated array not work? I have recently moved from Linux to Windows 10 for my OpenGL C++ projects, and the first time I do something with arrays on Windows, they suddenly don't seem to work anymore. Every time I try to create an array from a non-const variable that represents a size, the execution of the program does nothing (meaning no output to the console, but also no error message). It compiles fine. To understand what I mean, look at this code snippet:
#include <iostream>
int main()
{
int s = 10;
float* array = new float[s];
std::cout << *array;
delete[] array;
return 0;
}
It is perfectly legit, but when compiling it with MinGW on Windows and then running it, nothing happens. Yet, using the GCC compiler on Linux writes a 0 to the console, which is perfectly fine and logical, indicating that it is not the code that is flawed. Do you know what could cause this problem? It is really on Windows that I have encountered this behaviour for the first time. Both compilation commands are straight-forward:
g++ array-test.cpp -o array-test
Note that making s a const int fixes the issue, but I do want my arrays to be dynamically allocated, from user input.
I am using a relatively unspectacular text editor (Notepad++) and compile in the Windows PowerShell with MinGW. The supplied code replicates the behaviour on my machine, but I cannot guarantee that it will do so on others as well. Even example code from the internet creating an array with a non-const variable as size will not run.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66940299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add new line for the following string I am new to regex and I am trying to add new line for the following string pattern.
(request-target): put /api/v1/9e7336e2-ee96-406d-bba8-e75cf14b2a94/account/e15be91a-b63c-4b4b-ae3f-a0426ae98bcd/address/73844762-8305-4528-ac44-1f1024297abd/payment/041c5e65-0556-4df1-a504-6a31fa48fe64/domestic\nDate: 2018-01-31T14:16:50.259-06:00\nDigest: Ghjaioq+mFvjNOIkKZivIYa/khMz1siWw/zA502E+k0HzKIWhoXXYFeoFaLztXWBcQpcSjDqpTEx688OuU1x9A==
Expected output:
(request-target): put /api/v1/9e7336e2-ee96-406d-bba8-e75cf14b2a94/account/e15be91a-b63c-4b4b-ae3f-a0426ae98bcd/address/73844762-8305-4528-ac44-1f1024297abd/payment/041c5e65-0556-4df1-a504-6a31fa48fe64/domestic
Date: 2018-01-31T14:16:50.259-06:00
Digest: Ghjaioq+mFvjNOIkKZivIYa/khMz1siWw/zA502E+k0HzKIWhoXXYFeoFaLztXWBcQpcSjDqpTEx688OuU1x9A==
I did tried the combination of match and replace \n and nothing match.
Can anyone please help?
Update:
Adding final output when matching //n or ////n and replacing with \n
output:
(request-target): put /api/v1/9e7336e2-ee96-406d-bba8-e75cf14b2a94/account/e15be91a-b63c-4b4b-ae3f-a0426ae98bcd/address/73844762-8305-4528-ac44-1f1024297abd/payment/041c5e65-0556-4df1-a504-6a31fa48fe64/domesticDate: 2018-01-31T14:16:50.259-06:00Digest: Ghjaioq+mFvjNOIkKZivIYa/khMz1siWw/zA502E+k0HzKIWhoXXYFeoFaLztXWBcQpcSjDqpTEx688OuU1x9A==
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48670452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Animated material colors not working in three.js when exported from blender with collada I am trying to simulate a blinking light on an object, so I am animating the material color. I then export the blender model into three.js via the collada exporter.
To demonstrate the problem, I have created a model with a single cube on which I change the color from red to green and back to red. I also move the cube a little.
At frame 0, I make the cube red with no displacement:
At frame 12, I make it green and displace it a little:
When I play the animation within blender, I see the color change and the cube displace. However, when I export it with collada into three.js, the cube moves, but it stays one color (the color of the cube that was active at the time I exported it e.g it can be either red or green, but always one color). I have created a plunker demonstrating the problem. My collada code is based on the three.js collada pump example. Here is the code used to load the model:
factory.loadColladaModel = function () {
console.log(`now in loadColladaModel`);
var loader = new THREE.ColladaLoader();
loader.options.convertUpAxis = true;
var promise = new Promise( (resolve, reject) => {
loader.load( 'color_animation.dae', (collada) => {
console.log(`now in collada load closure`);
let model = collada.scene;
factory.scene.add(model);
factory.animations = collada.animations;
model.scale.x = model.scale.y = model.scale.z = 5.0;
for ( var i = 0; i < factory.animations.length; ++i ) {
var animation = factory.animations[ i ];
var kfAnimation = new THREE.KeyFrameAnimation( animation );
kfAnimation.timeScale = 1;
factory.kfAnimations.push( kfAnimation );
}
resolve('loaded');
})
})
return promise;
}
What do I do have to do in order to get three.js to animate the material (color) changes as well as the motion? I do see color entries under the 'animation' tag of the collada file, so I assume collada supports it. I saw this prior question where someone had to set morphTargets in order to get materials to work. Do I need to do something like this too? Is morphTargets only for motion, or is it for color too?
three.js r84
blender 2.78b
Many Thanks.
A: It basically looks like the three.js ColladaLoader simply does not support material animations (it only supports position and rotation animations). I determined this by looking at raw data structure returned by the collada loader. Note how Object 0, which corresponds to the position animation has sids (string ids) and keys etc. Object 1, which corresponds to the material animation, has no sids or keys. While the material animation data is in the raw collada file, the ColladaLoader parser is simply not reading it, thus no color animations.
Apparently, the Collada loader is "kind of deprecated" per mrdoob (as of 5/2016). There is a ColladaLoader2, which is supposed to be the next version of the ColladaLoader, but I tried that and it appears to not support any animations at all. I've been reading up on the collada loader and indeed it is an aging format and basically looks likes it's a dead end as far as future growth goes (?)
Unfortunately, I've tried the obj, json, and stl loaders and the collada loader is by far the best. I'm currently investigating the gltf format, which basically seems like the next generation of collada (e.g the new and improved version also from the Khronos group). I found this discussion very useful. Basically, a couple of years ago there was a three.js user who wrote his own ColladaLoader, but he has since abandoned Collada and now backs glTF.
Update: I tried the GLTFLoader and GLTF2Loader loaders, but unfortunately they are failing on a semi-complex scene (a scene with 20 objects and 310 faces). It looks like a promising format though. I just think that between a test exporter and test loaders, it's just not quite stable at the moment. I was almost able to get animation working with the format (not material animation though) when I tested with a simple cube.
Looks like I'll have to stay with Collada for now and just do material animations in javascript.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42993444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Comparing data in previous row using shift() function I am working with monthly Citi bike trip data that looks like this:
> head(data)
tripduration starttime stoptime start.station.id start.station.name end.station.id
1 732 2015-07-01 00:00:03 2015-07-01 00:12:16 489 10 Ave & W 28 St 368
2 322 2015-07-01 00:00:06 2015-07-01 00:05:29 304 Broadway & Battery Pl 3002
3 790 2015-07-01 00:00:17 2015-07-01 00:13:28 447 8 Ave & W 52 St 358
4 1228 2015-07-01 00:00:23 2015-07-01 00:20:51 490 8 Ave & W 33 St 250
5 1383 2015-07-01 00:00:44 2015-07-01 00:23:48 327 Vesey Pl & River Terrace 72
6 603 2015-07-01 00:01:00 2015-07-01 00:11:04 455 1 Ave & E 44 St 367
end.station.name bikeid usertype birth.year gender
1 Carmine St & 6 Ave 18669 Subscriber 1970 1
2 South End Ave & Liberty St 14618 Subscriber 1984 1
3 Christopher St & Greenwich St 18801 Subscriber 1992 1
4 Lafayette St & Jersey St 19137 Subscriber 1990 1
5 W 52 St & 11 Ave 15808 Subscriber 1988 1
6 E 53 St & Lexington Ave 17069 Subscriber 1953 1
Each trip has it's own unique record, and only for the month of July there are some 1,085,676 trips. The raw data in .csv format can be found here on the Citi Bike website. Normally, bikes start from the station where they ended on the previous trip. However, this is not always the case. Sometimes bikes will start at different station than where they ended, which indicates the bikes were "rebalanced" or moved by a truck from one station to the next to meet station demands. I want to filter out all of the "normal" trips and isolate all of the instances where the bikes started at a different station than where they ended (e.g. start.station.id is not equal to previous end.station.id.) The unique identifying factor of bikes is bikeid, and this must be used. Here is a subset of the month's data by one bikeid (the most frequently ridden bike):
head(onebike)
tripduration starttime stoptime start.station.id start.station.name
1952 691 2015-07-01 07:23:24 2015-07-01 07:34:56 161 LaGuardia Pl & W 3 St
2369 332 2015-07-01 07:38:49 2015-07-01 07:44:22 379 W 31 St & 7 Ave
3879 259 2015-07-01 08:14:34 2015-07-01 08:18:54 472 E 32 St & Park Ave
4310 1112 2015-07-01 08:22:53 2015-07-01 08:41:25 498 Broadway & W 32 St
5795 1509 2015-07-01 08:47:18 2015-07-01 09:12:27 345 W 13 St & 6 Ave
7857 1361 2015-07-01 09:23:50 2015-07-01 09:46:32 348 W Broadway & Spring St
end.station.id end.station.name bikeid usertype birth.year gender
1952 379 W 31 St & 7 Ave 22075 Subscriber 1985 1
2369 472 E 32 St & Park Ave 22075 Subscriber 1986 1
3879 498 Broadway & W 32 St 22075 Subscriber 1986 1
4310 345 W 13 St & 6 Ave 22075 Customer NA 0
5795 348 W Broadway & Spring St 22075 Customer NA 0
7857 386 Centre St & Worth St 22075 Customer NA 0
The task is now to select instances where the start.station.id of a row does not equal end.station.id of the previous row.
The result should contain the bikeid, the end.station.id, the start.station.id, and the time difference between when the bike was dropped off and picked up (indicating approximately when it was moved).
Is the best way to do this to use the shift() function?
How would one loop through every bike.id in the first dataset (there are about 7000) to reveal all of the hidden movements?
A: I am sure there are hundreds of ways to do this, but since the data is only around 100MB, a simple for loop is very capable and very flexible to modify and extend in this case, so here it is (done in seconds):
raw_data = read.csv("201511-citibike-tripdata.csv")
bikeid <-22075
onebike <- raw_data[ which(raw_data$bikeid== bikeid), ]
output <- data.frame("bikeid"= integer(0), "end.station.id"= integer(0), "start.station.id" = integer(0), "diff.time" = numeric(0))
for(i in 2:nrow(onebike)) {
if(onebike[i-1,"end.station.id"] != onebike[i,"start.station.id"]){
diff_time <- as.double(difftime(strptime(onebike[i-1,"stoptime"], "%m/%d/%Y %H:%M:%S"),
strptime(onebike[i,"starttime"], "%m/%d/%Y %H:%M:%S"),units = "mins"))
new_row <- c(bikeid, onebike[i-1,"end.station.id"], onebike[i,"start.station.id"], diff_time)
output[nrow(output) + 1,] = new_row
}
}
output
bikeid end.station.id start.station.id diff.time
1 22075 514 520 181.5667
2 22075 356 502 628.8833
Edit: This is to further answer the question in the comments.
It is an easy extension to include all the bikeids:
raw_data = read.csv("201511-citibike-tripdata.csv")
unique_id = unique(raw_data$bikeid)
#bikeid <-22075
output <- data.frame("bikeid"= integer(0), "end.station.id"= integer(0), "start.station.id" = integer(0), "diff.time" = numeric(0), "stoptime" = character(),"starttime" = character(), stringsAsFactors=FALSE)
for (bikeid in unique_id)
{
onebike <- raw_data[ which(raw_data$bikeid== bikeid), ]
if(nrow(onebike) >=2 ){
for(i in 2:nrow(onebike )) {
if(is.integer(onebike[i-1,"end.station.id"]) & is.integer(onebike[i,"start.station.id"]) &
onebike[i-1,"end.station.id"] != onebike[i,"start.station.id"]){
diff_time <- as.double(difftime(strptime(onebike[i,"starttime"], "%m/%d/%Y %H:%M:%S"),
strptime(onebike[i-1,"stoptime"], "%m/%d/%Y %H:%M:%S")
,units = "mins"))
new_row <- c(bikeid, onebike[i-1,"end.station.id"], onebike[i,"start.station.id"], diff_time, as.character(onebike[i-1,"stoptime"]), as.character(onebike[i,"starttime"]))
output[nrow(output) + 1,] = new_row
}
}
}
}
dim(output)
[1] 32589 6
head(output)
bikeid end.station.id start.station.id diff.time stoptime starttime
1 22545 520 529 24.8166666666667 11/2/2015 08:38:22 11/2/2015 09:03:11
2 22545 520 517 537.483333333333 11/2/2015 09:39:19 11/2/2015 18:36:48
3 22545 2004 3230 563.066666666667 11/2/2015 22:06:27 11/3/2015 07:29:31
4 22545 296 3236 471.783333333333 11/4/2015 23:40:29 11/5/2015 07:32:16
5 22545 520 449 43.4166666666667 11/9/2015 08:24:06 11/9/2015 09:07:31
6 22545 359 519 30.7166666666667 11/9/2015 09:14:46 11/9/2015 09:45:29
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34485362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Uncaught ReferenceError: describe is not defined cors I am building a phonegap app which has a cors.js with the following code:
describe('cors', function () {
it('passes control to next middleware', function (done) {
// arrange
var req, res, next;
req = fakeRequest();
res = fakeResponse();
next = function () {
done();
};
The error I am getting is:
Uncaught ReferenceError: describe is not defined
Where do I set the reference to describe?
A: When I had this problem, i solved it by switching the order of the libraries.
<script src="/bower_components/angular/angular.min.js"></script>
...
<script src="/bower_components/jasmine/lib/jasmine-core/jasmine.js"></script>
<script src="/bower_components/jasmine/lib/jasmine-core/jasmine-html.js"></script>
<script src="/bower_components/jasmine/lib/jasmine-core/boot.js"></script>
<script src="/bower_components/angular-mocks/angular-mocks.js"></script>
... then the tests e.g.
<script src="/js/lib/sync/test/local-test.js"></script>
Also I import all of them at the end of the <body>.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30773468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tableau Filtering on ocurence of a String I have a Field in my Column that is filed with a String that can have a multiple occurence of the same word. Now what i want to do is to Filter this Column so that a certain Word mus occure and that only the rows show up where another word don't ocure more than one time. Here is what i get so far:
CONTAINS([Column1], "Santiego") AND COUNT(CONTAINS([Column1], "25")) < 2
The error tells me I canot mix Agregat and Non Agregat Arguments.
Is there any possibility to do this kind of filtering?
A: I found a solution,
In the Filter function You have to use just the Column you need and Filter with this Formula:
COUNT(CONTAINS([Column1], "25")) < 2
After that you just create a new calculation that you put in the Filter, the calculation uses then this Formula:
CONTAINS([Column1], "Santiego")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46171322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the difference between the pair of functions floor()/ceil() and min()/max()? I would say all programming languages have functions with these names to choose the lesser or greater of two values:
*
*min() & max()
*floor() & ceil() / ceiling()
And some languages have both. JavaScript I believe is one example.
I've always been a bit fuzzy on the difference between the former pair and the latter pair. I have a vague impression that min/max are more simplistic and floor/ceiling are more mathematical, but that's not much to go on.
Oddly I can't find this discussed anywhere on StackOverflow or the Internet generally by searching Google. So is there some best practices or rules of thumb to decide which of these functions to use when your programming language offers both?
A: In Javascript:
*
*Floor Round a number downward to its nearest integer.
*Ceil Round a number upward to its nearest integer.
*Round Round a number to the nearest integer.
function ceil() {
var d = Math.ceil(5.1);
var x = d + "<br>";
document.getElementById("ceil").innerHTML = x;
}
function floor() {
var d = Math.floor(5.1);
var x = d + "<br>";
document.getElementById("floor").innerHTML = x;
}
function round() {
var d = Math.round(5.1);
var x = d + "<br>";
document.getElementById("round").innerHTML = x;
}
<!DOCTYPE html>
<html>
<body>
<p>Click the different buttons to understand the concept of Ceil, Floor and Round</p>
<button onclick="ceil()">Ceil 5.1</button>
<p id="ceil"></p>
<button onclick="floor()">Floor 5.1</button>
<p id="floor"></p>
<button onclick="round()">Round 5.1</button>
<p id="round"></p>
</body>
</html>
A: I realise this post is old, but an important distinction is being overlooked.
The function round() rounds towards or away from zero, while the functions ceil() and floor() round toward positive infinity and negative infinity;
This is important if dealing with both positive and negative numbers. i.e.
round(4.900000) = 5.000000
ceil(4.900000) = 5.000000
floor(4.900000) = 4.000000
round(4.100000) = 4.000000
ceil(4.100000) = 5.000000
floor(4.100000) = 4.000000
round(-4.100000) = -4.000000
ceil(-4.100000) = -4.000000
floor(-4.100000) = -5.000000
round(-4.900000) = -5.000000
ceil(-4.900000) = -4.000000
floor(-4.900000) = -5.000000
A: min() and max() return the smaller or larger of 2 values, some might do more than 2 values, as in
min(3, 5); returns 3.
floor() and ceiling() truncate a double into an integer as in
floor(5.3); returns 5.
A: Not sure I understand your question, see for example:
a = 1.7
b = 2.8
min(a,b) = 1.7 (returns the minimum of a and b)
max(a,b) = 2.8 (returns the maximum of a and b)
floor(a) = 1 (rounds towards 0)
floor(b) = 2 (rounds towards 0)
ceil(a) = 2 (rounds up)
ceil(b) = 3 (rounds up)
A: This is apples vs. oranges. In most languages/APIs, min/max take two (or more) inputs, and return the smallest/biggest. floor/ceil take one argument, and round it down or up to the nearest integer.
A: To my knowledge max and min are used on a collection, say an array of numbers. Floor and ceiling are used for single numbers. For example:
min(1, 2, 3, 4) => 1
max(1, 2, 3, 4) => 4
floor(3.5) => 3
ceiling(3.5) => 4
A: min(1, 2) == 1
max(1, 2) == 2
floor(3.9) == 3
round(3.9) == 4
ceil(3.1) == 4
round(3.1) == 3
trunc, as in (int)(3.xxx) = 3 (no matter what xxx is)
On the definition:
floor is the greatest integer less than n.
ceil is the smallest integer greater than n.
A: Please consider below for difference between Math.floor(), Math.round() and Math.ceil() in javascript:
1- Math.floor(x) /if x=0.99 convert to = x=0/ (Returns x rounded down to its nearest integer)
2- Math.ceil(x) /if x<0.1 convert to x=1/(Returns x rounded up to its nearest integer)
3-1- Mathh.round(x) / if x<0.5 convert to x=0/
3-2- Mathh.round(x) / if 0.5<=x<1 convert to x=1/
(Returns x rounded to its nearest integer)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9724960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Unexpected token "(" JavaScript I've checked all of my parentheses and it looks okay to me, what's the deal? (I'm doing the Javascript course at Codecademy) [random text here because stackoverflow wants me to have a better ratio between text and code]
function StaffMember(name,discountPercent){
this.name = name;
this.discountPercent = discountPercent;
}
var sally = new StaffMember("Sally",5);
var bob = new StaffMember("Bob",10);
// Create yourself again as 'me' with a staff discount of 20%
var me = new StaffMember("Axel", 20);
var cashRegister = {
total:0,
lastTransactionAmount: 0,
add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item,quantity){
switch (item){
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
// Create a new method applyStaffDiscount here
applyStaffDiscount(employee){
this.total -= (this.total * (employee.discountpercent/100));
}
};
cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',3);
// Apply your staff discount by passing the 'me' object
// to applyStaffDiscount
cashRegister.applyStaffDiscount(me);
// Show the total bill
console.log('Your bill is '+cashRegister.total.toFixed(2));
A: Well, it's not okay, you have syntax errors in your literal where you're creating the applyStaffDiscount property
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
applyStaffDiscount(employee){
this.total -= (this.total * (employee.discountpercent/100));
}
Let's assume you where really trying to create a function, as you're trying to pass arguments and have parenthesis etc
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
applyStaffDiscount : function(employee){
this.total -= (this.total * (employee.discountpercent/100));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23274674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Twig doesn't extend template My problem is next:
I have base.html.twig placed in view folder (root)
{# app/Resources/views/base.html.twig #}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{% block title %}Test Application{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block body %}{% endblock %}
</div>
</body>
</html>
and index.html.twig in Blog directory (views/Blog):
{% extends '::base.html.twig' %}
{% block title %}
{{ parent() }}
{% endblock %}
{% block sidebar %}
{{ parent() }}
{% endblock %}
{% block body %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
My problem is next:
When I render and return that template it is shown just as index.html.twig and it doesn't use any part from the base template. Even I {{ parent() }} doesn't work (is not showing anything). Please help!
EDIT: it shows just articles part
A: Hah... I made it work... Simply changed ::base.html.twig with AcmeHelloBundle::base.html.twig ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19328423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wrong moving speed for sprite animation I'm using Math.atan2 method to detect two different points from point a to point b.
But my sprite animation will be moving at a super fast speed when it detect the other point. Is it possible to reduce the moving speed of my sprite animation?
So after you press on the add fish button, a fish sprite animation will be moving on the canvas. Then you can click on any part of the canvas, and the fish sprite animation will be moving towards it. At the same time you will be seeing the super fast moving speed sprite.
A: You'd have to change the speed mechanism of the fish, By lowering the number you multiply with
changing
this.speedX= (tx/dist) * 1
into
this.speedX=(tx/dist) * 0.1
should reduce the speed by 10 times
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25113110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it mandatory to use the isAuthorized() method in Cakephp? I am using cakephp 2.6.9. and I'm trying to log in using auth, but it shows:
$controller does not implement an isAuthorized() method
Is it mandatory to use the isAuthorized() method in cakephp?
A: If you're using the Auth component with the ControllerAuthorize authorization adapter yes. If you want to use something else use one of the other adapters or write your own.
See the documentation for a basic introduction on how the auth component works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31147695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Could not load file or assembly 'System.Data.Entity 4.0.0.0 in azure function referencing a class library Getting this error:
System.IO.FileNotFoundException HResult=0x80070002 Message=Could
not load file or assembly 'System.Data.Entity, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot
find the file specified. Source=... StackTrace: at ....
I create an azure function referencing a class library.
I checked on the class library, System.Data.Entity is being referenced.
But when I run the azure function, I get this error.
What might be wrong here?
The Azure function is on .Net Core 3.1.
The referenced class library (as a project so I can debug it) is on .Net Framework 4.7.2
Is a class library of .net Framework 4.7.2 supported when referenced on .net Core 3.1 (why its not loading System.Data.Entity)?
A: From this post we can know:
.NET Core doesn't support inclusion of .NET Framework libraries. Period. However, .NET Core supports .NET Standard, and since .NET Framework also implements .NET Standard, Microsoft made a special exception in the compiler to allow you include .NET Framework libraries, with the caveat that they may not actually function at all or totally. You get a warning to this effect when you include a .NET Framework library in a .NET Core project, and it's on you to ensure that the library works correctly end-to-end.
Because .NET Core supports .NET Standard library, you can use the package of .NET Standard. This post is similar to your problem, his solution may inspire you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63351139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Automated CRUD in Java using Swing JTable I used this code for displaying a database table in a JTable but when I change a value it is not saved to database. I'm using IntelliJIdea. I want to know if there is a general package to implement this kind of binding with database table? I've seen that netbeans can do sth similar. But I'd like to have an IDE independent method for this problem.
By the way, if Swing can't do it, is there a component in JavaFX which would be able to do such a thing?
A: for javaFX there is a library with write back support DataFX2.0
Sample Examples can be found here
If you need any further help on datafx then you can post in datafx google groups Link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20830453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Media contents, Woocommerce Login Forms becomes unavailable when a certain line of code is included in functions.php Happy to be here and elated to have interactions with you.
I have a challenge I need help with to determine the causative issue. I am creating a wordpress theme for a woocommerce store, as a first timer. All is going well, although challenging and tasking (I like it like that).
In the cause of the development, I observed that I could not access the media folder or the login section of the theme when put oline (accessed on liveserver), but on the local development server all works fine.
After much troubleshooting by checking all codes in the different file, by excluding and including diffrent lines of codes, I discovered the trigger is coming from a section of the functions.php file. Find below the codes therein, with the pain-point highlighted at 7.2. :
<?php
/**
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++
* + THEME FUNCTIONS & WIDGETS +
* +++++++++++++++++++++++++++++++++++++++++++++++++++
*
* */
/********************************************************************************************
* 1.0. REGISTER STYLESHEETS AND SCRIPTS **********************************************************************************************/
// 1.1. register and enqueue stylesheets
function load_stylesheets()
{
if(!is_admin()){
wp_register_style('stylesheet', get_template_directory_uri() . '/style.css', '', 1, 'all');
wp_enqueue_style('stylesheet');
wp_register_style('custom', get_template_directory_uri() . '/assets/css/app.css?asasggfghf=asfsfrrdfghghfgdgsdg', '', 1, 'all');
wp_enqueue_style('custom');
wp_register_style('woostyles', get_template_directory_uri() . '/assets/css/woocommerce/woocommerce.css?asdadsfggdgfdfd=fgfghghgjjhj', '', 1, 'all');
wp_enqueue_style('woostyles');
wp_register_style('woolayout', get_template_directory_uri() . '/assets/css/woocommerce/woocommerce-layout.css?asfdffgd=sdsfggf', '', 1, 'all');
wp_enqueue_style('woolayout');
wp_register_style('fontawesome', get_template_directory_uri() . '/assets/fontawesome/css/all.min.css', '', 1, 'all');
wp_enqueue_style('fontawesome');
}
}
add_action('wp_enqueue_scripts', 'load_stylesheets');
// 1.2. register and enqueue javascripts
function load_javascript()
{
if(!is_admin()){
wp_enqueue_script('jquery');
wp_register_script('custom', get_template_directory_uri() . '/assets/js/app.js?adddghhjkjk', 'jQuery', 1, true);
wp_enqueue_script('custom');
wp_register_script('form-validate', get_template_directory_uri() . '/assets/js/jquery.validate.min.js', 'jQuery', 1, true);
wp_enqueue_script('form-validate');
}
}
add_action('wp_enqueue_scripts', 'load_javascript');
/********************************************************************************************
* 2.0. THEME'S SITE AND CUSTOMISATIONS **********************************************************************************************/
//2.1. Activates Support for Theme's Custom Logo Setup
function config_theme_custom_logo(){
// Custom image size created somewhere in your code.
add_image_size( 'custom-image-size' , '' , '' , true );
$defaults = array(
'height' => 'custom-image-size',
'width' => 'custom-image-size',
'flex-height' => true,
'flex-width' => true,
'class' => 'logo',
'header-text' => array( 'site-title', 'site-description' ),
'unlink-homepage-logo' => false,
);
add_theme_support( 'custom-logo', $defaults );
}
add_action( 'after_setup_theme' , 'config_theme_custom_logo' );
//2.2. Activate Support for Theme's Site Logo and Name Customization Setup
function theme_site_logo(){
if ( has_custom_logo() ) {
$logo = wp_get_attachment_image_src( get_theme_mod( 'custom_logo' ) , 'full' );
echo '<a class="site-logo-link" href="' . get_site_url() . '" >';
echo '<img class="img-fluid logo" src="' . esc_url( $logo[0] ) . '" width="' . $logo[1] . '" height="' . $logo[2] . '" alt="' . get_bloginfo( 'name' ) . '">';
echo "</a>";
}
else {
echo '<a href="' . get_site_url() . '" class="site-name-link" >';
echo '<h2>' . get_bloginfo( 'name' ) . '</h2>';
echo '</a>';
echo '<span class="site-description" >' . get_bloginfo( 'description' ) . '</span>';
}
}
/********************************************************************************************
* 3.0. ACTIVATES THEME'S WORDPRESS SUPPORT FEATURES MORE **********************************************************************************************/
function themes_support_features()
{
// 3.1. Activates Supports for Custom Menu
add_theme_support('menus');
// 3.1.1. Register's Location for 4 Navigation Menus
$locations = array(
'primary' => __( 'Primary Menu', 'devtheme' ),
'expanded' => __( 'Expanded Menu', 'devtheme' ),
'mobile' => __( 'Mobile Menu', 'devtheme' ),
'footer' => __( 'Footer Menu', 'devtheme' ),
'social' => __( 'Social Menu', 'devtheme' ),
);
// 3.1.2. Register's Location for 4 Navigation Menus
register_nav_menus( $locations );
//3.2. HTML5 Search: activate Theme's search form
add_theme_support('html5', array('search-form'));
//3.3. HTML5 Search: activate Theme's search form
add_theme_support('post-thumbnails');
}
add_action('init', 'themes_support_features');
/********************************************************************************************
* 4.0. LOAD THEME'S CUSTOM FUNCTIONS AND MORE **********************************************************************************************/
//4. Activate theme's support for Walker Class
require get_template_directory() . '/inc/walkerClasschild.php';
require get_template_directory() . '/inc/adhoc-functions.php';
/********************************************************************************************
* 5.0. LOAD THEME'S WIDGETS AND MORE **********************************************************************************************/
//** 5.1. */
require_once get_template_directory() . '/lib/theme-widgets.php';
require get_template_directory() . '/inc/allowSVG.php';
//* 5.2. Change Footer Widget Menu Properties
function custom_nav_args( $args ) {
return array_merge( $args, array(
'container_class' => 'widget-content',
'menu_class' => '',
'walker' => '',
// another setting go here ...
) );
}
add_filter( 'widget_nav_menu_args', 'custom_nav_args' );
/****************************************************************
* 8.0. Support using shortcodes in Widgets *
****************************************************************/
add_filter( 'widget_text', 'shortcode_unautop' );
add_filter( 'widget_text', 'do_shortcode' );
/********************************************************************************************
* 6.0. ACTIVATES THEME'S WORDPRESS CUSTOMIZER FEATURES & MORE **********************************************************************************************/
/**
* Do not include twice the file below.
*/
if ( file_exists( get_template_directory() . '/inc/api-customizer.php' ) ) {
require get_template_directory() . '/inc/api-customizer.php';
}
/********************************************************************************************
* 7.0. ACTIVATES WOOCOMMERCE & FEATURES TO THE THEME * ********************************************************************************************/
//**7.1. Theme Support for WooCommerce */
//**7.1.1. Adds constant that returns true if Woocommerce is Active */
define( 'WPEX_WOOCOMMERCE_ACTIVE', class_exists( 'WooCommerce' ) );
//**7.1.2. Check if Woocommerce is Active */
if ( WPEX_WOOCOMMERCE_ACTIVE ){
add_action('after_setup_theme', function(){
add_theme_support('woocommerce');
});
}
**
//** 7.2. WooCommerce Hooks */
if (class_exists('WooCommerce') && file_exists( get_template_directory() . '/inc/woocommerce-hooks.php' ) ) {
require get_template_directory() . '/inc/woocommerce-hooks.php';
}
**
Once the code section 7.2. is added (i.e. code to link the file containing hooks for woocommerce plugin) the malfunction shows face, even when the file contains no codes. Once that section is taken out, everything then works fine.
Can anyone help to determine what it is I have included in top sections of the functions codes?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75276658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SVG Symbol animate not working with Safari I'm currently struggling with a SVG.
Right now, I'm trying to display an animated SVG in my webpage. In order to do it, I just put the svg code at the end of the body, and used the html tag "use" to embed my SVG (which contains a symbol).
Here is my SVG code :
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient x1="100%" y1="0%" x2="0%" y2="100%" id="linearGradient">
<stop offset="0%" stop-color="#7A5FFF">
<animate attributeName="stop-color" values="#05FFA3; #45CAFC; #7873F5; #FC6262; #05FFA3;" dur="10s" repeatCount="indefinite"></animate>
</stop>
<stop offset="100%" stop-color="#01FF89">
<animate attributeName="stop-color" values="#2096FF; #303F9F; #FF6EC4; #FFD86F; #2096FF;" dur="10s" repeatCount="indefinite"></animate>
</stop>
</linearGradient>
</defs>
<symbol x="0px" y="0px" width="308px" height="308px" viewBox="0 0 308 308" id="svg-logo">
<circle cx="150" cy="150" r="150" fill="url(#linearGradient)" />
</symbol>
</svg>
And here is the way I embed it in my page :
<svg class="star">
<use xlink:href="#svg-logo">
</svg>
It works fine, except on safari. The linear gradient animation is completely broken, and looks like this :
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46655103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: APK which I developed used to work fine earlier, but suddenly stopped working with "App not installed" error I was working on an android app to push FCM notifications.
Now this debug app was getting installed on my mobile properly, however since am using my office laptop with intel-vt (HAXM) disabled I could not use the emulator and since the USB is also disabled, I could not use the ADB to side load.
So I was left with building the APK and manually side loading it on my mobile every time I made even a small change.(Redmi Note 5 Pro).
Now this app was working fine till the last time I uninstalled it.After which I tried to install the new version which failed with error "App not installed". Then I went on to install the older version thinking I might have screwed up something in the latest version, however all the older version APKs which were working absolutely fine earlier (at least they were installing i mean) stopped getting installed with the same error.
I have already uninstalled the older version and have double checked from system and there is no earlier APK existing on my mobile.
This is driving me crazy and has put a complete halt on my work as this is the only mobile I have. And yes I have tried restarting my mobile, I have even disabled MIUI optimizations from developers menu.
PS - I am an extreme noob at Android and have recently started with Android development so please forgive me if my question sounds very silly.
Appreciate any help I can get on this.
A: Please follow the following steps:
*
*Go to Settings -> Permissions -> Install via USB: Uncheck your App if
it's listed.
*Go to Settings -> Additional Settings -> Privacy: Check the Unknown
Sources option.
*Finally go to Settings -> Additional Settings -> Developer options:
Check the Install via USB option.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53768480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send text to an input element within a webpage using Selenium Python I'm trying to learn selenium and I want to fill out a form and copying some tutorial . In this form there a text input with this code :
<input required="" autocomplete="off" placeholder="First Name" type="text" id="firstName" class=" mr-sm-2 form-control">
Following the tutorial this code should do it :
from selenium import webdriver as w
d=w.Chrome(executable_path="C:\\chromedriver.exe")
d.get("https://demoqa.com/automation-practice-form")
try :
d.find_element_by_id('firstName').send_keys("TEST")
except:
print('cant identify')
d.quit()
I think the problem is the find element syntax anyways what is the problem ?
A: d.find_element("xpath",'//*[@id="firstName"]').send_keys("amine")
d.find_element("id","lastName").send_keys("wannes")
A: To send a character sequence to the <input> field you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
*
*Using CSS_SELECTOR:
driver.get('https://demoqa.com/automation-practice-form')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#firstName"))).send_keys("hamdi")
*Using XPATH:
driver.get('https://demoqa.com/automation-practice-form')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='firstName']"))).send_keys("hamdi")
*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
*Browser Snapshot:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73008411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Can we add extra hidden tag in the surefire report Currently generating surefire report with below details in output.xml
<testcase name="ExchangeHostInformation" classname="adm.exchange.PreUpgradeExchangeTest" time="0.716">
Is it possible to add one more extra proeprties in the same tag. My requirement is add one more tag for feature.
Can anyone give the right direction ?
Tried using custom maven plugin but not able to get existing report information
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74472626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Helicon ISAPI rewrite I'd like to add cache and expires headers for all my .js files because I'm not able to do it on my server. I'm using IIS. How might I do this?
A: Consider using Helicon Ape mod_headers module. But note that it works only for IIS7 and higher.
A: Are you saying you don't have access to administer the server? If you can access the IIS management console, you can set these headers directly through the UI:
http://www.webpaths.com/archives/software/microsoft/iis/2009/02/05/how-to-add-an-expires-header-in-iis.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8083177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Verify MenuItem title in test In my activity test I need to verify that a menu item has certain title.
I can get it by ID but it returns a view.
final View menuItem = (View) mActivity.findViewById(R.id.do_it);
But how can I get the title from this view then?
Note: I need to do it in ActivityInstrumentationTestCase2 test.
Update
I am hoping to find a way to get menu item's title in my test case without writing any additional code in activity, like storing menu in a variable.
A: Use getTitle():
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.<manuLayout>, menu);
MenuItem menuItem = menu.findItem(R.id.do_it);
String title = menuItem.getTitle();
return true;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23452766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RubyGem Environment incorrect (gem env) So I'm following a book and installed GIT, CURL, rvm, RubyGems, and ruby.
When I run gem env, the variables incorrect... my home is "/home/wegener" NOT "/home/wegejos" ... I have no clue where or how it got the incorrect home world... I used rvm to install RubyGems and Ruby.
[~]$ gem env
RubyGems Environment:
- RUBYGEMS VERSION: 1.8.24
- RUBY VERSION: 1.9.3 (2012-04-20 patchlevel 194) [x86_64-linux]
- INSTALLATION DIRECTORY: /home/wegejos/ruby/gems
- RUBY EXECUTABLE: /home/wegener/.rvm/rubies/ruby-1.9.3-p194/bin/ruby
- EXECUTABLE DIRECTORY: /home/wegejos/ruby/gems/bin
- RUBYGEMS PLATFORMS:
- ruby
- x86_64-linux
- GEM PATHS:
- /home/wegejos/ruby/gems
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :benchmark => false
- :backtrace => false
- :bulk_threshold => 1000
- "gem" => "--remote --gen-rdoc --run-tests"
- "gemhome" => "/home/wegejos/ruby/gems"
- "gempath" => []
- "rdoc" => "--inline-source --line-numbers"
- REMOTE SOURCES:
- http://rubygems.org/
.
[~]$ env
reinstall_flag=1
rvm_bin_path=/home/wegener/.rvm/bin
HOSTNAME=ren.renegew.com
GEM_HOME=/home/wegener/.rvm/gems/ruby-1.9.3-p194
TERM=xterm
SHELL=/bin/bash
HISTSIZE=1000
IRBRC=/home/wegener/.rvm/rubies/ruby-1.9.3-p194/.irbrc
SSH_CLIENT=24.8.185.82 51882 22
PERL5LIB=/home/wegener/perl5/lib/perl5/x86_64-linux:/home/wegener/perl5/lib/perl5
MY_RUBY_HOME=/home/wegener/.rvm/rubies/ruby-1.9.3-p194
PERL_MB_OPT=--install_base /home/wegener/perl5
SSH_TTY=/dev/pts/1
USER=wegener
LS_COLORS=no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.flac=01;35:*.mp3=01;35:*.mpc=01;35:*.ogg=01;35:*.wav=01;35:
__array_start=0
rvm_path=/home/wegener/.rvm
escape_flag=1
rvm_prefix=/home/wegener
MAIL=/var/spool/mail/wegener
PATH=/home/wegener/.rvm/gems/ruby-1.9.3-p194/bin:/home/wegener/.rvm/gems/ruby-1.9.3-p194@global/bin:/home/wegener/.rvm/rubies/ruby-1.9.3-p194/bin:/home/wegener/.rvm/bin:/usr/local/jdk/bin:/home/wegener/perl5/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/wegener/bin
INPUTRC=/etc/inputrc
PWD=/home/wegener
JAVA_HOME=/usr/local/jdk
uninstall_flag=1
EDITOR=pico
LANG=en_US.UTF-8
_second=1
rvm_version=1.13.6 (stable)
SHLVL=1
HOME=/home/wegener
LS_OPTIONS=--color=tty -F -a -b -T 0
PERL_LOCAL_LIB_ROOT=/home/wegener/perl5
_first=0
LOGNAME=wegener
VISUAL=pico
CVS_RSH=ssh
GEM_PATH=/home/wegener/.rvm/gems/ruby-1.9.3-p194:/home/wegener/.rvm/gems/ruby-1.9.3-p194@global
CLASSPATH=.:/usr/local/jdk/lib/classes.zip
SSH_CONNECTION=24.8.185.82 51882 96.125.160.242 22
LESSOPEN=|/usr/bin/lesspipe.sh %s
PROMPT_COMMAND=echo -ne "\033]0;${PWD/#$HOME/~}\007"
install_flag=1
RUBY_VERSION=ruby-1.9.3-p194
PERL_MM_OPT=INSTALL_BASE=/home/wegener/perl5
G_BROKEN_FILENAMES=1
_=/bin/env
A: I found it! It was hidden in some file at /home/wegener/.gemrc ... I have no clue why it was set to wegejos or where that even came from.. there is not even a /home/wegejos/ I changed it to /home/wegener/ and now it's working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10667369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Basic RegExp examples in Javascript Can any one give the perfect regular expression for
1. US date format (mm/dd/yyyy).
2. Alpha Numerics.
3. Alpha Numerics with spaces.
4. age betwenn 15-100.
in java script. i have this Regex.
/^[0-9a-zA-Z]+$/ (alphanumeric that doesnot allow spaces)
/^[0-9]+$/ ( for age but not getting below 100)
/^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d+$/; (US date format)
Thanks
A: I think http://regexpal.com/ is a very good resource to learn regexp in general. Combine this with the mozilla docs: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
For 4, you are better of parsing the string as a number with parseInt or parseFloat and then comparing them with an if.
A: *
*I'm guessing you dont want the brackets (0[1-9]|1[0-2])/(0[1-9]|1[0-9]|2[0-9]|3[01])/[0-9]{4}
Note this doesn't validate that the number of days is valid in that month
*
*[a-zA-Z0-9]+?
*[a-zA-Z0-9\s]+?
*I wouldn't use regex for this but anyway (1[5-9]|[2-9][0-9]|100)
for these you may need to add the bol an eol chars depending on where your input is coming from (as in is there other content in the line).
Tested using regexpal
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7158307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Object being freed but dealloc not called At some point in my app I remove a view controller (let's call it A) from its parent view controller (let's call it B). And even though A is not referenced anymore, its dealloc method is not called.
I checked with instruments, A is really being freed. The number of living objects (of class A) is 0.
NSZombie is not enabled, I saw that it could interfere with dealloc calls.
The only moment the dealloc method is called, is when the view controller B is deallocated. At that moment, the stack trace is like that :
#0 0x0001ac78 in -[MyViewController dealloc] <-- This is A
#1 0x021061bf in _objc_deallocOnMainThreadHelper ()
#2 0x029f34d0 in _dispatch_client_callout ()
#3 0x029e1726 in _dispatch_main_queue_callback_4CF ()
#4 0x0274443e in __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ ()
#5 0x026855cb in __CFRunLoopRun ()
#6 0x026849d3 in CFRunLoopRunSpecific ()
#7 0x026847eb in CFRunLoopRunInMode ()
#8 0x046095ee in GSEventRunModal ()
#9 0x0460942b in GSEventRun ()
#10 0x00db4f9b in UIApplicationMain ()
#11 0x00028ea2 in main at /../main.m:17
I am not sure how the dealloc is triggered
Any idea what can be happening here?
-- EDIT
I create the view controller A with a class method :
+ (instancetype)viewController
{
return [[MyViewController alloc] init];
}
The weird thing is that when I replace the call to this class method with [[MyViewController alloc] init] everything works as expected. I don't know what's happening. Any idea?
A: I finally found what was going on.
The view controller that was not being dealloc was created through a class method, for example :
+ (instancetype) createMyViewController.
This kind of methods return autorelease objects.
My only guess is that the autorelease pool is drained way too late in my case. Adding an @autoreleasepool {} block around the appropriate code fixed everything.
A: Check out these view controller lifecycle methods. One of them is probably the right place for the code you have in dealloc, and you can count on them being called at the times stated. Dealloc should only be used for memory cleanup, e.g. free.
- (void)viewWillDisappear:(BOOL)animated
- (void)viewDidDisappear:(BOOL)animated
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25408225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Store canvas coordinates to local storage using angular.js I want to store drawing canvas coordinates to local storage using angular.js i got the coordinates but can"t able to push values to local storage.
getting values from this
draw(lastX, lastY, currentX, currentY);
and to store value to local storage
app.controller('app', function ($scope, $http, $localStorage) {
// Set a default
$scope.$storage = $localStorage.$default({
"lines": []
});
$scope.cloneItem = function () {
$scope.$storage.lines.push({
"lastX":lastX ,
"lastY": lastY,
"currentX": currentX,
"currentY": currentY
});
}
});
i can"t able to get the values lastX lastY currentX currentY
Plunker Demo
A: Plunker did not work for me, lastX variable is undefined when I click the button. But I copy pasted code and I put values manually and seem that it works, so I think the problem is that you should check if variable is defined before store them.
Also, you need init lines in localStorage before setting its default value, or will throw an error later trying to store in an undefined value.
http://embed.plnkr.co/kbrRd2fYlL3oW07iI8Hm/
A: setup you variables at scope
app.controller('app', function($scope, $http, $localStorage) {
// Set a default
$scope.$storage = $localStorage.$default({
"lines": []
});
$scope.cloneItem = function() {
$scope.$storage.lines.push({
"lastX": $scope.lastX,
"lastY": $scope.lastY,
"currentX": $scope.currentX,
"currentY": $scope.currentY
});
alert('$scope.lastX11111 -' + $scope.lastX)
}
});
to
app.directive("drawing", function() {
return {
restrict: "A",
link: function(scope, element) {
var ctx = element[0].getContext('2d');
// variable that decides if something should be drawn on mousemove
var drawing = false;
element.bind('mousedown', function(event) {
if (event.offsetX !== undefined) {
scope.lastX = event.offsetX;
scope.lastY = event.offsetY;
} else {
scope.lastX = event.layerX - event.currentTarget.offsetLeft;
scope.lastY = event.layerY - event.currentTarget.offsetTop;
}
// begins new line
ctx.beginPath();
drawing = true;
});
element.bind('mousemove', function(event) {
if (drawing) {
// get current mouse position
if (event.offsetX !== undefined) {
scope.currentX = event.offsetX;
scope.currentY = event.offsetY;
} else {
scope.currentX = event.layerX - event.currentTarget.offsetLeft;
scope.currentY = event.layerY - event.currentTarget.offsetTop;
}
draw(scope.lastX, scope.lastY, scope.currentX, scope.currentY);
// console.log(lastX, lastY, currentX, currentY);
// set current coordinates to last one
scope.lastX = scope.currentX;
// console.log(lastX, lastY, currentX, currentY);
scope.lastY = scope.currentY;
}
});
element.bind('mouseup', function(event) {
// stop drawing
drawing = false;
});
// canvas reset
function reset() {
element[0].width = element[0].width;
}
function draw(lX, lY, cX, cY) {
// line from
ctx.moveTo(lX, lY);
// to
ctx.lineTo(cX, cY);
// color
ctx.strokeStyle = "#4bf";
// draw it
ctx.stroke();
}
}
};
});
http://plnkr.co/edit/Qcqua0gjoAfya6xkQFiX?p=preview
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34992724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to calculate number of years individuals exceeded a value and display said years I have the following dataset:
## ID cumulative sector meters DOB
## 1 20100 41.75948 H38 6400 1979-08-24
## 2 20101 35.16874 B01 1600 1980-05-05
## 3 20102 20.60899 H04 1600 1979-03-17
## 4 20103 38.72266 c("B09", "B37") c(3200, 8000) c("1981-11-30", "1981-11-30")
## 5 20104 38.72266 c("B09", "B37") c(3200, 8000) c("1978-09-01", "1978-09-01")
## 6 20105 116.88668 c("B09", "B09") c(3200, 3200) c("1980-12-03", "1980-12-03")
## Oct Res_FROM Res_TO
## 1 W 1979-08-15 1991-05-15
## 2 NW 1980-05-15 1991-04-15
## 3 SW 1972-06-15 1979-08-15
## 4 c("NE", "N") c("1982-01-15", "1984-01-15") c("1984-01-15", "1986-04-15")
## 5 c("NE", "N") c("1982-01-15", "1984-01-15") c("1984-01-15", "1986-04-15")
## 6 c("NE", "NE") c("1980-12-15", "1983-08-15") c("1983-08-15", "1991-03-15")
## Exp_FROM Exp_TO
## 1 1979-08-24 1988-12-31
## 2 1980-05-15 1988-12-31
## 3 1979-03-17 1979-08-15
## 4 c("1982-01-15", "1984-01-15") c("1984-01-15", "1986-04-15")
## 5 c("1982-01-15", "1984-01-15") c("1984-01-15", "1986-04-15")
## 6 c("1980-12-15", "1983-08-15") c("1983-08-15", "1988-12-31")
## Exps_Grp Yr1952 Yr1953 Yr1954 Yr1955 Yr1956 Yr1957 Yr1958
## 1 fr51>88 NA NA NA NA NA NA NA
## 2 fr51>88 NA NA NA NA NA NA NA
## 3 between NA NA NA NA NA NA NA
## 4 c("between", "between") NA NA NA NA NA NA NA
## 5 c("between", "between") NA NA NA NA NA NA NA
## 6 c("between", "fr51>88") NA NA NA NA NA NA NA
## Yr1959 Yr1960 Yr1961 Yr1962 Yr1963 Yr1964 Yr1965 Yr1966 Yr1967 Yr1968 Yr1969
## 1 NA NA NA NA NA NA NA NA NA NA NA
## 2 NA NA NA NA NA NA NA NA NA NA NA
## 3 NA NA NA NA NA NA NA NA NA NA NA
## 4 NA NA NA NA NA NA NA NA NA NA NA
## 5 NA NA NA NA NA NA NA NA NA NA NA
## 6 NA NA NA NA NA NA NA NA NA NA NA
## Yr1970 Yr1971 Yr1972 Yr1973 Yr1974 Yr1975 Yr1976 Yr1977 Yr1978 Yr1979
## 1 NA NA NA NA NA NA NA NA NA 5.950991
## 2 NA NA NA NA NA NA NA NA NA NA
## 3 NA NA NA NA NA NA NA NA NA 20.608986
## 4 NA NA NA NA NA NA NA NA NA NA
## 5 NA NA NA NA NA NA NA NA NA NA
## 6 NA NA NA NA NA NA NA NA NA NA
## Yr1980 Yr1981 Yr1982 Yr1983 Yr1984 Yr1985 Yr1986
## 1 4.340588 4.340588 4.340588 4.340588 4.340588 4.340588 4.3405881
## 2 2.927725 4.447229 4.447229 4.447229 4.447229 4.447229 4.4472289
## 3 NA NA NA NA NA NA NA
## 4 NA NA 15.365412 16.018407 3.594414 3.052618 0.6918076
## 5 NA NA 15.365412 16.018407 3.594414 3.052618 0.6918076
## 6 0.758267 16.018407 16.018407 16.018407 16.018407 16.018407 16.0184067
## Yr1987 Yr1988 Yrs_Exp arth_mean median cumulative.1 Age
## 1 4.340588 1.083782 9.3616438 4.175948 4.340588 41.75948 9
## 2 4.447229 1.110409 8.6356164 3.907637 4.447229 35.16874 8
## 3 NA NA 0.4136986 20.608986 20.608986 20.60899 9
## 4 NA NA 4.2493151 7.744532 3.594414 38.72266 7
## 5 NA NA 4.2493151 7.744532 3.594414 38.72266 10
## 6 16.018407 3.999565 8.0493151 12.987409 16.018407 116.88668 8
From this information, I want to accomplish a couple things:
*
*I want to calculate how many years that each individual (each ID is one individual) had a mean (which is the arth_mean column) greater than 4. Adding this as a column to my dataset would be ideal.
*Coming off of number 2, I want to have each year that each individual exceeded 4 for arth_mean listed out for each person, also in a new column for my dataset. So for example, I may have a column that has 1954, 1966, 1967, etc. listed for each ID.
I'm relatively new to R, so any help or suggestions are appreciated. I have no idea how to get my desired output. I've added reproducible data below.
## structure(list(ID = 20100:20109, cumulative = c(41.75947792,
## 35.16873597, 20.60898553, 38.72265958, 38.72265958, 116.8866785,
## 271.4880918, 134.9473309, 35.91709062, 26.06165412), sector = c("H38",
## "B01", "H04", "c(\"B09\", \"B37\")", "c(\"B09\", \"B37\")", "c(\"B09\", \"B09\")",
## "c(\"B09\", \"B09\")", "H02", "B13", "H38"), meters = c("6400",
## "1600", "1600", "c(3200, 8000)", "c(3200, 8000)", "c(3200, 3200)",
## "c(3200, 3200)", "1600", "4800", "6400"), DOB = c("1979-08-24",
## "1980-05-05", "1979-03-17", "c(\"1981-11-30\", \"1981-11-30\")",
## "c(\"1978-09-01\", \"1978-09-01\")", "c(\"1980-12-03\", \"1980-12-03\")",
## "c(\"1978-04-25\", \"1978-04-25\")", "1979-06-22", "1978-10-09",
## "1982-04-26"), Oct = c("W", "NW", "SW", "c(\"NE\", \"N\")", "c(\"NE\", \"N\")",
## "c(\"NE\", \"NE\")", "c(\"NE\", \"NE\")", "SE", "N", "W"), Res_FROM = c("1979-08-15",
## "1980-05-15", "1972-06-15", "c(\"1982-01-15\", \"1984-01-15\")",
## "c(\"1982-01-15\", \"1984-01-15\")", "c(\"1980-12-15\", \"1983-08-15\")",
## "c(\"1978-04-15\", \"1983-08-15\")", "1979-06-15", "1978-10-15",
## "1982-04-15"), Res_TO = c("1991-05-15", "1991-04-15", "1979-08-15",
## "c(\"1984-01-15\", \"1986-04-15\")", "c(\"1984-01-15\", \"1986-04-15\")",
## "c(\"1983-08-15\", \"1991-03-15\")", "c(\"1983-08-15\", \"2000-01-15\")",
## "1991-04-15", "1983-03-15", "1991-04-15"), Exp_FROM = c("1979-08-24",
## "1980-05-15", "1979-03-17", "c(\"1982-01-15\", \"1984-01-15\")",
## "c(\"1982-01-15\", \"1984-01-15\")", "c(\"1980-12-15\", \"1983-08-15\")",
## "c(\"1978-04-25\", \"1983-08-15\")", "1979-06-22", "1978-10-15",
## "1982-04-26"), Exp_TO = c("1988-12-31", "1988-12-31", "1979-08-15",
## "c(\"1984-01-15\", \"1986-04-15\")", "c(\"1984-01-15\", \"1986-04-15\")",
## "c(\"1983-08-15\", \"1988-12-31\")", "c(\"1983-08-15\", \"1988-12-31\")",
## "1988-12-31", "1983-03-15", "1988-12-31"), Exps_Grp = c("fr51>88",
## "fr51>88", "between", "c(\"between\", \"between\")", "c(\"between\", \"between\")",
## "c(\"between\", \"fr51>88\")", "c(\"between\", \"fr51>88\")",
## "fr51>88", "between", "fr51>88"), Yr1952 = c(NA, NA, NA, NA,
## NA, NA, NA, NA, NA, NA), Yr1953 = c(NA, NA, NA, NA, NA, NA, NA,
## NA, NA, NA), Yr1954 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
## ), Yr1955 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1956 = c(NA,
## NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1957 = c(NA, NA, NA, NA,
## NA, NA, NA, NA, NA, NA), Yr1958 = c(NA, NA, NA, NA, NA, NA, NA,
## NA, NA, NA), Yr1959 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
## ), Yr1960 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1961 = c(NA,
## NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1962 = c(NA, NA, NA, NA,
## NA, NA, NA, NA, NA, NA), Yr1963 = c(NA, NA, NA, NA, NA, NA, NA,
## NA, NA, NA), Yr1964 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
## ), Yr1965 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1966 = c(NA,
## NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1967 = c(NA, NA, NA, NA,
## NA, NA, NA, NA, NA, NA), Yr1968 = c(NA, NA, NA, NA, NA, NA, NA,
## NA, NA, NA), Yr1969 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
## ), Yr1970 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1971 = c(NA,
## NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1972 = c(NA, NA, NA, NA,
## NA, NA, NA, NA, NA, NA), Yr1973 = c(NA, NA, NA, NA, NA, NA, NA,
## NA, NA, NA), Yr1974 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA
## ), Yr1975 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1976 = c(NA,
## NA, NA, NA, NA, NA, NA, NA, NA, NA), Yr1977 = c(NA, NA, NA, NA,
## NA, NA, NA, NA, NA, NA), Yr1978 = c(NA, NA, NA, NA, NA, NA, 79.39642441,
## NA, 5.655852488, NA), Yr1979 = c(5.950991161, NA, 20.60898553,
## NA, NA, NA, 59.94484924, 28.50091596, 16.41746701, NA), Yr1980 = c(4.340588078,
## 2.927724588, NA, NA, NA, 0.758267013, 16.01840668, 12.90308755,
## 4.387060214, NA), Yr1981 = c(4.340588078, 4.447228937, NA, NA,
## NA, 16.01840668, 16.01840668, 12.90308755, 4.387060214, NA),
## Yr1982 = c(4.340588078, 4.447228937, NA, 15.36541238, 15.36541238,
## 16.01840668, 16.01840668, 12.90308755, 4.387060214, 3.274931595
## ), Yr1983 = c(4.340588078, 4.447228937, NA, 16.01840668,
## 16.01840668, 16.01840668, 16.01840668, 12.90308755, 0.682590481,
## 4.340588078), Yr1984 = c(4.340588078, 4.447228937, NA, 3.594414445,
## 3.594414445, 16.01840668, 16.01840668, 12.90308755, NA, 4.340588078
## ), Yr1985 = c(4.340588078, 4.447228937, NA, 3.052618478,
## 3.052618478, 16.01840668, 16.01840668, 12.90308755, NA, 4.340588078
## ), Yr1986 = c(4.340588078, 4.447228937, NA, 0.691807598,
## 0.691807598, 16.01840668, 16.01840668, 12.90308755, NA, 4.340588078
## ), Yr1987 = c(4.340588078, 4.447228937, NA, NA, NA, 16.01840668,
## 16.01840668, 12.90308755, NA, 4.340588078), Yr1988 = c(1.083782142,
## 1.110408824, NA, NA, NA, 3.999564755, 3.999564755, 3.221714571,
## NA, 1.083782142), Yrs_Exp = c(9.361643836, 8.635616438, 0.41369863,
## 4.249315068, 4.249315068, 8.049315068, 10.69315068, 9.534246575,
## 4.416438356, 6.687671233), arth_mean = c(4.175947792, 3.907637331,
## 20.60898553, 7.744531916, 7.744531916, 12.98740872, 24.68073562,
## 13.49473309, 5.98618177, 3.723093446), median = c(4.340588078,
## 4.447228937, 20.60898553, 3.594414445, 3.594414445, 16.01840668,
## 16.01840668, 12.90308755, 4.387060214, 4.340588078), cumulative.1 = c(41.75947792,
## 35.16873597, 20.60898553, 38.72265958, 38.72265958, 116.8866785,
## 271.4880918, 134.9473309, 35.91709062, 26.06165412), Age = c(9L,
## 8L, 9L, 7L, 10L, 8L, 10L, 9L, 10L, 6L)), class = "data.frame", row.names = c(NA,
## -10L))
A: If your 10 row dataset above is dat, then you can melt the dataset into a long format (Yr columns), restrict to rows where the value in those year columns exceeds 4, count the number of rows as num_yr_above, and concatenate the year values as years_above.
Then just join back to dat
library(data.table)
setDT(dat)
dat[melt(dat,id="ID",
measure=patterns("Yr\\d"))[value>4, .(
num_yr_above=.N,
years_above = list(gsub("Yr","",variable))),
by=ID],
on=.(ID)]
Output: (all columns included, but here I show only the new additional columns added to the dataset)
ID num_yr_above years_above
1: 20106 10 1978,1979,1980,1981,1982,1983,...
2: 20108 5 1978,1979,1980,1981,1982
3: 20100 9 1979,1980,1981,1982,1983,1984,...
4: 20102 1 1979
5: 20107 9 1979,1980,1981,1982,1983,1984,...
6: 20101 7 1981,1982,1983,1984,1985,1986,...
7: 20105 7 1981,1982,1983,1984,1985,1986,...
8: 20103 2 1982,1983
9: 20104 2 1982,1983
10: 20109 5 1983,1984,1985,1986,1987
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71195516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Yii ActiveRecord delete doesn't work I ran into strange situation with Yii ActiveRecord.
I have model User (there are some relations, but no foreign keys). When I try to delete some rows from action:
$cr = new CDbCriteria();
$cr->addColumnCondition(array(
'status' => User::USER_STATUS_DELETED
));
$items = User::model()->findAll($cr);
if(!empty($items)){
foreach($items as $item){
$item->delete();
}
}
There is no effect. Users are still there. By the way, I can delete them manually with phpmyadmin. More interesting thing - $item->delete() returns true.
Where is the problem?
A: 1) Make sure you do not have a function overwriting the delete function
2) if you have a relation, and it is improper created and you are trying to delete a user.id that is related to another record then the delete might fail. (but that should also fail in phpmyadmin)
3) I for example have a soft delete, I just replace the user.status with "deleted". I cannot do that if my model is not validating, so I have to make a ->save(false) to get around that (I actually do not do that but you get my point).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22167164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: javascript - function call in conditional not working I'm fairly new to JavaScript, and trying to build a Snake style game. I have a conditional statement inside an interval update function checking which direction the snake is moving, which calls movement methods in the Snake object to keep it going. Originally, I had this conditional directly in the update function, which worked as intended - the snake kept moving until it hit a wall, where it would stop and wait for different direction input, which it would accept and keep going in a different direction.
It looked like this:
//before, with the checks being done in GamePlay.update()
var Snake = (() => {
let x = 10 * GameBoard.unit;
let y = 10 * GameBoard.unit;
let dir = "r";
let body = [];
body.unshift({x, y});
const moveRight = () => {
x = body[0].x + GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveLeft = () => {
x = body[0].x - GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveUp = () => {
y = body[0].y - GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveDown = () => {
y = body[0].y + GameBoard.unit;
body.unshift({x, y});
body.pop();
}
return {body, dir, moveLeft, moveRight, moveDown, moveUp};
})();
//inside IIFE called GamePlay
const update = () => {
if (Snake.dir == "l" && Snake.body[0].x >= GameBoard.LEFT_WALL){
Snake.moveLeft();
}
else if (Snake.dir == "u" && Snake.body[0].y >= GameBoard.TOP_WALL){
Snake.moveUp();
}
else if (Snake.dir == "r" && Snake.body[0].x <= GameBoard.RIGHT_WALL){
Snake.moveRight();
}
else if (Snake.dir == "d" && Snake.body[0].y <= GameBoard.BOTTOM_WALL){
Snake.moveDown();
}
}
In the interest of organizing the code into its appropriate objects, I tried to move the conditional movement into the Snake object, placing it into a method called movement(), which would be called from the update() function, like so:
//after, update conditionals moved from GamePlay.update() to Snake.movement()
var Snake = (() => {
let x = 10 * GameBoard.unit;
let y = 10 * GameBoard.unit;
let dir = "r";
let body = [];
body.unshift({x, y});
const moveRight = () => {
console.log("in moveRight");
x = body[0].x + GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveLeft = () => {
x = body[0].x - GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveUp = () => {
y = body[0].y - GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveDown = () => {
y = body[0].y + GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const movement = () => {
console.log("called");
if (dir == "l" && body[0].x >= GameBoard.LEFT_WALL){
console.log("in l");
moveLeft();
}
else if (dir == "u" && body[0].y >= GameBoard.TOP_WALL){
console.log("in u");
moveUp();
}
else if (dir == "r" && body[0].x <= GameBoard.RIGHT_WALL){
console.log("in r");
moveRight();
}
else if (dir == "d" && body[0].y <= GameBoard.BOTTOM_WALL){
console.log("in d");
moveDown();
}
}
const alive = () => {
return true;
}
return {body, dir, movement};
})();
// ... in GamePlay
const update = () => {
Snake.movement();
}
This, however, caused the movement to stop functioning after the Snake ran into the right wall (its initial movement on startup is rightward). Before hitting the wall, the console.log("called") and console.log("in r") are output as expected, but after hitting the wall only the "called" log continues, while "in r" stops, which would make sense if body[0].x is greater than GameBoard.RIGHT_WALL. The snake then stops taking any input, and does not move up or downwards, which should not be affected by body[0].x being too large.
My confusion comes from the fact that the behaviors different in the two cases, when its the same conditional code, just refactored into an object method, and why the movement would stop accepting directional input when it continues to do so when outside the object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48448513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: youtube api video search using php restrict adult videos I'm using YouTube API to search videos from my website and I want to restrict users to search adult videos from my site. Is there any option?
Thanks.
A: You could use the safeSearch parameter, set it to "strict" to avoid mature content. E.g.:
https://gdata.youtube.com/feeds/api/videos?q=football&max-results=10&v=2&safeSearch=strict
More info here:
https://developers.google.com/youtube/2.0/reference?csw=1#safeSearchsp
A: safeSearch is also supported in v3 of the API.
https://developers.google.com/youtube/v3/docs/search/list#safeSearch
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26177170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does @RequestMapping annotation accept String parameter in java but not in scala? Reading the @RequestMapping documentation : http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/bind/annotation/RequestMapping.html
It accepts a String array parameter for its path mapping.
So this works using java :
@RequestMapping("MYVIEW")
but in scala I need to use :
@RequestMapping(Array("MYVIEW"))
The scala version makes sense as the annotation expects a String array. But why does above work in java, should it not give a compile time error ?
Below class 'ArrayChecker' (a class I wrote to illustrate this point) causes a java compile time error :
The method acceptArrayParam(String[]) in the type ArrayChecker is not
applicable for the arguments (String)
public class ArrayChecker {
public static void main(String args[]){
String[] strArray;
acceptArrayParam("test");
}
private static void acceptArrayParam(String[] param){
}
}
Should a similar error not be caused by @RequestMapping("MYVIEW") ?
A: Section 9.7.1 of the Java SE specification states:
If the element type is an array type and the corresponding ElementValue is not an ElementValueArrayInitializer, then an array value whose sole element is the value represented by the ElementValue is associated with the element. Otherwise, if the corresponding ElementValue is an ElementValueArrayInitializer, then the array value represented by the ElementValueArrayInitializer is associated with the element.
With a comment clarifying the above stating:
In other words, it is permissible to omit the curly braces when a single-element array is to be associated with an array-valued annotation type element.
Because Scala has no equivalent array initializer syntax, you must use Array(elems).
A: This is part of the language specification for annotations that use the default value element.
See JLS 9.7.3 for examples, including one with the comment "Note that the curly braces are omitted."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14323732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: node.js url with square bracket In express.js i am trying to add a router for url /xxx/xxx/items[5] .
the url have Square Bracket.
Router works fine without Square Bracket, but fails with Square Bracket.
Have any one faced this before if so, what is the way to make it work.
var buildingDeviceCount = require("../models/buildingDeviceCount");
/* api/analytics/v1/deviceCount/Building[5]/today?areas=&yAxis=absoluteDevices&timeRange=00:00-23:59 */
router.get('/api/analytics/v1/deviceCount/Building[5]/today', function(req, res) {
res.json(buildingDeviceCount.buildingDeviceCount);
});
A: The reason the square bracket [ and ] chars are causing chaos is due to the fact that they represent the basic character class in Regular Expressions. Additionally, express.js allows its routes to be defined with regular expressions in them. So, here is what you are actually telling express to respond to when you say: /xxx/xxx/items[5] it is trying to match the given URL with /xxx/xxx/items5
To fix it, define your route like this:
app.get(/^\/api\/analytics\/v1\/deviceCount\/Building\[\d+\]\/today/, function(req, res) {...});
EDIT:
I just found out that express allows for parameter validation. So you can try something like this as well...
app.param("building_5", /^Building\[\d+\]$/);
app.get("/api/analytics/v1/deviceCount/:building_5/today", function(req, res) {...});
A: When you're passing a string to a regex function in JS you need to escape the backslash before the opening bracket, like so
router.get('/api/analytics/v1/deviceCount/Building\\[5\]/today', function(req, res) {
Related:
How can I put [] (square brackets) in RegExp javascript?
Also, use this to get the number in the brackets
app.get('/api/analytics/v1/deviceCount/Building\\[:n\]/today', function(req, res) {
res.send(req.params.n)
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23900750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Merging values attached to like keys in dictionary What i am trying to do is take a text file and return a dictionary of the anagrams (words that make a new word when rearranged alphabetically) in the file. So if the file contained the words dub and bud, then the code should create a key bdu and attach the strings dub and bud to them in a tuple or list or what have you.
Now my code outputs exactly what i want, except that instead of one key with multiple values, im getting identical keys for every value. To draw back to my previous example, i get the key bdu for dub, then another bdu key for bud. How would i remove identical keys and merge key values to one key?
def anagrams(f):
'''takes a file and returns a list of anagrams in the file'''
wordget = open(f).read().lower().split()
dic = {}
for w in wordget:
if ("".join(sortword(w))) in wordget:
dic = {("".join(sortword(w))):w}
for key in dic.keys():
print "'%s': %s" % (key, dic[key])
return None
Any help would be appreciated. I hope to come up with a solution that runs quick too, even with files containing tens of thousands of words (like books)
A: Python's defaultdict type in the collections package is useful for this kind of thing.
from collections import defaultdict
from pprint import pprint
answer = defaultdict(list)
for word in open(filename).read().lower().split():
answer[''.join(sorted(word))].append(word)
pprint(answer)
The defaultdict initialization accepts a function which initializes an object. In this case we initialize an empty list which we can immediately append.
You may also find the pprint module useful. It'll nicely format your lists of words.
A: This
dic = {("".join(sortword(w))):w}
is replacing dic with a new dictionary each time. You should be inserting keys or appending to lists instead
for w in wordget:
key = ''.join(sorted(word))
if key in dic:
dic[key].append(word)
else:
dic[key] = [word]
return dic
The if/else block can be tidied up using defaultdict as in GrantJ's answer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19395007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Spring Security Bad Credentials Error for Password I am using spring authentication. I have hit a problem when attempting to use the following password.
!"£$%^&*()_+{}:@~|<>?A1
The error gives 'Bad credentials'. After doing some debugging I notice in the method 'additionalAuthenticationChecks' of the DaoAuthenticationProvider class that
String presentedPassword = authentication.getCredentials().toString();
evaluates to my input password but with a  character before the £ like so £
It looks to be the £ character causing issues.
Any ideas. Let me know if you require me to paste any configuration e.t.c
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29827315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Orchard get Taxonomy term name of a particular Content Item Is it possible to get the taxonomy term name of a content item in orchard?
I use the Designer tools module and i cannot find it in there.
A: Solved, 'Category' is the name of my taxonomy:
@{
var categoryName = "";
foreach (dynamic term in Model.ContentItem.BlogPost.Category.Terms.Value)
{
categoryName = term.Name;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17342780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Laravel - Relation not push in the second time I trying to save the record with relation by using push() it work well for the first save but I click save it in the second time it doesn't push the relation Laravel 5.5.
public function store(Request $request)
{
if (Session::has('_leave-generation')) {
$ids = $request->input('id');
$data = $request->input('data');
$leaveGenerate = Session::get('_leave-generation');
$leaveGenerate->fill($data);
$this->leaveGenerationItemService->setStatus($ids, $leaveGenerate);
if($leaveGenerate->push())
{
$this->leaveBalanceService->generateLeaveEntitle();
}
}
}
public function setStatus($ids, LeaveGeneration $leaveGeneration)
{
for ($i = 0; $i < count($ids); $i++) {
$id = $ids[$i];
$item = $leaveGeneration->items->find($id);
$item->status = 'P';
$item = $leaveGeneration->items->find($id)->fill($item->toArray());
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49896893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JDK1.8 in Production but JDK 1.7 in Testing Environment What will Happen If I have JDK 1.8 in my Production Environment but on Testing Environment JDK 1.7 ?
A: You shouldn't have any significant issues between Java 1.7 for testing and Java 1.8 for production. Problems exist beyond the 1.9 transition, but 1.7 and 1.8 are compatible.
What you might find is that combinations of start-up flags for the JVM itself (which GC you're using, any additional flags) are different between the two versions. So if you're using a start-up script to set JAVA_OPTIONS then there may be differences in the way that they are launched.
Finally, if you're doing any kind of performance testing then the tests won't be valid between the two JVMs. Even if you're using the same GC configuration, the performance differences in Java 1.7 are likely to be slightly different from Java 1.8.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62607257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: SQLite Query decimal places I have a SQLite database, and I need to extract some values from DB.
I use next query to do it:
SELECT
date, code, model, price,
SUM(Units),SUM(Total)
FROM VTA_VTAdetalle
where code = '07'
GROUP BY date,
code,
price
ORDER BY date ASC
All is OK with the query, but I can't make it to display 3 decimal places.
I have used round(value,3), but when sum has 0 at right (1.100) it only displays 1.1. What I need is that all the time display 1.100.
A: printf("%.3f", value) should work for you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51860424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Request scoped field in a Singleton bean I know it's possible to inject a request scoped bean into a singleton bean in Spring so I know what I'm trying to do will work, I'm just wondering if there is a way to express it more concisely without so many extra unnecessary class definitions. I'm new to Spring annotations so maybe there's an annotation I don't know about.
I have an abstract class that will be extended maybe 100 times in my application as different singleton spring beans. Take this class definition for an example:
/** The abstract class with a field that needs to be request-specific **/
public abstract class AbstractSingletonBean {
private SampleState state;
public SampleState getState() { return state; }
public void setState(SampleState state) { this.state = state; }
// Other fields that are just singleton here
}
And an example of what one of the bean definitions might look like:
@Component
public class SampleSingletonBean extends AbstractSingletonBean {
@Resource(name="sampleState")
public void setState(SampleState state) { super.setState(state); }
}
Now of course we need a bean called sampleState. So I have to create two classes: a base class to define the fields in SampleState and then a request-scoped bean definition. This is because each extension of AbstractSingletonBean will need it's own request-scoped instance of the state field.
Here might be the base class:
public class SampleState {
private String fieldOne;
public String getFieldOne() { return fieldOne }
public void setFieldOne() { this.fieldOne = fieldOne }
}
And here is this silly bean definition:
@Component ("sampleState")
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SampleStateBean extends SampleState {}
The thing that bothers me is that if I have 100 extensions of AbstractSingletonBean, I'll need 100 extensions of SampleStateBean with just boilerplate code to make it request-scoped. Is there a way to just override setState() in the extensions of AbstractSingletonBean and indicate to spring that it should create a new request scoped bean on the fly and inject it here? So my SampleSingletonBean could look like this:
@Component
public class SampleSingletonBean extends AbstractSingletonBean {
@Resource
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public void setState(SampleState state) { super.setState(state); }
}
Of course this doesn't work because @Resource needs to refer to a bean that already exists. Is there another annotation to accomplish this without creating a new class for every SampleState bean?
A: Spring can inject into abstract classes too. So you can move the injection of the SampleState to the abstract class, if each AbstractSingletonBean descendant needs just a SampleState (as in your example).
A: It doesn't look like this was available out of the box so I created an annotation I call @AnonymousRequest that I put on the field I want, and a BeanDefinitionRegistryPostProcessor to do the work of creating the bean. It basically goes like this:
for each bean in the BeanFactory
if bean class has AnonymousRequest annotation
create request scoped bean from field class
create singleton bean to be request scoped bean wrapper
set the annotated property value to the singleton wrapper
This took a lot of work to figure out how Spring registers request scoped beans. You create the bean definition you want as a request scoped bean. Then you create a singleton bean of type RootBeanDefinition that acts as a wrapper to the request scope bean and set a property on the wrapper called "targetBeanName" to whatever you named the request scoped bean ("scopedTarget." + the singleton bean name by convention).
So this could probably be improved by someone who actually knows this stuff but here's what I came up with:
public void createRequestBeanFromSetterMethod(String containingBeanName, BeanDefinition containingBean, Method method, BeanDefinitionRegistry registry)
{
String fieldName = ReflectionUtil.getFieldNameFromSetter(method.getName());
String singletonBeanName = containingBeanName+"_"+fieldName;
String requestBeanName = "scopedTarget."+singletonBeanName;
BeanDefinition requestBean = createAnonymousRequestBean(ReflectionUtil.getFieldTypeFromSetter(method), containingBean);
RootBeanDefinition singletonBean = new RootBeanDefinition();
singletonBean.setBeanClass(ScopedProxyFactoryBean.class);
singletonBean.getPropertyValues().addPropertyValue("targetBeanName", requestBeanName);
registry.registerBeanDefinition(singletonBeanName, singletonBean);
registry.registerBeanDefinition(requestBeanName, requestBean);
beanDefinition.getPropertyValues().addPropertyValue(fieldName, new RuntimeBeanReference(singletonBeanName));
}
private BeanDefinition createAnonymousRequestBean(Class<?> beanType, BeanDefinition parentBean)
{
BeanDefinition newBean = null;
if (parentBean != null)
{
newBean = new GenericBeanDefinition(parentBean);
}
else
{
newBean = new GenericBeanDefinition();
}
if (beanType != null)
{
newBean.setBeanClassName(beanType.getName());
}
newBean.setScope("request");
newBean.setAutowireCandidate(false);
// This would have come from the Proxy annotation...could add support for different values
String proxyValue = "org.springframework.aop.framework.autoproxy.AutoProxyUtils.preserveTargetClass";
BeanMetadataAttribute attr = new BeanMetadataAttribute(proxyValue, true);
newBean.setAttribute(proxyValue, attr);
return newBean;
}
It seems to work! I effectively have now a request scoped bean created just before the context initialization that is localized to this one containing bean. It's a request-scoped property, more or less.
A: You can try defining single SampleState request scope bean and then use spring's lookup method to inject this bean wherever you want to.That's works just fine with prototype-scope beans. Fingers crosses it would work with request scope as well.
AFAIK, there is no annotation support for lookup method as of now, so either use it's xml vis-a-vis
or have a look at javax.inject.Provider relevant question here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17455324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Jquery loop interval I have a series of animation co-ordinates stacked inside a loop. I want to run ALL co-ordinates over a certain period and when it finishes going through all it must start from the top and run through them again.
The loop works, but it doesn't start from the first co-ordinates ('top':'+=50' and 'left':'+=300') when it goes through the loop.
var port = $('span.view-port'),
yoyoDuration = 100,
run = setInterval( function (){
port.animate({
'top': '+=50',
'left': '+=300'
}, {duration: 1500}) /* -- first co-ordinates -- */
.animate({
'top': '+=80',
'left': '-=300'
}, {duration: 1500})
.animate({
'left': '+=300',
}, {duration: 2500})
.animate({
'top': '-=80',
'left': '-=300'
}, {duration: 2500})
.animate({
'top': '+=150',
'left': '+=300'
}, {duration: 2500})
.animate({
'top': '+=50',
'left': '-=300'
}, {duration: 2500}) /* -- last co-ordinates -- */
}, 500);
setTimeout(function () {
}, yoyoDuration);
DEMO: http://jsfiddle.net/simomultimedia/NXSVk/1/
A: There seems to be a mathematical error. If you want your last animate to move the element to the start position, change it to:
.animate({
'top': '-=200',
'left': '-=300'
}
But if you want it to move to start after you current last animation then add the following animate after that:
.animate({
'top': '-=250'
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14807489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Program gets hung up when I use "delete" function I'm trying to write a program where it'll take in info from a user, and the user will have options on what to do. The options are to add, modify, delete, display certain info, find the average, and exit.
I have written code for all of them but I can't get my delete function to work.
Here is my code:
void delete_student(struct students *list, int *count) //Delete's Selected student
{
int id4;
int k;
if (*count != 0)
{
printf("\nEnter the ID of the student you wish to delete: ");
scanf("%d\n", &id4);
for (int i = 0; i < *count; i++) //Searches for the selected student
{
k = i;
if (list[i].id == id4)
{
printf("\nStudent found.\nDeleting...\n");
for (int c = k; c < *count; c++) //Deletes the student if found
{
list[c].id = list[c + 1].id;
strcpy(list[c].name, list[c + 1].name);
list[c].age = list[c + 1].age;
strcpy(list[c].dept, list[c + 1].dept);
list[c].grade = list[c + 1].grade;
}
*count = *count - 1;
printf("\nDeletion Complete.\n");
break;
}
else
printf("\nStudent not found. Please try again.\n");
break;
}
}
else
printf("\nNo student's to delete.\n");
}
Edit:
When I go through the program, and I select to use this function, it'll ask me for the "ID" and then it does nothing and has a blinking cursor.
Could someone tell me what I'm doing wrong?
There's more code if you need it.
Is this how the last element would be deleted:
list[*count].id = 0;
strcpy(list[*count].name, NULL);
list[*count].age = 0;
strcpy(list[*count].dept, NULL);
list[*count].grade = 0;
A: You have a break statement at the end of your for loop that probably shouldn't be there. Just delete that one.
else
printf("\nStudent not found. Please try again.\n");
break;
} ^
|
+------ this one
That printf is a bit inaccurate too; it will get printed out on every iteration of the loop where you didn't happen to find a matching ID.
A: Your scanf() statement has an incorrect format string. You don't need to add the trailing newline; scanf takes care of it. Change that line to scanf("%d", &id4); (no newline) and it should work.
I just wrote a small stub program that compares scanf with and without the newline, and it replicates your error.
A: This loop:
for (int c = k; c < *count; c++)
should probably instead be:
for (int c = k; c < *count - 1; c++)
As written, it reads one past the end of the valid array. The results are undefined. And in particular, the strcpy calls may go quite badly. When it gets to the last entry in that loop, list[c+1] refers to an entry that does not exist (based on *count).
A: Your scanf hangs as it never gets to read your number. No \n needed. Use %d only.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19671060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: why is warning for variable being uninitialized supressed when kernel is compiled with size optimization config enabled? trying to optimize kernel boot time, I disabled the CONFIG_CC_OPTIMIZE_FOR_SIZE flag in config. This resulted in a lot of may-be uninitialized warning (which was treated as error).
Trying to debug that I found that in Makefile:
ifdef CONFIG_CC_OPTIMIZE_FOR_SIZE
KBUILD_CFLAGS += -Os $(call cc-disable-warning,maybe-uninitialized,)
else
KBUILD_CFLAGS += -O2
endif
I dont understand the reson behind disabling the warning for uninitialized variable when kernel is size optimized and not other wise. What is the thought behind this and if i add flag to ignore the uninitialized variables in the later case of "not optimized for size", what issues I can face if any.
Any help is appreciated.
Thank you
A: Very recent kernels (5.1 and later - not yet released at the time of writing - see commit b303c6df80c9 ("kbuild: compute false-positive -Wmaybe-uninitialized cases in Kconfig")) have a separate config option CONFIG_CC_DISABLE_WARN_MAYBE_UNINITIALIZED to disable the warning. Those kernels define the option by default for GCC version 4.7 (which introduced the warning) and GCC version 4.8, but the option can be configured manually.
For your kernel and compiler version, it should be safe to modify the Makefile to add $(call cc-disable-warning,maybe-uninitialized,) globally. Alternatively, you could consider using GCC 4.9 or later.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55489421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Install Sonata Dashboard bundle I want to install Sonata Dashboard bundle, so I follow these steps.
After installing and configuring I get an error:
Compile Error: Declaration of Application\Sonata\DashboardBundle\Entity\Dashboard::getId() must be compatible with Sonata\DashboardBundle\Model\Dashboard::getId(): ?int
I use Symfony 3.4, php 7.2 and composer.json looks like:
"require": {
"php": ">=5.5.9",
"doctrine/doctrine-bundle": "^1.6",
"doctrine/orm": "^2.5",
"enqueue/amqp-lib": "^0.8.23",
"friendsofsymfony/rest-bundle": "^2.3",
"friendsofsymfony/user-bundle": "^2.1",
"incenteev/composer-parameter-handler": "^2.0",
"jms/serializer-bundle": "^2.3",
"liip/monitor-bundle": "^2.6",
"nelmio/api-doc-bundle": "^3.2",
"sensio/distribution-bundle": "^5.0.19",
"sensio/framework-extra-bundle": "^5.0.0",
"sonata-project/admin-bundle": "^3.34",
"sonata-project/block-bundle": "^3.12",
"sonata-project/cache": "1.x-dev",
"sonata-project/cache-bundle": "2.4",
"sonata-project/classification-bundle": "^3.6",
"sonata-project/core-bundle": "^3.9",
"sonata-project/dashboard-bundle": "^0.3.0",
"sonata-project/datagrid-bundle": "2.3",
"sonata-project/doctrine-extensions": "^1.0",
"sonata-project/doctrine-orm-admin-bundle": "^3.5",
"sonata-project/easy-extends-bundle": "^2.5",
"sonata-project/formatter-bundle": "^3.4",
"sonata-project/google-authenticator": "^2.1",
"sonata-project/media-bundle": "^3.12",
"sonata-project/news-bundle": "3.4",
"sonata-project/notification-bundle": "^3.5",
"sonata-project/seo-bundle": "^2.5",
"sonata-project/user-bundle": "^4.1",
"symfony/monolog-bundle": "^3.1.0",
"symfony/polyfill-apcu": "^1.0",
"symfony/swiftmailer-bundle": "^2.6.4",
"symfony/symfony": "3.4.*",
"symfony/templating": "3.4.8",
"twig/twig": "^1.0||^2.0"
},
Any ideas what can be wrong?
A: Looks like the generated entity misses the return type hints… probably a bug in Sonata Easy Extends bundle. You can add type hint by finding and modifying Application\Sonata\DashboardBundle\Entity\Dashboard
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50337910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Convert multiple files from tsv to csv using pandas and glob While trying to convert the tab separated files (.tsv extension) to comma separated files (.csv extension) from local folder, it converted first two files to .csv but the last 2 files are not converted to .csv.
Here is list of files format :
dir--
abc.tsv
red 1.tsv
yellow 2022.01.20.tsv
blue 2022.01.28.tsv
for the first 2 files will be converting into .csv as successfully. But last 2 files are not being converted as .csv and it's throwing the error like :
ValueError: Excel file format cannot be determined, you must specify an engine manually.
Here is the sample code snippet :
import glob
import pandas as pd
tsvfiles =
glob.glob('C:/Users/xxxx/xxx/xxx/*.tsv')
for tsv_file in tsvfiles:
out = tsv_file.split('.')[0]+'.csv'
df = pd.read_csv(tsv_file)
df.to_csv(out)
A: You can try this code:
import pandas as pd
import glob
path = 'Enter your path here'
tsvfiles = glob.glob(path + "/*.tsv")
for t in tsvfiles:
tsv = pd.read_table(t, sep='\t')
tsv.to_csv(t[:-4] + '.csv', index=False)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71342975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to setup Webpack to change a specific config file for dev or production? I have 2 files, config_local.js and config_prod.js.
How would you pass in a variable into webpack to basically generate a new file named config_api.js from either the local one or the production one.
config_local.js
"api": {
"login": "http://localhost/app/api/login/",
"users": "http://localhost/app/api/users/"
}
config_prod.js
"api": {
"login": "/app/api/login/",
"users": "/app/api/users/"
}
Then inside of my services/api.js file
import axios from 'axios'
export const userLogin = (username, password) => {
const post_data = { username, password };
return axios.post('http://localhost/app/api/login', post_data)
.then(res => res);
};
I could do something like so:
import axios from 'axios'
import api from 'config_api'
export const userLogin = (username, password) => {
const post_data = { username, password };
return axios.post(api.login, post_data) // <--
.then(res => res);
};
A: In package.json you can use scripts or even at commandline you can use environment variable.s
"scripts": {
"dev": "NODE_ENV=development webpack",
"production": "NODE_ENV=production webpack",
"watch": "npm run dev -- --watch"
},
In webpack.config.js you can use
const inProduction = process.env.NODE_ENV === 'production';
const inDevelopment = process.env.NODE_ENV === "development";
if(inProduction)
//do this
if(inDevelopment)
//do that
webpack by default looks for weback.config.js however for custom config you can use
webpack --config config_local.js
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44336649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is the difference between :focus and :active? What is the difference between the :focus and :active pseudo-classes?
A: :active Adds a style to an element that is activated
:focus Adds a style to an element that has keyboard input focus
:hover Adds a style to an element when you mouse over it
:lang Adds a style to an element with a specific lang attribute
:link Adds a style to an unvisited link
:visited Adds a style to a visited link
Source: CSS Pseudo-classes
A: :focus and :active are two different states.
*
*:focus represents the state when the element is currently selected to receive input and
*:active represents the state when the element is currently being activated by the user.
For example let's say we have a <button>. The <button> will not have any state to begin with. It just exists. If we use Tab to give "focus" to the <button>, it now enters its :focus state. If you then click (or press space), you then make the button enter its (:active) state.
On that note, when you click on an element, you give it focus, which also cultivates the illusion that :focus and :active are the same. They are not the same. When clicked the button is in :focus:active state.
An example:
<style type="text/css">
button { font-weight: normal; color: black; }
button:focus { color: red; }
button:active { font-weight: bold; }
</style>
<button>
When clicked, my text turns red AND bold!<br />
But not when focused only,<br />
where my text just turns red
</button>
edit: jsfiddle
A: There are four cases.
*
*By default, active and focus are both off.
*When you tab to cycle through focusable elements, they will enter :focus (without active).
*When you click on a non-focusable element, it enters :active (without focus).
*When you click on a focusable element it enters :active:focus (active and focus simultaneously).
Example:
<div>
I cannot be focused.
</div>
<div tabindex="0">
I am focusable.
</div>
div:focus {
background: green;
}
div:active {
color: orange;
}
div:focus:active {
font-weight: bold;
}
When the page loads both are in case 1. When you press tab you will focus the second div and see it exhibit case 2. When you click on the first div you see case 3. When you click the second div, you see case 4.
Whether an element is focusable or not is another question. Most are not by default. But, it's safe to assume <a>, <input>, <textarea> are focusable by default.
A: :focus is when an element is able to accept input - the cursor in a input box or a link that has been tabbed to.
:active is when an element is being activated by a user - the time between when a user presses a mouse button and then releases it.
A: Active is when the user activating that point (Like mouse clicking, if we use tab from field-to-field there is no sign from active style. Maybe clicking need more time, just try hold click on that point), focus is happened after the point is activated. Try this :
<style type="text/css">
input { font-weight: normal; color: black; }
input:focus { color: green; outline: 1px solid green; }
input:active { color: red; outline: 1px solid red; }
</style>
<input type="text"/>
<input type="text"/>
A: Using "focus" will give keyboard users the same effect that mouse users get when they hover with a mouse. "Active" is needed to get the same effect in Internet Explorer.
The reality is, these states do not work as they should for all users. Not using all three selectors creates accessibility issues for many keyboard-only users who are physically unable to use a mouse. I invite you to take the #nomouse challenge (nomouse dot org).
A: Focus can only be given by keyboard input, but an Element can be activated by both, a mouse or a keyboard.
If one would use :focus on a link, the style rule would only apply with pressing a botton on the keyboard.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1677990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "360"
}
|
Q: SDL2 SDL_SetEventFilter vs SDL_WaitEvent I had a typical SDL event loop calling SDL_WaitEvent, and ran into a much-discussed issue (see here and here) where my application was not able to re-draw during a resize because SDL_WaitEvent doesn't return until a resize is finished on certain platforms (Win32 & Mac OS). In each of these discussions, the technique of using SDL_SetEventFilter to get around it is mentioned and more or less accepted as a solution and a hack.
Using the SDL_SetEventFilter approach works perfectly, but now I'm looking at my code and I've practically moved all the code from my SDL_WaitEvent into my EventFilter and just handling events there.
Architecturally it's fishy as heck.
Are there any gotcha's with this approach of dispatching messages to my application in the function set by SDL_SetEventFilter, besides the possibility of being called on a separate thread?
Bonus question: How is SDL handling this internally? From what I understand, this resize issue is rooted in the underlying platform. For example, Win32 will issue a WM_SIZING and then enter its own internal message pump until WM_SIZE is issued. What is triggering the SDL EventFilter to run?
A: Answering my own question after more experimentation and sifting through the source.
The way SDL handles events is that when you call SDL_WaitEvent/SDL_PeekEvent/SDL_PeepEvents, it pumps win32 until there's no messages left. During that pump, it will process the win32 messages and turn them into SDL events, which it queues, to return after the pump completes.
The way win32 handles move/resize operations is to go into a message pump until moving/resizing completes. It's a regular message pump, so your WndProc is still invoked during this time. You'll get a WM_ENTERSIZEMOVE, followed by many WM_SIZING or WM_MOVING messages, then finally a WM_EXITSIZEMOVE.
These two things together means that when you call any of the SDL event functions and win32 does a move/resize operation, you're stuck until dragging completes.
The way EventFilter gets around this is that it gets called as part of the WndProc itself. This means that you don't need to queue up messages and get them handed back to you at the end of SDL_Peek/Wait/Peep Event. You get them handed to you immediately as part of the pumping.
In my architecture, this fits perfectly. YMMV.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46869687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to have different text in each pop-up I'm very new to coding and am trying to create a portfolio website.
I have used a pop-up code sourced from W3 Schools.
The idea is that when you click on each small illustration, a full-screen pop-up appears with text. I have been able to do it successfully for one pop-up when you click on the flower.
My problem is, I am now unsure how to do a pop-up for each small illustration with different text.
I have added my code to this post, as well as screenshots of it in the browser to give you a better idea of what it looks like with the illustrations. Website Screenshot Here
Any help would be very much appreciated! I'm very stuck.
/* Open */
function openNav() {
document.getElementById("popup").style.height = "100%";
}
/* Close */
function closeNav() {
document.getElementById("popup").style.height = "0%";
}
/* Universal Styles */
body, html {
width: 100%;
}
body {
font-family: "Montserrat", "Helvetica", san-serif;
color: white;
background-color: #9486f2;
font-weight: 300;
font-size: 18px;
}
/* Navigation */
a {
color: white;
text-decoration: none;
font-size: 20px;
}
a:hover {
color:#adff2f;
font-weight: 400;
letter-spacing: 5px;
}
nav {
text-align: right;
padding-top: 30px;
padding-right: 50px;
float: right;
}
nav div {
padding: 5px 0;
}
/* Logo */
header img {
height: 80px;
padding-left: 50px;
padding-top: 50px;
}
/* Heart & Icons */
.container .rowtop {
text-align: center;
}
#flower {
position: relative;
right: 120px;
cursor: pointer;
height: 100px;
}
#adobe {
position: relative;
left: 190px;
}
.container .rowmiddle {
text-align: center;
}
#code {
position: relative;
bottom: 370px;
right: 30px;
}
#heart {
position: relative;
bottom: 60px;
}
#pudding {
position: relative;
bottom: 330px;
left: 50px;
}
.container .rowbottom {
text-align: center;
}
#certificate {
position: relative;
bottom: 210px;
right: 120px;
}
#tv {
position: relative;
bottom: 200px;
left: 190px;
}
/* Pop-Ups */
/* The Overlay (background) */
.overlay {
/* Height & width depends on how you want to reveal the overlay (see JS below) */
height: 0;
width: 100%;
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
opacity: 0.95;
background-color: #cc90ec; /* Black w/opacity */
overflow-y: hidden; /* Disable horizontal scroll */
transition: 0.5s; /* 0.5 second transition effect to slide in or slide down the overlay (height or width, depending on reveal) */
}
/* Position the content inside the overlay */
.overlay-content {
position: relative;
top: 25%; /* 25% from the top */
width: 40%; /* 100% width */
text-align: left; /* Centered text/links */
margin-top: 50px;
font-size: 30px;
line-height: 46px;
margin: 0 auto;
}
/* When you mouse over the navigation links, change their color */
.overlay a:hover, .overlay a:focus {
color:#adff2f;
}
/* Position the close button (top right corner) */
.overlay .closebtn {
position: absolute;
top: 20px;
right: 45px;
font-size: 60px;
}
/* Wavy Text */
.wavy
{
position: relative;
-webkit-box-reflect: below -12px linear-gradient(
transparent, rgba(0,0,0,0.2));
}
.wavy span
{
position: relative;
display: inline-block;
color: #adff2f;
font-weight: 400;
animation: animate 2s ease-in-out infinite;
animation-delay: calc(0.1s * var(--i));
}
@keyframes animate
{
0%
{
transform: translateY(0px);
}
10%
{
transform: translateY(-20px);
}
30%,100%
{
transform: translateY(0px);
}
}
/* Footer */
h5 {
font-family: "Montserrat", "Helvetica", san-serif;
color: white;
font-weight: 200;
font-size: 14px;
}
footer {
padding-left: 50px;
position: relative;
bottom: 30px;
}
<!DOCTYPE html>
<html>
<head>
<title>Dom Pooley</title>
<script src="main.js" ></script>
<link rel="stylesheet" href="/Users/dominiquepooley/Documents/03_Dom Personal/05_Portfolio/Portfolio 2020/Portfolio2020/resources/css/style.css" type="text/css" />
<link href="https://fonts.googleapis.com/css2?family=Montserrat+Alternates:ital,wght@0,200;0,300;0,400;0,700;1,200;1,300;1,400;1,700&display=swap" rel="stylesheet">
</head>
<!-- Header -->
<body>
<header class="flex-container">
<img src="/Users/dominiquepooley/Documents/03_Dom Personal/05_Portfolio/Portfolio 2020/Portfolio2020/resources/images/DomPooley_Logo_01.png"">
<nav>
<div><a href= "./about.html">About</a></div>
<div><a href= "./work.html">Work</a></div>
<div><a href= "./contact.html">Contact</a></div>
</nav>
</header>
<!-- Heart and Icons -->
<div class="container">
<div class="rowtop">
<img id="flower" src="resources/images/Pansy_01.png" onmouseover="this.src='resources/images/Pansy_02.png' " onmouseout="this.src='resources/images/Pansy_01.png'" onClick="openNav()">
<img src="resources/images/Adobe_01.gif" id="adobe" alt="" height="120">
</div>
<div class="rowmiddle">
<img src="resources/images/Code_01.gif" onmouseover="this.src='resources/images/Code_02.png' " onmouseout="this.src='resources/images/Code_01.gif'" id="code" alt="" height="40">
<img id="heart" height="500" src="resources/images/Dom_Heart_01.png" onmouseover="this.src='resources/images/Dom_Heart_02.png' " onmouseout="this.src='resources/images/Dom_Heart_01.png'"/>
<img src="resources/images/Pudding_01.gif" id="pudding" alt="" height="120">
</div>
<div class="rowbottom">
<img src="resources/images/Certificate_01.gif" id="certificate" alt="" height="100">
<img src="resources/images/TV_01.gif" id="tv" alt="" height="110">
</div>
</div>
<!-- Pop-Ups -->
<!-- The Overlay -->
<div id="popup" class="overlay">
<!-- Button to close the overlay navigation -->
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<!-- Overlay content -->
<div id="flowerpop" class="overlay-content">
<p>Thanks to COVID-19, I now have a new hobby -I have been growing, picking, pressing and coating flowers in resin to make jewellery. I would include a photo but they still have that "primary school project vibe"...
<br><div class="wavy">
<span style="--i:1;">*</span>
<span style="--i:2;">W</span>
<span style="--i:3;">a</span>
<span style="--i:4;">t</span>
<span style="--i:5;">c</span>
<span style="--i:6;">h</span>
<span style="--i:7;"> </span>
<span style="--i:8;">t</span>
<span style="--i:9;">h</span>
<span style="--i:10;">i</span>
<span style="--i:11;">s</span>
<span style="--i:12;"> </span>
<span style="--i:13;">s</span>
<span style="--i:14;">p</span>
<span style="--i:15;">a</span>
<span style="--i:16;">c</span>
<span style="--i:17;">e</span>
<span style="--i:18;">*</span>
</div></br></p>
</div>
</div>
<!-- Footer Section -->
<footer>
<h5>Copyright Dominique Pooley 2020</h5>
</footer>
</body>
</html>
A: You have to make a small change in css.
a:hover {
color:#adff2f;
font-weight: 400;
letter-spacing: 5px;
}
You have to remove letter-spacing: 5px; from css file.
then code looks like :
a:hover {
color:#adff2f;
font-weight: 400;
}
A: based on what you've mentioned, it sounds like you're trying to have a generic pop-up/modal as a HTML element and then when you click on different illustrations it will open the modal and the modal would contain some text related to that illustration that you clicked on.
What you want to do, is keep your modal, which appears to be the #popup element, add an onclick to each illustration that runs a function which dynamically injects some text by targetting the heading where you need the text to be, for example:
toggleModal (title, subtitle) {
const headingEl = document.querySelector('[data-your-heading]')
const subtitleEl = document.querySelector('[data-your-subtitle]')
headingEl.innerText = title
subtitleEl.innerText = subtitle
// run some code to hide/show the modal below here
}
Next, attach the data-your-* attributes to whichever tag you want to update text with, for instance a <p> tag within your generic HTML modal/pop-up.
And then on each of your illustrations, you add an onclick function and pass the arguments of what text you want, for example:
<button type="button" onclick="toggleModal('My Title', 'My Subtitle')">Show Illustration 1</button>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63968610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Replace " by ' with awk I have a file call xxxx.txt and I want in a var the line start with Sentencia, but " replaced by '.
$ cat xxxx.txt
>Ejecutor: Ezequiel
>Jira: 13226
>Origen (PROD/CUA/ACE/PROD6/DEV): PROD
>Destino (PROD/CUA/ACE/PROD6/DEV): CUA
>Sentencia: select * from pricing_user.prc_promotions where fec_baja is NULL and end_date
between NOW() and adddate(NOW(), 30) and werks in ("6027", "0006", "0055", "6785")
>Tabla Destino: pricing_user.prc_promotions
I am using awk, but I can not do it.
$ var=$(awk -F": " '{if ($1 == "Sentencia") print $2} {gsub("\"","\'",$0)}' xxxx.txt)
> ^C
A: The bullet proof version would be:
awk 'match($0,/^Sentencia: */){gsub("\042","\047"/); print substr($0,RLENGTH+1)}'
We make use of the octal notation as this is the one which is supported by Posix (See section regular expressions of the POSIX standard).
I avoid the usage of FS=":" as there could be an extra : in the respective line.
A: awk -F": " '{if ($1 == "Sentencia") {gsub("\042","\047",$2);print}}' $wkdir/xxxx.txt
I replace the double quote by \042 and single quote by \047 (octal equivalent)
$ awk -F": " '{if ($1 == "Sentencia") {gsub("\042","\047",$2);print}}' $wkdir/MigrarDatosTablas.txt
Sentencia select * from pricing_user.prc_promotions where fec_baja is NULL and end_date between NOW() and adddate(NOW(), 30) and werks in ('6027', '0006', '0055', '6785')
A: Adding to the others answers, you could also write your program to an awk file and, with the shell not interfering, use the quotes as-is:
$ cat program.awk
BEGIN {
FS=":" # set the delimiter
}
/^>Sentencia:/ { # match the beginning
gsub(/"/,"'",$0) # <- LOOK HERE
print $2
}
$ awk -f program.awk file
select * from pricing_user.prc_promotions where fec_baja is NULL and end_date between NOW() and adddate(NOW(), 30) and werks in ('6027', '0006', '0055', '6785')
I'm going to overlook some other problems in the code as others already have pointed them out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59158251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Why does not this RPC server scale? package main
import (
"fmt"
"net"
"net/rpc"
"sync"
)
type SumInput struct {
UpTo int
}
type SumOutput struct {
Result int
}
type RpcServer struct {
}
func (s *RpcServer) Calculate(in *SumInput, out *SumOutput) error {
for i := 0; i < in.UpTo; i++ {
out.Result += i
}
return nil
}
func main() {
server := new(RpcServer)
rpc.Register(server)
sock, err := net.Listen("tcp", ":1234")
if err != nil {
panic(err)
}
go func() {
for {
conn, err := sock.Accept()
if err != nil {
panic(err)
}
go rpc.ServeConn(conn)
}
}()
wg := &sync.WaitGroup{}
wg.Add(100)
for i := 0; i < 100; i++ {
go func(i int) {
client, err := rpc.Dial("tcp", "127.0.0.1:1234")
if err != nil {
panic(err)
}
rpcOut := &SumOutput{}
err = client.Call("RpcServer.Calculate", &SumInput{100000000}, rpcOut)
if err != nil {
panic(err)
}
fmt.Println("Got reply: ", rpcOut, i)
wg.Done()
}(i)
}
wg.Wait()
}
It starts an RPC server and 100 clients in parallel, but it never makes use of more than 1 CPUs, despite that GOMAXPROCS is properly configured.
So what was stopping it from using more CPUs? And how to improve the situation?
A: I tried your example like this and it worked fine using all 8 CPUs on my laptop
GOMAXPROCS=8 go run rpctest.go
So at a guess you messed up setting the GOMAXPROCS environment variable somehow. Did you set it on a separate line and forget to export it?
export GOMAXPROCS=8
Normally I set this in program using the runtime module
runtime.GOMAXPROCS(runtime.NumCPU())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21362099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Display date or time on the values axis (y-axis) of a chart in Excel I have a process that produces widgets at a variable rate. The number of widgets produced every 5 minutes is reported to a log. Knowing how many widgets must be produced in total, I can use the number of widgets produced in any timeframe to compute the estimated time of completion (ETC) of the process. But how can I make Excel show the ETC on the y-axis?
For example, this data shows sample time; count of widgets since the process started; (computed) average number of widgets produced per minute from record 1 to the current record; and the (computed) ETC based on the average, the known total number of widgets (127830) to be produced, and the current time.
+-------------+-------+---------+-------------+
| Time | Count | Average | ETC |
+-------------+-------+---------+-------------+
| 11:39:20 AM | 256 | | |
| 11:44:20 AM | 13083 | 2617 | 12:27:20 PM |
| 11:49:20 AM | 27979 | 2798 | 12:24:20 PM |
| 11:54:20 AM | 28196 | 1880 | 12:47:20 PM |
| 11:59:20 AM | 28201 | 1410 | 1:09:20 PM |
| 12:04:20 PM | 28791 | 1152 | 1:29:20 PM |
| 12:09:20 PM | 28936 | 965 | 1:51:20 PM |
| 12:14:20 PM | 52237 | 1492 | 1:04:20 PM |
| 12:19:20 PM | 56599 | 1415 | 1:09:20 PM |
| 12:24:20 PM | 59948 | 1332 | 1:14:20 PM |
| 12:29:20 PM | 66523 | 1330 | 1:15:20 PM |
| 12:34:20 PM | 69557 | 1265 | 1:20:20 PM |
| 12:39:20 PM | 74458 | 1241 | 1:22:20 PM |
| 12:44:20 PM | 80642 | 1241 | 1:22:20 PM |
+-------------+-------+---------+-------------+
When I chart this in Excel, I get the ETC (time) values as fractions of a day.
I see the y-axis has a property named "Display units" that allows me to show the values as thousands or millions, but not date or time. Am I missing something, or is this just a limitation of Excel?
A: *
*Right-click on the labels and choose "Format Axis from the drop down menu
*Under "Number", choose the number format you want (Time)
This should give you the desired result:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58208678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java ArrayLists not equal even though they are Hi I have two ArrayList which has HashMap stored in it. For e.g
expectedList = [
{
id = 1, key = X, rowid = 1, id = 1, timeofday = 12: 12: 00,
stream = A
},
{
id = 999999999, key = Y, rowid = 2, id = 1, timeofday = 16: 12: 00,
stream = A
}]
tableList = [
{
id = 1, key = X, rowid = 1, id = 1, timeofday = 12: 12: 00,
stream = A
},
{
id = 999999999, key = Y, rowid = 2, id = 1, timeofday = 16: 12: 00,
stream = A
}]
expectedFileList.equals(tableList) //returns false any idea why? Data is exactly same in both lists even order is same still it returns false. Please guide. Thanks in advance.
A: Two things:
*
*The last element in tableList says bundlestream=..., while expectedList just says stream=.... Something is clearly different. Edit: It appears the OP edited out this change; so it must have been a typo, which leaves:
*Are you sure the objects stored in the list implement equals() properly (or, in this case, the keys and values in the HashMaps in the lists)? If those objects' equals() are not returning expected results, then neither will the ArrayList's equals().
Temporary Edit:
@OP: Can you run the following code:
public static <T,U> void dumpList (List<HashMap<T,U>> list) {
System.out.println("List:");
for (HashMap<T,U> map:list)
for (Map.Entry<T,U> e:map.entrySet())
System.out.println(e.getKey().getClass() + ", " + e.getValue().getClass());
}
On both of your lists, e.g.:
dumpList(tableList);
dumpList(expectedList);
And post the output that it prints in your question?
A: Data is different
stream=A
vs
bundlestream=A
A: Your tableList has bundlestream=A
A: The problem is that the last object of data is different in them.
stream=A and bundlestream=A
A: equals() for ArrayList is inherited from AbstractList:
public boolean equals(Object o)
Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists
have the same size, and all corresponding pairs of elements in the two
lists are equal. (Two elements e1 and e2 are equal if (e1==null ?
e2==null : e1.equals(e2)).) In other words, two lists are defined to
be equal if they contain the same elements in the same order.
So, perhaps you have not overridden .equals() for at least one of the objects in your List.
A: First you have to understand how equals works in ArrayList.
And also you stored HashMap with in Array.
This is how equals method works in ArrayList
public boolean equals(Object paramObject)
{
if (paramObject == this)
return true;
if (!(paramObject instanceof List))
{
return false;
}
ListIterator localListIterator1 = listIterator();
ListIterator localListIterator2 = ((List) paramObject).listIterator();
while ((localListIterator1.hasNext()) && (localListIterator2.hasNext()))
{
Object localObject1 = localListIterator1.next();
Object localObject2 = localListIterator2.next();
if (localObject1 == null)
if (localObject2 != null)
;
else if (!(localObject1.equals(localObject2)))
return false;
}
return ((!(localListIterator1.hasNext())) && (!(localListIterator2.hasNext())));
}
Yes, ArrayList internally compare each and evertObject in List, the compare by means of again, equals method of element in ArrayList.
In your case the element is HashMap, so U also need to know how equals method works in HashMap. http://javarevisited.blogspot.in/2011/02/how-hashmap-works-in-java.html
So, the sort and quick solution is that just overide equals method of your own. And dont forget to implement hasCode method also.
How to return index of ArrayList<Field>
Sorry for the long Answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18117871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WP-Calendar Saturday will not show My problem is very simple to say. In the graphical calendar which I called for in one of my pages. Despite setting the parameters and reading the documentation, I can get every day of the week to show up in the calendar except for Saturday. I wouldn't care so much except I run a internet radio show and one of my specialty shows is on a Saturday. I'd like for it to be able to show all seven days in the full month view. I really like the layout and design of your calendar, but your parameters make my head spin. I set the weekends to true, because I thought from what I read would make them display. I guess I was wrong. I'm not a programmer of web designer yet. I start school in the fall. I'm having a hard time wrapping my head around these settings. Please help.
You may visit my page directly to see what I mean.
http://www.loftonspace.com/home/radio/
Thank You for any help.P.S. I realize people just don't give out help for free, so to the person who helps the most resolve my issue, I have a special place at the footer of my site for special thanks to people who helped with the site. I would be willing to add a link there to a professional website. Thanks
A: You need to set the width of the calendar. It is showing the fullCalendar completely, but the overflow is hidden behind the smaller div you placed the calendar in. Make the available space smaller and that should fix the problem...
As for the promotion... If my answer is accepted, use Stackoverflow as the promotion as I do not run any kind of professional establishment. I just do my own projects.
I am not in a position where I can further inspect the code and give you a proper answer, but you can use firebug to find the class/id of the div you need to change. Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10024362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make all users within the domain a member of a security group Using either Powershell or VBS, how can I make all of the users within my domain who have an email address a member of a specific security group?
A: import ActiveDirectory
$Group = Get-ADGroup -filter {Name -eq "GroupName"}
Get-ADUser -filter {EmailAddress -like "*"} | % {Add-ADGroupMember $Group $_}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5269413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.