text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: JWT x5c token validation .net core I would like to validate a JWS token with "alg": "ES256", "x5c" header fields only.
x5c field contain 3 certificates. I'm able to load them but .net return a IDX10503 error telling me kid field is missing.
here is my code :
var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(token);
var x5cList = JsonConvert.DeserializeObject<List<string>>(jwtSecurityToken.Header.X5c);
var certs = ValidateCertificate(x5cList.ToList());
var keys = certs.Select(cert => new X509SecurityKey(cert)).ToList();
SecurityToken validatedToken;
handler.ValidateToken(jwtSecurityToken.RawData, new TokenValidationParameters
{
ValidateLifetime = true,
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
IssuerSigningKeys = keys,
TryAllIssuerSigningKeys = true,
}, out validatedToken);
Anyone know why it's not working ? I also tried to don't load keys by myself thinking that JwtSecurityTokenHandler may be able to do it by it self but it's not working as well.
When I load this token on jwt.io it says it is validated...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70677968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Logistic regression with small and differing sample sizes I am relatively new to statistics and confused about the best way to proceed with this logistic regression model (and if it is the correct statistical test to use).
I ran the model in SAS and I can't make sense of the results. My first question- does it matter that the groups are quite different in size AND the sample size is small? The total sample size excluding missing values is 57, with 13 in Group 3, 18 in Group 2, 26 in Group 1.
Second question- The odds ratios are very small, ranging from <.0001 to 0.9 with a 95%CI of seemingly infinity. Is this just a function of the sample size?
Am I missing something here that would give more accurate results, or should a different test be utilized? It seems like as it stands it is not worth moving forward with the analysis.
The independent variable is social support-- continuous and ranging from 1.10 to 4 in 0.10 increments.
The outcome variable is sleep quality that has been combined into 3 separate groups -- categorical.
Thank you in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62903855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: updating NSManagedObject doesn't call NSFetchedResultsControllerDelegate using MagicalRecord I have a model with this one to many relationShip:
Order -->> LineItem
I display LineItems in UITableViewCells:
I use UIPickerView for changing quantity of LineItems.
GOAL=> by changing picker value, subTotal be recalculated again.
the problem is here by updating lineItem, NSFetchedResultsController Delegate doesn't call (where I can reconfigure the cell again and display updated data). but when I update Order e.g set it as completed NSFetchedResultsController Delegate methods will be called.
why by updating lineItem doesn't affect delegates methods to be called?
I use magicalRecord and here is how I get NSFetchedResultsController
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
else
{
_fetchedResultsController = [Order fetchAllSortedBy:@"orderDate" ascending:YES withPredicate:nil groupBy:nil delegate:self];
}
return _fetchedResultsController;
}
the way I setup table view:
ConfigureCellBlock configureCell = ^(OrderDetailsCell *cell, LineItem *lineItem)
{
[cell configureForLineItem:lineItem];
};
//set fetchedresults controller delegate
Order *order = [[self.fetchedResultsController fetchedObjects] lastObject];
NSArray *lineItems = [order.lineItems allObjects];
self.ordersDataSource = [[ArrayDataSource alloc] initWithItems:lineItems cellIdentifier:@"lineItemCell" configureCellBlock:configureCell];
self.tableView.dataSource = self.ordersDataSource;
configuring cell:
- (void)configureForLineItem:(LineItem *)lineItem
{
self.menuItemName.text = lineItem.menuItemName;
self.price.text = [lineItem.unitPrice stringValue];
self.quantity.text = [lineItem.quantity stringValue];
self.totalPrice.text = [lineItem.totalPrice stringValue];
self.pickerController.model = lineItem;
self.picker.delegate = self.pickerController;
self.picker.dataSource = self.pickerController;
[self.picker setSelectedNumber:lineItem.quantity];
}
does fetching obj1 then updating obj3 cause the NSFRC delegate methods to be called?
A: The FRC will only observe changes to the objects that it is directly interested in, not any of the objects that they are related to.
You should configure your own observation, either directly with KVO or to the context being saved, and use that to trigger a UI refresh.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24579860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery Mobile changePage() not working in WP8.1 Hi I've spent a long time trying to get my jquery mobile (v1.4.5) and cordova (v5.3.1) app running on WP8.1. It runs fine on iOS and Android. I am aware of this SO question, and the problem I'm having is not related to this, or any others on SO.
Changepage seems to get stuck on WP8.1 because it thinks my app is still in a page transitioning state. For some reason releaseTransitionLock is not being called when it should from a previous transition.
If I comment out the if(isPageTransitioning) check in the 'change' method then it works, but I presume this has negative side-effects elsewhere.
It's a multipage app where all the pages are divs in the same html doc and I'm running jQuery v2.0.3. My changepage syntax is this, and I've tried it with transition 'none' and a variety of other options:
$.mobile.changePage("#register", { transition: "slide" });
Has anyone observed this behaviour and come up with a diagnosis or fix?
A: Use below method and it will work definitely
$.mobile.navigate("#register", {transition: "slide"});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32757265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Trying to use geojson data to plot a district level choropleth I recently been interested in doing a chloropleth map of average rent prices in San Francisco over time. For example if I had a dataset like
example Dataset
data = {'district' : ['6a', '6b','7a', '7c', '5f'],
'price' : [1000, 1500,2000 ,2500, 1750]
}
data = pd.DataFrame(data)
GeoJson San Francisco Districts
import requests
r = requests.get('https://raw.githubusercontent.com/JimKing100/SF_Real_Estate_Live/master/data/Realtor%20Neighborhoods.geojson')
json_response = r.json()
type(json_response)
San Francisco district breakdown https://www.houseofkinoko.com/sf-district-guide/
I was wondering how I would use plotly or other data visualization tools to create a detailed 'zoomed- in' choropleth of san francisco filled by the varying prices.
Sorry if this is a bit vague but I'm a bit lossed and confused on how I should proceed with this project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73264582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to install specific branch of git repository using yarn? I am able to install one GitHub package but not other using yarn. Please let me know what could be the issue here.
I can add https://github.com/fancyapps/fancybox#3.0
but not https://github.com/opentripplanner/otp-react-redux#result-post-processor
ravis-MacBook-Pro:gitprojects ******$ mkdir test
ravis-MacBook-Pro:gitprojects ******$ cd test
ravis-MacBook-Pro:test ***********$ yarn init
yarn init v1.6.0
question name (test):
question version (1.0.0):
question description:
question entry point (index.js):
question repository url:
question author:
question license (MIT):
question private:
success Saved package.json
✨ Done in 11.54s.
ravis-MacBook-Pro:test ******$ yarn add https://github.com/fancyapps/fancybox#3.0
yarn add v1.6.0
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
warning " > @fancyapps/[email protected]" has unmet peer dependency "jquery@>=1.9.0".
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ @fancyapps/[email protected]
info All dependencies
└─ @fancyapps/[email protected]
✨ Done in 1.35s.
ravis-MacBook-Pro:test *******$ yarn add https://github.com/opentripplanner/otp-react-redux#result-post-processor
yarn add v1.6.0
[1/4] Resolving packages...
error Can't add "otp-react-redux": invalid package version undefined.
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
ravis-MacBook-Pro:test *******$
A: UPDATE
Please note that for Yarn 2+ you need to prefix the URL with package name:
yarn add otp-react-redux@https://github.com/opentripplanner/otp-react-redux#head=result-post-processor
A: You need use you git remote url and specify branch after hash(#).
yarn add https://github.com/opentripplanner/otp-react-redux.git#result-post-processor
installs a package from a remote git repository at specific git branch, git commit or git tag.
yarn add <git remote url>#<branch/commit/tag>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49992677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: JdbcPagingItemReader with SELECT FOR UDATE and SKIP LOCKED I have a multi instance application and each instance is multi threaded.
To make each thread only process rows not already fetched by another thread, I'm thinking of using pessimistic locks combined with skip locked.
My database is PostgreSQL11 and I use Spring batch.
For the spring batch part I use a classic chunk step (reader, processor, writer). The reader is a jdbcPagingItemReader.
However, I don't see how to use the pessimist lock (SELECT FOR UPDATE) and SKIP LOCKED with the jdbcPaginItemReader. And I can't find a tutorial on the net explaining simply how this is done.
Any help would be welcome.
Thank you
A: I have approached similar problem with a different pattern.
Please refer to
https://docs.spring.io/spring-batch/docs/current/reference/html/scalability.html#remoteChunking
Here you need to break job in two parts:
*
*Master
Master picks records to be processed from DB and sent a chunk as message to queue task-queue. Then wait for acknowledgement on separate queue ack-queue once it get all acknowledgements it move to next step.
*
*Slave
Slave receives the message and process it.
send acknowledgement to ack-queue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70719117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XML Schema is not validating I am working on XML and Schemas. I need help validating my schema, as when I put it in an online validator, I get an error of: S4s-elt-must-match.1: The Content Of 'sequence' Must Match (annotation?, (element | Group | Choice | Sequence | Any)*). A Problem Was Found Starting At: ComplexType.
I am using the Russian Doll design, as this seems to be the one I like the most.
catalog.xml
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<catalog xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance" xsi:noNamespaceSchemaLocation="catalog.xsd">
<photo cid="c1749" donatedBy="John Borelli">
<name metadata="tunis cooper property museum">Tunis R. Cooper property</name>
<description>
<![CDATA[
A more recent picture of the property taken by the Borelli family. The property is listed in the
National and New Jersey Registers of Historic Places.
]]>
</description>
<date>circa 1950</date>
<images>
<img src="1749a.jpg" />
</images>
</photo>
<photo cid="c1411" donatedBy="Saint Johns Catholic Church">
<name metadata="saint johns catholic church">Saint Johns Church</name>
<description>
<![CDATA[
A more recent picture of the property taken by the Borelli family. The property is listed in the
National and New Jersey Registers of Historic Places.
]]>
</description>
<date>1921</date>
</photo>
</catalog>
catalog.xsd
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="catalog">
<xs:complexType>
<xs:sequence>
<xs:element name="photo"/>
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="description" type="xs:string"/>
<xs:element name="data" type="xs:string"/>
<xs:element name="images">
<xs:complexType>
<xs:simpleContent>
<xs:element name="img"/>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:attribue name="cid" type="xs:string"/>
<xs:attribue name="donatedBy" type="xs:string"/>
<xs:attribue name="metadata" type="xs:string"/>
<xs:attribue name="src" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
A: You had a couple of errors in your XSD. And one in your XML.
To remove this one error in your XML, change the namespace in the <catalog...> element from xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance" to xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance". A simple typo.
And your XSD should look like this to validate your XML:
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="catalog">
<xs:complexType>
<xs:sequence>
<xs:element name="photo" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="name">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="metadata" type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name="description" type="xs:string"/>
<xs:element name="date" type="xs:string"/>
<xs:element name="images" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="img"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="cid" type="xs:string"/>
<xs:attribute name="donatedBy" type="xs:string"/>
<xs:attribute name="metadata" type="xs:string"/>
<xs:attribute name="src" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
What I changed was:
*
*The element photo occurs more than one time, so I added maxOccurs="unbounded"
*The element name can have an attribute, so I changed its definition to a complexType with simpleContent.
*The element images does not have to occur, hence I added minOccurs="0"
*I moved the attributes out of the xs:sequence into the xs:complexType
Now the XSD should validate your XML.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58653209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove the dots from custom menu with CSS I want to remove(hide) bullets (dots) with css code, but I can`t
Please tell me what I do wrong:
1) I give class name in my case: .no-bullets
2) I use this css code:
.no-bullets {
list-style-type: none;
}
this is not working for me...
Then I use this css in theme stylesheet:
ul
{
list-style-type: none !important;
}
again nothing...
Please help me with this, thank you in advance
A: here is my suggestion:
ul {
list-style: none;}
A: the list-style properties apply to elements with display: list-item only ,make sure your list elements doesnt have any other display style.UPDATE
seeing your link your style.css file is overriding your custom style with list-style-type: disc; you have to get rid of this line.
UPDATE 2use this code in your custom css .entry-content ul > li {
list-style-type: none !important;
}
this will do the job quickly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37094612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Click to drop widget using gwt-dnd library I'm using gwt-dnd library and I would like to know how to make click to drop.
That is, click the widget to move, release the mouse button, drag the widget and click to drop.
Thank you.
A: It's pretty big hacking. gwt-dnd handles mouse events by MouseDragHandler class and it's tightly coupled with AbstractDragController, so you must provide your own implementation of this handler (just extend it) which will call onMouseDown and onMouseUp methods on your click events. But you must also override AbstractDragController, so you end up rewriting half of the library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4259462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to avoid repeated jobs (one per core) when I'm trying to launch different threads? I'm processing multiple big independent files (same process for each file, no communication between processes). So, I have a situation that seems great for parallel multicore processing. And, in fact, I have access to a nice server (Scientific Linux -Red Hat Enterprise-) with multiple cores.
I'm trying to write some scripts with Perl in order to take profit of these cores. I tried both the threads module and Parallel::ForkManager. I launch the works to the server using sbatch, where I can define the number of tasks (cores) I will use (and the memory I will take, etc.). Nevertheless, when I launched a job selecting X number of tasks, the job is not divided between cores, but always carry out repeatedly (X times, once in each core). I'm sure I'm missing something big (and basic!) but after one week going in all the directions, I don't realize what it is. What's going wrong???
Here is a sample Perl script (test.pl):
#!/usr/bin/perl -w
use strict;
use threads;
use Benchmark qw(:hireswallclock);
my $starttime = Benchmark->new;
my $finishtime;
my $timespent;
my $num_of_threads = 4;
my @threads = initThreads();
foreach(@threads){
$_ = threads->create(\&doOperation);
}
foreach(@threads){
$_->join();
}
$finishtime = Benchmark->new;
$timespent = timediff($finishtime,$starttime);
print "\nDone!\nSpent ". timestr($timespent);
sub initThreads{
my @initThreads;
for(my $i = 1;$i<=$num_of_threads;$i++){
push(@initThreads,$i);
}
return @initThreads;
}
sub doOperation{
# Get the thread id. Allows each thread to be identified.
my $id = threads->tid();
my $i = 0;
while($i < 100000000){
$i++
}
print "Thread $id done!\n";
# Exit the thread
threads->exit();
}
And here, an example of an sbatch script used to launch it:
#!/bin/bash -x
#SBATCH --job-name=prueba
#SBATCH -e slurm-%j.out
#SBATCH --ntasks=4
#SBATCH --mem=12G
srun perl -w test.pl
The output (as I said, it seems that the whole process have been repeated once in each core):
Thread 4 done!
Thread 1 done!
Thread 1 done!
Thread 4 done!
Thread 3 done!
Thread 3 done!
Thread 1 done!
Thread 3 done!
Thread 1 done!
Thread 4 done!
Thread 4 done!
Thread 3 done!
Thread 2 done!
Thread 2 done!
Thread 2 done!
Thread 2 done!
Done!
Spent 36.1026 wallclock secs (36.02 usr + 0.00 sys = 36.02 CPU)
A: With --ntasks=4, srun will launch 4 identical Perl processes. What you want is --ntasks=1 and --cpu-per-task=4 so that Slurm allocates four cores on one node for your job.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18276484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to launch console application using CreateProcess with Minimized main window I have a native c++ windows application that is launching two child processes using the following code -
if (!CreateProcess(NULL, // No module name (use command line)
cmdLine, // szCmdline, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
false, // Set handle inheritance to FALSE
CREATE_DEFAULT_ERROR_MODE | NORMAL_PRIORITY_CLASS // Process Create Flags
NULL, // Use parent's environment block
NULL, // workingDir, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
with all parameters in STARTUPINFO block 0. This code works fine in launching the processes. However, I need to be able to launch the windows c++ console applications with their windows minimized.
If I add CREATE_NO_WINDOW to the Process Create Flags, I can launch the processes without any windows. This will be unacceptable.
In my research, there does not appear to be a way force a console application to open in a minimized mode. Is this correct?
Yes, I know that I could minimize the child application windows from within their own process, however, the other programmers on the team prefer not to do this.
A: You need to specify in the STARTUPINFO structure that you want your console window to be initially minimized:
ZeroMemory(&si);
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_MINIMIZE;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4380575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: UITableViewCell Not Sizing To UIImageView I was wondering if anyone knows hot to fix this issue. When I run the app, the image gets cut off instead of displayed. I have attached photos to show in detail.
A: Since you have two kind of Cells in the Table View, you have to set the height of both cells programatically inside heightForRowAtIndexPath.
Currently, you have only one cell size and I think it is default to 44.0.
A: May be you doesn't set imageview's constraints properly.
Set top, bottom, left, rignt constraint of imageview with tableviewcell frame properly. Give a aspect ratio size of the imageview.
And return UITableViewAutomaticDimension from heightForRowAtIndexPath and estimatedHeightForRowAtIndexPath delegate functions.
This will work !!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39196432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# Deserialize XML to correct class type I am using the XmlSerializer to do some serialization work. I was wondering if it is possible to "generically" deserialize from the XmlDocuement.
Concrete: If I have an XML File I would watch the tag and compare it with my DTO Model. Is this possible (better: Does .NET support this?) ? Maybe using an XSD file or something?
Example (without generic deserialization):
XmlDocument myDocument = new XmlDocument();
myDocument.Load(xml);
MemoryStream stream = new MemoryStream();
myDocument.Save(stream);
// Here I would like to use an interface instead and load the correct type of object.
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
MyClass myObject;
serializer.Serialize(stream, myObject);
A: The only way is that you pre parse the xml file so you understand the class to create.
You could also write somewhere (in the file extension? in an attribute of the first element of the doc?) the class type.
When you have the class type you can create the right class via a switch statement (converting a string to a type) or via reflection (better).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24671538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP and an int with a value of 200 being treated as 2 100%, to declare another variable I have quite an original problem and am unsure how I can achieve it in the best way.
I have a variable let us say that it is called percent, it is an int that can hold any value between 0 - 200.
While the number of percent is not more than 100, it is treated as a percent to work out another variable, let us say that for each 1% you get 2 apples.
$percent = 89;
$apples = $percent*2;
While the number of percent is more than 100 upto the value of 200, it should work in reverse. So if percent equaled to 101 it should act as 99%.
Basically how can I easily calculate the amount of apples from percent which is an int ranging from 0-200, when I need the number to act like below...
If percent equals 0-99
Acts as a normal percentage value
If percent equals 100
The max value for apples
If percent equals 101-200
For each increment over 100, it should take from the max value of apples.
I think I explained it good enough,
Thanks.
A: Try 100 - abs(100 - $percent).
abs(100 - $percent) gives you the distance between the two values. It is 1 for both 99 and 101.
Subtracting this distance from 100 gives you the desired ouput.
A: I think that the elegant mathematical approach is the following:
$true_percent = 100 - abs(100 - $percent);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8370507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to verify the current page is a collection page with Javascript in Shopify I know you can check the template with liquid to check if a template is a collection template. However, I need to check if the template is a collection template with JS in a main JS file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73116368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Selenium - get all child elements from div class I want to get the values contained in the span class with value "indigo-text descfont" for the following:
<div id="WineDetailContent"> event
<span class="blue-text codefont">...</span>
<span class="indigo-text descfont">Alsace</span>
<br>
<span class="blue-text codefont">...</span>
<span class="indigo-text descfont">2014</span>
<br>
</div>
So that I get Alsace and 2014.
I have tried using the following:
details = driver.find_element_by_xpath("//div[starts-with(@id,'WineDetailContent')]")
res = details.find_element_by_xpath("//span[starts-with(@class,'indigo-text descfont')]")
print(res.text)
But it only returns the first needed value, i.e. Alsace.
How is it possible to get 2014 as well?
A: As per the HTML:
<div id="WineDetailContent">
...
<span class="indigo-text descfont">Alsace</span>
<br>
...
<span class="indigo-text descfont">2014</span>
<br>
</div>
Both the desired texts are within the decendants <span class="indigo-text descfont"> of their ancestor <div id="WineDetailContent">
Solution
To print the texts from the <span class="indigo-text descfont"> elements you can use list comprehension and you can use either of the following locator strategies:
*
*Using CSS_SELECTOR:
print([my_elem.text for my_elem in driver.find_elements(By.CSS_SELECTOR, "div#WineDetailContent span.indigo-text.descfont")])
*Using XPATH:
print([my_elem.text for my_elem in driver.find_elements(By.XPATH, "//div[@id='WineDetailContent']//span[@class='indigo-text descfont']")])
A: find_element_by_xpath return single WebElement. You need to use find_elements_by_xpath to select both elements:
details = driver.find_element_by_xpath("//div[@id ='WineDetailContent']")
res = details.find_elements_by_xpath("./span[@class = 'indigo-text descfont']")
for i in res:
print(i.text)
A: I assume you are missing an (s) in find element, you need to use find_elements.
In general when we apply find element
element.find_element_by_xxxx(selector)
we will get back the first element that matches our selector.
however in case of more items you can use find elements
element.find_elements_by_xxxx(selector)
the find elements will return a list of all elements that matches our selector.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73223578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: docker how to commit but exclude directory from image I have running docker container and I want to commit the changes on that container, but the size of one of the directories is very huge and I want to exclude it from the snapshot.
How to commit changes on that container while excluding a directory from that image?
A: Container's volumes won't be saved when you commit a container as an image. So you can take advanced of this to exclude a folder (volume) from the snapshot. For example, suppose you want to exclude dir /my-videos from your image when committing. You can run your container mounting /my-videos as a volume:
docker run -i -t -v /my-videos my_container /bin/bash
or you mount a host's folder in container's /my-videos:
docker run -i -t -v /home/user/videos:/my-videos my_container /bin/bash
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29740079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Database design for school management to keep track of current and previous school years What's the best way to design a students registration records and keep tracks of previous academic years?
I have a table to enroll students, something like this:
CREATE TABLE [dbo].[Students] (
[StudentID] INT IDENTITY (1, 1) NOT NULL,
[StudentNumber] NVARCHAR (50) NOT NULL,
[EnrolmentDate] DATE NULL,
[Class] NVARCHAR (50) NOT NULL,
[StudentSurname] NVARCHAR (60) NOT NULL,
[StudentFirstNames] NVARCHAR (60) NOT NULL,
[FatherSurname] NVARCHAR (100) NULL,
[FatherNames] NVARCHAR (100) NULL,
[MotherSurname] NVARCHAR (100) NULL,
[MotherNames] NVARCHAR (100) NULL,
[SchoolYear] NVARCHAR (50) NOT NULL,
[StudentPicture] VARBINARY (MAX) NULL,
CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED ([StudentID] ASC),
CONSTRAINT [IX_Students] UNIQUE NONCLUSTERED ([StudentNumber] ASC),
CONSTRAINT [FK_Students_AcademicYear] FOREIGN KEY ([SchoolYear]) REFERENCES [dbo].[AcademicYear] ([SchoolYear]) ON UPDATE CASCADE
);
I also have other tables for SchoolFees, MarksEntry, SchoolYear, etc.
So far everything works well for current year, I an just select where SchoolYear = current year, whether it's list of students, ,marks or fees paid/unpaid.
The challenge is to access data from previous years, I haven't figured out how to design the database or add a column to keep track of previous year.
When a student passes the exam, he/she promoted to a different class, so what I update in the Students table is: Class and SchoolYear, the rest of data remain the same like student number and other details.
So if I have a student in class 1B in school year 2020-2021 and promote to class 2B in year 2021-2022, the records of this student in class 1B in 2020-2021 are still in database but no longer accessible because that student no longer exist, their records have been modified.
What's the best and easy solution not to duplicate a student records but somewhat keep track of previous classes and school years when promoting a student to a different class?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67676113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: QTableWidget - Drag and Drop a Button into a cell in the QTableWidget When i drag and drop the button into the QTableWidget, the button disappers from the old position and nothing is displayed in the cell where i drop the button.
Could anyone suggest what's the problem?
Please find below the code
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class Button(QtGui.QPushButton):
def __init__(self, title, parent):
super(Button, self).__init__(title, parent)
def mouseMoveEvent(self, e):
if e.buttons() != QtCore.Qt.RightButton:
return
mimeData = QtCore.QMimeData()
drag = QtGui.QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.pos() - self.rect().topLeft())
dropAction = drag.start(QtCore.Qt.MoveAction)
def mousePressEvent(self, e):
if e.button() == QtCore.Qt.LeftButton:
print 'Left Button Pressed'
class MyTable(QtGui.QTableWidget):
def __init__(self, rows, columns, butObject, parent):
super(MyTable, self).__init__(rows, columns, parent)
self.setAcceptDrops(True)
self.butObject = butObject
def dragEnterEvent(self, e):
e.accept()
def dropEvent(self, e):
position = e.pos()
print position
self.butObject.move(position)
e.setDropAction(QtCore.Qt.MoveAction)
e.accept()
def dragMoveEvent(self, e):
e.accept()
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setAcceptDrops(True)
self.button = Button('Button', self)
self.button.move(50, 200)
self.table = MyTable(2, 2, self.button, self)
self.table.setAcceptDrops(True)
self.table.setDragEnabled(True)
self.setWindowTitle('Click or Move')
#self.setGeometry(300, 300, 280, 150)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
app.exec_()
if __name__ == '__main__':
main()
A: When you drop the button into the table, does the 'print position' work? It should be printing out the coords of the drop position to your shell.
I think you need to use those to then insert the button into the table.
Got it working - change your drop event to this:
position = e.pos()
print position
row = self.rowAt(position.y())
column = self.columnAt(position.x())
self.setCellWidget(row,column,self.butObject)
e.setDropAction(QtCore.Qt.MoveAction)
e.accept()
Cheers
Dave
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10524178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Angular 6 component re-binding I have an Angular Component named Dashboard. This component displays a dashboard page with data. I also have a menu component. When I am in the dashboard page, I click on a menu item and it opens up a popup screen. The popup is nothing but a hidden div that can be made visible/invisible. I added a new transaction item in this pop up, saving it to the database and closing the popup after displaying an information alert.
What I wanted is to ensure the dashboard is able to refresh or rebind with the newly added data immediately after hitting save in the pop up.
I tried the following:
1) Use Router.Navigate. My browser URL was always localhost:4200/Dashboard and this code does not seem to reload the route
saveTransaction() {
this.addTnxBtn = true;
this.services.addTransaction(this.newTnx).subscribe((data) => {
if (data.mStatus == "Success") {
this.success = true;
this.addTnxBtn = false;
this.Failed = false;
this.router.navigate(['/dashboard']);
} else {
this.success = false;
this.Failed = true
this.addTnxBtn = false;
}
})
}
2) Recreate the Dashboard component and call the function to re-bind. The dbcomponent.ngOnInit is supposed to call api service and rebind the data to Dashboard
saveTransaction() {
this.addTnxBtn = true;
this.services.addNewSwiftTransaction(this.newTnx).subscribe((data) => {
if (data.mStatus == "Success") {
this.success = true;
this.addTnxBtn = false;
this.Failed = false;
let dbcomponent = new DashboardComponent(this.services);
dbcomponent.ngOnInit();
} else {
this.success = false;
this.Failed = true
this.addTnxBtn = false;
}
})
}
ngOnInit() {
this.count = new dashboardClass()
this.services.getDashboardCount().subscribe((data) => {
if (data.mStatus == "Success") {
this.dashData = data.responseData
} else {
console.log(data.mStatus)
}
})
}
So I am stuck with the question can I refer already loaded Dashboard component from my menu component? Are there any other ways to reload a component again to do rebind?
A: What you need is communication between the components.
*
*Create a service with a BehaviourSubject and subscribe it in the Dashboard component where in you can fetch the response again.
*Whenever you add a new record from the modal, emit the value and you will get a hit in dashboard where you have subscribed to get the grid data again.
This way you won't have to reload the page also.
A: After doing your stuff you can use Router.Navigate as used below:
constructor() {private _router: Router}
this._router.routeReuseStrategy.shouldReuseRoute = () => {
return false;
}; // to reload your component on same page
this._router.navigate(['/fsf']); // this will work
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62467243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby string.scan(/#{regexp_pattern}/) - execution time Problem:
ruby .scan with regex pattern taking up to 5 minutes. Time depends on string that are scanning.
Tests run on ruby '2.5.1', and ruby '2.4.2'.
Examples:
def time_regexp_test(string)
start = Time.now
puts "parse start: #{start}"
regexp_pattern = "[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?"
email = string.scan(/#{regexp_pattern}/).flatten.last
finish = Time.now
puts "parse finish: #{finish}"
puts "total #{(finish-start).to_s}"
email
end
strings = [
'"Test test Real Estate - Test\'s International Real Estate" <[email protected]>',
'"Test test Real Estate - Christie\'s International Real Estate" <[email protected]>',
'"Test test Real Estate - Christie\'s International Real Estate"',
'"Test test Real Estate - Christie\'s International Real Estate" t@',
'"Test test Real Estate - testtesttest\'s International Real Estate" <[email protected]>',
'"testtesttest\'s" <[email protected]>',
'testtesttest\'s <[email protected]>'
]
strings.each_with_index do |string, n|
puts "Test # #{n}"
puts "Input: #{string}"
time_regexp_test(string)
end
Result:
Test # 0
Input: "Test test Real Estate - Test's International Real Estate" <[email protected]>
parse start: 2018-04-19 17:43:26 +0200
parse finish: 2018-04-19 17:43:29 +0200
total 3.630606
Test # 1
Input: "Test test Real Estate - Christie's International Real Estate" <[email protected]>
parse start: 2018-04-19 17:43:29 +0200
parse finish: 2018-04-19 17:43:54 +0200
total 24.119056
Test # 2
Input: "Test test Real Estate - Christie's International Real Estate"
parse start: 2018-04-19 17:43:54 +0200
parse finish: 2018-04-19 17:43:54 +0200
total 0.000256
Test # 3
Input: "Test test Real Estate - Christie's International Real Estate" t@
parse start: 2018-04-19 17:43:54 +0200
parse finish: 2018-04-19 17:44:06 +0200
total 12.093272
Test # 4
Input: "Test test Real Estate - testtesttest's International Real Estate" <[email protected]>
parse start: 2018-04-19 17:44:06 +0200
parse finish: 2018-04-19 17:46:51 +0200
total 165.338206
Test # 5
Input: "testtesttest's" <[email protected]>
parse start: 2018-04-19 17:46:51 +0200
parse finish: 2018-04-19 17:46:51 +0200
total 0.000385
Test # 6
Input: testtesttest's <[email protected]>
parse start: 2018-04-19 17:46:51 +0200
parse finish: 2018-04-19 17:46:51 +0200
total 0.000369
We can see, that times of parsing some strings are incredibly huge (Test # 4).
Time is rising if we add some part of email address with @ character, and also rising if add characters to word with ' character.
Testing this regexp in https://regexr.com/3o721 - all working fast.
Where can be the problem?
Update:
Playing with deleting characters shows that delete of '-' character making parsing much faster ( 165.338206 -> 0.578216 ).
But Why?
string = '"Test test Real Estate - testtesttest\'s International Real Estate" <[email protected]>'
time_regexp_test(string.delete("-"))
parse start: 2018-04-19 18:17:21 +0200
parse finish: 2018-04-19 18:17:22 +0200
total 0.578216
A: You need to properly escape the dot.
Either
regexp_pattern = '[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?'
email = string.scan(/#{regexp_pattern}/).flatten.last
Or
regexp_pattern = /[a-zA-Z0-9!#\$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#\$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/
email = string.scan(regexp_pattern).flatten.last
Else, your "\." is parsed by the Ruby engine as a mere . that matches any character but a line break char by the Onigmo regex engine, and you get tripped up in the classical catastrophic backtracking.
If you want to reproduce the same behavior in the regex tester as you have in the Ruby code, just remove a backslash before the dots in your pattern.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49925688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Problems with netlink socket, kernel opps 0002 I try to send some data from user mode to my kernel module. But when it send something, it triggers a kernel error:
Bug:unable to handle kernel paging request ad ffff88022f168bc0
IP: [<...>]build_skb+0xf5/0x1c0
#include "socket.hpp"
using namespace std;
KernelSocket::KernelSocket(DataLink * dl){
this->dl = dl;
this->sock_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_USER);
if(sock_fd<0) {
printf("unable to create socket%d\n", sock_fd);
exit(-1);
}
memset(&src_addr, 0, sizeof(src_addr));
src_addr.nl_family = AF_NETLINK;
src_addr.nl_pid = getpid();
//src_addr.nl_groups = 0;
bind(sock_fd, (struct sockaddr*)&src_addr, sizeof(src_addr));
memset(&dest_addr, 0, sizeof(dest_addr));
memset(&dest_addr, 0, sizeof(dest_addr));
dest_addr.nl_family = AF_NETLINK;
dest_addr.nl_pid = 0;
dest_addr.nl_groups = 0;
nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
memset(nlh,0,NLMSG_SPACE(MAX_PAYLOAD));
nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
nlh->nlmsg_pid = getpid();
nlh->nlmsg_flags = 0;
reportLocalAddress();
}
void KernelSocket::sendToKernel(string data){
int length = data.length();
char c;
c = (length%0xff);
data.insert(0, 1, c);
c = (length/0xff);
data.insert(0, 1, c);
nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
nlh->nlmsg_pid = getpid();
nlh->nlmsg_flags = 0;
memcpy((NLMSG_DATA(nlh)), data.c_str(), length+2);
iov.iov_base = (void *)nlh;
iov.iov_len = nlh->nlmsg_len;
//iov.iov_len = length;
msg.msg_name = (void *)&dest_addr;
msg.msg_namelen = sizeof(dest_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
sendmsg(sock_fd,&msg,0);
}
void KernelSocket::reportLocalAddress(){
int length = 6;
string data = dl->localAddress.toString();
data.insert(0,1, 0xff);
data.insert(0,1, 0xff);
nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
nlh->nlmsg_pid = getpid();
nlh->nlmsg_flags = 0;
memcpy((NLMSG_DATA(nlh)), data.c_str(), length+2);
iov.iov_base = (void *)nlh;
iov.iov_len = nlh->nlmsg_len;
msg.msg_name = (void *)&dest_addr;
msg.msg_namelen = sizeof(dest_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
sendmsg(sock_fd,&msg,0);
printf("send mac address to kernel\n");
}
void * kernelSocketWorkLoop(void * kernelSocket){
int length,ret;
KernelSocket * ks = (KernelSocket *) kernelSocket;
while(1){
ret = recvmsg(ks->sock_fd, &(ks->msg), MSG_DONTWAIT);
if(ret>=0){
string c;
c.assign((char *)NLMSG_DATA(ks->nlh));
length = c[0]*0xff+c[1];
ks->dl->packetDownBuffer.push(c);
}
sleep(1);
}
}
I am using this period code now. Anybody have opinion on this problem? Thanks~
Here is the function in the kernel module that I use to receive message.
static void ss_recv(struct sk_buff *skb){
struct nlmsghdr *nlh;
int len;
char * c;
struct uwmodem_priv* priv = NULL;
priv = netdev_priv(dev);
printk("in ss_recv\n");
nlh = (struct nlmsghdr *)skb->data;
if(nlh->nlmsg_pid>0){
priv->daemon_pid = nlh->nlmsg_pid;
len = nlh->nlmsg_len - NLMSG_HDRLEN;
c = kmalloc(len, GFP_ATOMIC);
if(c==NULL){
printk("Fail to allocate c\n");
}
memcpy(c, nlmsg_data(nlh), len);
if(c[0]==0xff && c[1]==0xff){
printk("Set MacAddress(%d) \n", nlh->nlmsg_pid);
//for mac address
memcpy(dev->dev_addr, c+2, ETH_ALEN);
}else{
len = c[0]*0xff+c[1];
//printk("Kernel Length:[%d][%d][%d]\n", c[0], c[1], c[2]);
printk("Kernel received from (%d)[%d]: \n", nlh->nlmsg_pid,len);
uwmodem_rx(dev, c+2, len);
}
kfree(c);
}
//printk("Exit ss_recv\n");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14738580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Shopify Public App - How To Get Key, Token & Url I am totally new to Shopify Public App development and I will need your help to understand it a bit better.
For a client, I need to build a Shopify Public App that will be used by several Merchants.
This application will have to access the Merchants' store via the Admin API.
If my understanding is correct, in order to access one specific Merchant's store via the Admin API, I need to have 3 pieces of information from that Merchant's store: the Public API Key, Token and URL.
Now, my question:
When the Shopify Public App is installed by a Merchant, how does my app get these 3 pieces of information (specific to that particular merchant) ?
Is there any "magic" trick? Does the Merchant need to input this info? ...
In advance, many thanks for your help
A: Each merchant will need to install your app. In the installation phase shopify will pass, as an argument, the access token, that is a token that you will need, to use the Admin API.
If we're talking about an embedded app is expected that every request made is authenticated.
Depending on which kind of app you want to create (embedded or not) and language you may want to use, using the Shopify Cli to create the first draft of the app is really reccommended. It will create the base to have an installable app. Here is the documentation https://shopify.dev/apps/getting-started/create
You need to install the Shopify Cli and then run
shopify app create (node | ruby | php)
depending on your language of choice.
A: For those who might be interested, I finally found the link to the information.
Shopify - Getting started with OAuth
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72498355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting address of pointer from a method returning pointer Suppose I have:
class Map {
public:
Map();
vector<Territory>* getTerritories();
};
vector<Territory>* Map::getTerritories()
{
vector<Territory> t;
for (int i = 0; i < 8; i++) {
Territory ter;
ter.setName("Territory " + std::to_string(i + 1));
t.push_back(ter);
}
return &t;
}
Now in another class, I want to get the same vector I created in the getTerritories() method.
Here's how:
void GameSetup::assignTerritories()
{
vector<Territory> * generatedTeritories = (*map).getTerritories(); // dereferenced
}
I'm not getting a compiler error because they're both pointers. But somehow I cannot seem to access my Territory objects within my vector by simple iteration like you would normally do over a vector.
At this point, (*map).getTerritories() gets a pointer to my territory vector (if I try to follow). Now suppose I want to make an 'alias' of some sort of this pointer I'm returning, how would I do so? Is it possible to get the address of a pointer? I asked myself this question and tried the following:
vector<Territory> * generatedTeritories = &(map->getTerritories());
but that obviously didn't work. I'm not sure what else to do and I've been going in circles.
A: Please, forget pointers here. getTerritories() was returning a pointer to a local object. This object is destroyed after the function return. You just need to return the object and you'll then find in back in your generatedTeritories variable.
class Map {
public:
Map();
vector<Territory> getTerritories();
};
vector<Territory> Map::getTerritories()
{
vector<Territory> t;
for (int i = 0; i < 8; i++) {
Territory ter;
ter.setName("Territory " + std::to_string(i + 1));
t.push_back(ter);
}
return t;
}
void GameSetup::assignTerritories()
{
vector<Territory> generatedTeritories = (*map).getTerritories(); // dereferenced
}
Now you can get the address of the vector like that:
vector<Territory>* addressOfGeneratedTeritories = &generatedTeritories;
But it's only safe to use it while generatedTeritories remains alive (in the code above, it's alive untill assignTerritories() execution ends as it is a local variable of this function). To make it persistent, it has to be an attribute of another object...it will then remain alive untill the parent object gets destroyed...and so on. It could allso be a global variable which is definitely not recommended (it's a bad practice, object oriented design always have alternatives to that).
BTW, I would recommend that you follow some tutorials about C++ before starting to code a game.....;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32925974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the reliable way to get all entries of the Elasticsearch index (in Java with Rest client) As far as I understand the server and its Java Highlevel Rest client make me use paging when retrieving long sets:
_query = QueryBuilders.matchAllQuery();
SearchRequest sr = new SearchRequest(_index);
SearchSourceBuilder ssb = new SearchSourceBuilder();
ssb.from(_from);
ssb.size(_count);
ssb.query(_query);
sr.source(ssb);
SearchResponse response;
try {
response = Factory.DB.search(sr);
So if I omit size, it will fall back to a default 10 or something.
This seems to me a bit unreliable because when I try to query the next "from-to" page, a lot of entries may be removed or added.
Is there a way to get all results at once no matter how big the resultset is?
(implying the server will use some streamish manner to serve the long resultset without being out of memory)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50513849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to run each sampler in parallel with same csv data Need to run these sampler request in parallel with same csv file provided
CSV have LN,Userid columns that with three values
I want to run all three samplers at same time for each values. So total would be 9 requests ( 3 values ins CSV)
Submit1|Submit2|Submit3 (all should run in parallel for same userid's in csv)
(for value Userid1) | for value Userid2 | Userid3
Submit1 | Submit1 | Submit1
Submit2 | Submit2 | Submit2
Submit3 | Submit3 | Submit3
A: Did able to manage by setting csv for all Threads and Recycle on EOF = True and Stop at EOF to False.
When used No of threads to 3, It reaches 18 instead was expecting 9 only
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65010656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Triger Pipeline on any Pull Request from any branch and feature branches I have pipeline for some backend app for example, I would like to create trigger that run the pipeline whenever a pull request is created (before the approve and merge) but not only for the main/master branch, also for any branches
For example if I create a pull request from branch side branch "abc" to side branch "xyz" the pipeline will be triggered and run.
Also if in the feature I will create branch with the name "foobar" and create pull request to some other side branch the pipeline will be created.
How can I achieve that ?
A: In the DevOps git repo, PR syntax is invalid.
The only way you can trigger the pipeline via PR in DevOps is through branch settings.
1, Go to branch settings.
2, Add a build validation policy for all of the branches.
https://learn.microsoft.com/en-us/azure/devops/pipelines/repos/azure-repos-git?view=azure-devops&tabs=yaml#pr-triggers
A: You can do that with pr triggers. You can include which branches do you want to trigger a build. In the below example when you create a pull request for current branch the pipeline will run. You can also use regex syntax like feature/*
trigger:
pr:
branches:
include:
- current
- xyz
exclude:
- uat
https://blog.geralexgr.com/devops/build-triggers-on-azure-devops-pipelines
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73192273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Improve performance of count and sum when already indexed First, here is the query I have:
SELECT
COUNT(*) as velocity_count,
SUM(`disbursements`.`amount`) as summation_amount
FROM `disbursements`
WHERE
`disbursements`.`accumulation_hash` = '40ad7f250cf23919bd8cc4619850a40444c5e90c978f88635a09ccf66a82ffb38e39ea51cdfd651b0ebdac5f5ca37cd7a17e0f60fea6cbce1397ccff5fa37346'
AND `disbursements`.`caller_id` = 1
AND `disbursements`.`active` = 1
AND (version_hash != '86b4111677294b27a1805643d193b8d437b6ddb170b4ed5dec39aa89bf070d160cbbcd697dfc1988efea8429b1f1557625bf956180c65d3dcd3a318280e0d2da')
AND (`disbursements`.`created_at` BETWEEN '2012-12-15 23:33:22'
AND '2013-01-14 23:33:22') LIMIT 1
Explain extended returns the following:
+----+-------------+---------------+-------+-----------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+---------+------+--------+----------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+---------------+-------+-----------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+---------+------+--------+----------+--------------------------+
| 1 | SIMPLE | disbursements | range | unique_request_index,index_disbursements_on_caller_id,disbursement_summation_index,disbursement_velocity_index,disbursement_version_out_index | disbursement_summation_index | 1543 | NULL | 191422 | 100.00 | Using where; Using index |
+----+-------------+---------------+-------+-----------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+---------+------+--------+----------+--------------------------+
The actual query counts about 95,000 rows. If I explain another query that hits ~50 rows the explain is identical, just with fewer rows estimated.
The index being chosen covers accumulation_hash, caller_id, active, version_hash, created_at, amount in that order.
I've tried playing around with doing COUNT(id) or COUNT(caller_id) since these are non-null fields and return the same thing as count(*), but it doesn't have any impact on the plan or the run time of the actual query.
This is also a heavy insert table, essentially every single query will have had a row inserted or updated since the last time it was run, so the mysql query cache isn't entirely useful.
Before I go and make some sort of bucketed time sequence cache with something like memcache or redis, is there an obvious solution to getting this to work much faster? A normal ~50 row query returns in 5MS, the ones across 90k+ rows are taking 500-900MS and I really can't afford anything much past 100MS.
I should point out the dates are a rolling 30 day window that needs to be essentially real time. Expiration could probably happen with ~1 minute granularity, but new items need to be seen immediately upon commit. I'm also on RDS, Read IOPS are essentially 0, and cpu is about 60-80%. When I'm not querying the giant 90,000+ record items, CPU typically stays below 10%.
A: You could try an index that has created_at before version_hash (might get a better shot at having an index range scan... not clear how that non-equality predicate on the version_hash affects the plan, but I suspect it disables a range scan on the created_at column.
Other than that, the query and the index look about as good as you are going to get, the EXPLAIN output shows the query being satisfied from the index.
And the performance of the statement doesn't sound too unreasonable, given that it's aggregating 95,000+ rows, especially given the key length of 1543 bytes. That's a much larger size than I normally deal with.
What are the datatypes of the columns in the index, and what is the cluster key or primary key?
accumulation_hash - 128-character representation of 512-bit value
caller_id - integer or numeric (?)
active - integer or numeric (?)
version_hash - another 128-characters
created_at - datetime (8bytes) or timestamp (4bytes)
amount - numeric or integer
95,000 rows at 1543 bytes each is on the order of 140MB of data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14329000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cannot pass std::vector to winrt::array_view I trying to consume Windows::Gaming::Input::RawGameController via C++/WinRT library.
Calling RawGameController::GetCurrentReading() to acquire current controller state:
std::vector<bool> buttonsArray(rawController.ButtonCount(), false);
std::vector<GameControllerSwitchPosition> switchesArray(rawController.SwitchCount(), GameControllerSwitchPosition::Center);
std::vector<double> axisArray(rawController.AxisCount(), 0.0);
uint64_t timestamp = rawController.GetCurrentReading(buttonsArray, switchesArray, axisArray);
And have compile error:
1>------ Build started: Project: cppwinrtgamepad, Configuration: Debug x64 ------
1>cppwinrtgamepad.cpp
1>c:\somepath\x64\debug\generated files\winrt\base.h(3458): error C2039: 'data': is not a member of 'std::vector<T,std::allocator<_Ty>>'
1> with
1> [
1> T=bool,
1> _Ty=bool
1> ]
1>c:\somepath\x64\debug\generated files\winrt\base.h(3663): note: see declaration of 'std::vector<T,std::allocator<_Ty>>'
1> with
1> [
1> T=bool,
1> _Ty=bool
1> ]
1>c:\somepath\cppwinrtgamepad.cpp(121): note: see reference to function template instantiation 'winrt::array_view<T>::array_view<T>(std::vector<T,std::allocator<_Ty>> &) noexcept' being compiled
1> with
1> [
1> T=bool,
1> _Ty=bool
1> ]
1>c:\somepath\cppwinrtgamepad.cpp(121): note: see reference to function template instantiation 'winrt::array_view<T>::array_view<T>(std::vector<T,std::allocator<_Ty>> &) noexcept' being compiled
1> with
1> [
1> T=bool,
1> _Ty=bool
1> ]
1>c:\somepath\cppwinrtgamepad.cpp(90): note: see reference to class template instantiation 'winrt::impl::fast_iterator<winrt::Windows::Foundation::Collections::IVectorView<winrt::Windows::Gaming::Input::Gamepad>>' being compiled
1>c:\somepath\x64\debug\generated files\winrt\base.h(7801): note: see reference to class template instantiation 'winrt::com_ptr<winrt::impl::IContextCallback>' being compiled
1>c:\somepath\x64\debug\generated files\winrt\base.h(7573): note: see reference to class template instantiation 'winrt::com_ptr<winrt::impl::IServerSecurity>' being compiled
1>c:\somepath\x64\debug\generated files\winrt\base.h(7532): note: see reference to class template instantiation 'std::chrono::time_point<winrt::clock,winrt::Windows::Foundation::TimeSpan>' being compiled
1>c:\somepath\x64\debug\generated files\winrt\base.h(5264): note: see reference to class template instantiation 'winrt::com_ptr<winrt::impl::IMarshal>' being compiled
1>c:\somepath\x64\debug\generated files\winrt\base.h(2503): note: see reference to class template instantiation 'winrt::com_ptr<To>' being compiled
1> with
1> [
1> To=winrt::impl::ILanguageExceptionErrorInfo2
1> ]
1>c:\somepath\x64\debug\generated files\winrt\base.h(4120): note: see reference to function template instantiation 'winrt::com_ptr<To> winrt::com_ptr<winrt::impl::IRestrictedErrorInfo>::try_as<winrt::impl::ILanguageExceptionErrorInfo2>(void) noexcept const' being compiled
1> with
1> [
1> To=winrt::impl::ILanguageExceptionErrorInfo2
1> ]
1>c:\somepath\x64\debug\generated files\winrt\base.h(4202): note: see reference to class template instantiation 'winrt::com_ptr<winrt::impl::IRestrictedErrorInfo>' being compiled
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.16.27023\include\string_view(39): note: see reference to class template instantiation 'std::basic_string_view<wchar_t,std::char_traits<wchar_t>>' being compiled
1>c:\somepath\x64\debug\generated files\winrt\base.h(3458): error C2664: 'winrt::array_view<T>::array_view(winrt::array_view<T> &&)': cannot convert argument 1 from 'winrt::array_view<T>::size_type' to 'std::initializer_list<bool>'
1> with
1> [
1> T=bool
1> ]
1>c:\somepath\x64\debug\generated files\winrt\base.h(3459): note: No constructor could take the source type, or constructor overload resolution was ambiguous
1>Done building project "cppwinrtgamepad.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
GetCurrentReading() is defined in winrt/Windows.Gaming.Input.h like this:
template <typename D> uint64_t consume_Windows_Gaming_Input_IRawGameController<D>::GetCurrentReading(array_view<bool> buttonArray, array_view<Windows::Gaming::Input::GameControllerSwitchPosition> switchArray, array_view<double> axisArray) const
And corresponding winrt::array_view constructor is defined in winrt/base.h like this:
template <typename C>
array_view(std::vector<C>& value) noexcept :
array_view(value.data(), static_cast<size_type>(value.size()))
{}
Looks like oblivious bug considering that std::vector<bool> doesn't contrain data() method at all.
Or there is other recommended way to call RawGameController::GetCurrentReading()?
PS: as a workaround I could use std::array<bool, SOME_BIG_BUTTTON_COUNT> but its so ugly.
A: This is by design. The winrt::array_view is an adapter that tells the underlying API that the bound array or storage has the appropriate binary layout to receive the data efficiently (typically via a memcpy) without some kind of transformation. std::vector<bool> does not provide that guarantee and thus cannot be used. You might want to try something else like a std::array or some other contiguous container.
A: Ugly workaround instead of using vector<bool>:
int32_t buttons = rawController.ButtonCount();
int32_t switches = rawController.SwitchCount();
int32_t axis = rawController.AxisCount();
std::unique_ptr<bool[]> buttonsArray = std::make_unique<bool[]>(buttons);
std::vector<GameControllerSwitchPosition> switchesArray(switches);
std::vector<double> axisArray(axis);
uint64_t timestamp = rawController.GetCurrentReading(winrt::array_view<bool>(buttonsArray.get(), buttonsArray.get() + buttons), switchesArray, axisArray);
A: Each element in std::vector<bool> occupies a single bit instead of sizeof(bool) bytes.It does not necessarily store its elements as a contiguous array and thus doesn't contain data() method.I have a working code, but it is not the optimal solution.You can try to create bool array by using bool b[] method.
bool buttonsArray[]{ rawController.ButtonCount(), false };
std::vector<GameControllerSwitchPosition> switchesArray(rawController.SwitchCount(), GameControllerSwitchPosition::Center);
std::vector<double> axisArray(rawController.AxisCount(), 0.0);
uint64_t timestamp = rawController.GetCurrentReading(buttonsArray, switchesArray, axisArray);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57059598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Run a java program from svn in Jenkins I have a job on Jenkins that runs the functional tests and generates test results. After i get results I need to run a new job that will trigger a java program from svn. What the program does it updated test results in bug tracking datebase. My question is how to setup a new job on Jenkins that will trigger java program? Do I need some kind script? All suggestions are welcome. Thx
A: Create a job which checks out stuff from svn, like you would do for a job that does compilation.
Then create Excecute Windows batch command or Execute shell build step, where you put the command to run the java program, probably java -jar ....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12965481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Any possible way to get the locale with language and region in angular? Is there any way in angular to get the locale with region?
I know i can inject the locale id into components but most of the time i just get the language tag, i.e "en" when i need "en-US".
There are some functions in angular that i've looked at but none of them seem to be able to return a string in the language-region format.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71743145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails/ActiveRecord Model.Find returns the wrong record This is the wackiest.
When I visit:
/ingredients/14.json
I get
{ id: 13,
name: "Tomato",
category: "Vegetable",
created_at: "2013-11-20T04:35:36.704Z",
updated_at: "2013-11-20T05:59:34.444Z"
}
And in the logs:
Started GET "/ingredients/14.json" for 127.0.0.1 at 2013-11-19 22:02:35 -0800
Processing by IngredientsController#show as JSON
Parameters: {"id"=>"14"}
Ingredient Load (0.4ms) SELECT "ingredients".* FROM "ingredients" WHERE (14) LIMIT 1
#<Ingredient id: 13, name: "Tomato", category: "Vegetable", created_at: "2013-11-20 04:35:36", updated_at: "2013-11-20 05:59:34">
Completed 200 OK in 18ms (Views: 0.2ms | ActiveRecord: 0.6ms)
There are only two items in the database, #13 (tomato) and #14 (egg).
I'm using:
*
*Rails 4.0.0
*SQLite (it's a brand new app :)
*ActiveModel::Serializers (although I found the same result when I removed the gem and the serializers)
*Powder (but this continues after powder restart!)
*Batman.js (but this occurs when Batman requests JSON and when I visit the URL with my browser)
*Chrome (although it also happens in Safari and in Chrome Incognito)
I have no idea what this could be? Any guesses?!
Update
It was just me being an idiot. Check out my bad controller action code:
def show
@resource = @class.find_by(params[:id])
respond_with @resource
end
of course, this should be:
def show
@resource = @class.find(params[:id])
respond_with @resource
end
Thank you!
A: Yes, your generate SQL is wrong. The query generated is:
SELECT "ingredients".* FROM "ingredients" WHERE (14) LIMIT 1
whereas it should have been:
SELECT "ingredients".* FROM "ingredients" WHERE id = 14 LIMIT 1
Since the condition in the first where clause always evaluates to true, it picks up 1 row randomly. Which row gets picked up depends on how your DBMS stores data internally.
To know why the generated query is wrong, we'll need to see the code in your Controller's action.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20088781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.Net C# 4.0 - How to catch application thread exceptions I have an ASP.Net website that has custom internal threads, for periodically occurring tasks.
If I get an exception on one of these threads, it is not caught in Global.ASAX's Application_Error() function. It is allowed to bubble up to IIS and I find out about it by reviewing the Event Viewer logs. If I catch the exception then Log4Net will direct an email to me and I should find out about the error relatively quickly.
Is there a way I can trap exceptions on these threads? The app needs to be 'always-on', so an exception that drops the application is a show-stopper.
A: In a comment you mentioned:
This is a web-site rather than web app.
"Web site" vs. "web app" seems like a moot distinction at this point. There's enough complexity in the code that it's an "application" by pretty much any definition of the word. To that point, if the application host doesn't meaningfully manage thread faults for you (and I wouldn't expect a web application host to do so) then you have to manage them manually.
In this case I see that as one of two options:
Option 1: Don't let your threads end in a faulted state. Whatever your top-level worker item for any given thread is (a method invoked at the start of the thread, a loop repeating operations, etc.), that needs to be essentially fault-proof. No exception should get past that. Which means it needs to be dead simple (so as to not throw exceptions of its own) and needs to catch any and all exceptions from the operation(s) it invokes.
Once caught, do with them as you please. Roll back a unit of work, notify someone of the error, etc.
Option 2: Move the long-running thread operations out of the web application, since web applications aren't really suited for ongoing background processes. A Windows Service or scheduled Console Application is a much more suited application host for that logic.
Yes, bit of a re-write there though.
Is it? It shouldn't be. That's really a matter of how the code was originally architected, not related to the application hosts themselves. Invoking a business operation from one application host is the same as invoking it from another. If the logic is tightly coupled to the application technology, that's a separate problem. And there's no quick fix to that problem. The good news is that once you fix that problem, other problems (like the one which prompted this question) are quick fixes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26281154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: d3 - how to format xAxis ticks depending on weeks I have a d3 time scale chart. At the moment, the axis ticks render a date for every data object. The data could have a range of anything from 1 day of data, or 2 weeks in 1 month, or 5 months worth of data or even more, for example.
Ideally, we want to display ticks with a week number, based on the data - not the week number of the year or month like this: xAxis.tickFormat(d3.time.format('%W')) Eg, if the data starts from 15th of July, the first tick would say 'week 1', then 'week 2', etc.
How could you achieve such axis ticks with a time based d3 line chart? I'm new to d3 and almost lost with how to achieve this.
I'm using moment.js as well, so inside xAxis.tickFormat, i've tried using a function with some logic that returns different values depending on the date, but this seems fragile and not 'the d3 way'. Also tried using a custom time formatter as seen here.
Alternatively, we could have simpler ticks - just displaying the month and/or day with d3.time.format(%d-%b), but then there are duplicate tick values like 'Feb...Feb..Feb..Feb...Feb..Mar..Mar..Mar..`. Is there a method to prevent duplicate values from appearing?
I've tried limiting the amount of ticks, but this isn't working as expected. Eg, If I have xAxis.ticks(5), 3 ticks appear; same story if I have xAxis.ticks(2). If ticks is defined as 1, only 1 tick appears. What's going on here?
Any help would be most appreciated! Code below with 2 dataset examples
<!DOCTYPE html>
<body>
<style>
path { fill: #CCC; }
.line { fill: none; stroke: #000; stroke-width: 5px;}
</style>
<div id="chart-container">
<svg id="chart"></svg>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var now = moment();
var chartData = [
{ timestamp: moment(now).subtract(27, 'days').format('DD-MMM-YY'), value: 40 },
{ timestamp: moment(now).subtract(25, 'days').format('DD-MMM-YY'), value: 36 },
{ timestamp: moment(now).subtract(24, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(21, 'days').format('DD-MMM-YY'), value: 35 },
{ timestamp: moment(now).subtract(20, 'days').format('DD-MMM-YY'), value: 35 },
{ timestamp: moment(now).subtract(18, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(17, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(16, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(15, 'days').format('DD-MMM-YY'), value: 32 },
{ timestamp: moment(now).subtract(13, 'days').format('DD-MMM-YY'), value: 35 },
{ timestamp: moment(now).subtract(11, 'days').format('DD-MMM-YY'), value: 31 },
{ timestamp: moment(now).subtract(10, 'days').format('DD-MMM-YY'), value: 28 },
{ timestamp: moment(now).subtract(9, 'days').format('DD-MMM-YY'), value: 32 },
{ timestamp: moment(now).subtract(8, 'days').format('DD-MMM-YY'), value: 30 },
{ timestamp: moment(now).subtract(7, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(6, 'days').format('DD-MMM-YY'), value: 36 }
];
//data could have a shorter date range of eg, 1 or 2 weeks
//ideally we want to still display 'week 1, 2, 3, 4' etc in the axis.
//alternatively display dates instead
// var chartData = [
// { timestamp: moment(now).subtract(27, 'days').format('DD-MMM-YY'), value: 40 },
// { timestamp: moment(now).subtract(25, 'days').format('DD-MMM-YY'), value: 36 },
// { timestamp: moment(now).subtract(24, 'days').format('DD-MMM-YY'), value: 33 },
// { timestamp: moment(now).subtract(21, 'days').format('DD-MMM-YY'), value: 35 },
// { timestamp: moment(now).subtract(20, 'days').format('DD-MMM-YY'), value: 35 }
// ];
let lastObj = chartData[chartData.length - 1];
let lastObjTimestamp = lastObj.timestamp;
let lastAndNow = moment(lastObjTimestamp).diff(now, 'days');
console.log('difference between last entry ' + lastObjTimestamp + ' and today: ' + lastAndNow);
var chartWrapperDomId = 'chart-container';
var chartDomId = 'chart';
var chartWrapperWidth = document.getElementById(chartWrapperDomId).clientWidth;
var margin = 40;
var width = chartWrapperWidth - margin;
var height = 500 - margin * 2;
var xMin = d3.time.format('%d-%b-%y').parse(chartData[0].timestamp);
var xMax = d3.time.format('%d-%b-%y').parse(chartData[chartData.length-1].timestamp);
//set the scale for the x axis
var xScale = d3.time.scale();
xScale.domain([xMin, xMax]);
xScale.range([0, width]);
var yScale = d3.scale.linear()
.range([height, 0])
.nice();
console.log('no5 ', chartData[5].timestamp)
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.tickFormat(d3.time.format('%d-%b'));
//.tickFormat(d3.time.format('%b'))
//tickFormat(d3.time.format('%W'));
//.ticks(5);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left');
var line = d3.svg.line()
.x(function(d) {
return xScale(d.timestamp);
})
.y(function(d) {
return yScale(d.value);
});
var svg = d3.select('#' + chartDomId)
.attr('width', width + margin * 2)
.attr('height', height + margin * 2)
.append('g')
.attr('transform', 'translate(' + margin + ',' + margin + ')');
chartData.forEach(function(d) {
d.timestamp = d3.time.format('%d-%b-%y').parse(d.timestamp);
d.value = +d.value;
});
yScale.domain(d3.extent(chartData, function(d) {
return d.value;
}));
svg.append('g')
.attr('class', 'axis x-axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'axis y-axis')
.call(yAxis)
.append('text')
.attr('transform', 'rotate(-90)')
.attr('y', 6)
.attr('dy', '.71em')
.style('text-anchor', 'end');
svg.append('path')
.datum(chartData)
.attr('class', 'line')
.attr('d', line);
</script>
</body>
A: You need to find the first weekday (eg. Wednesday) from your data and set ticks according to that.
It can be achived using the following code:
var weekday = new Array(7);
weekday[0]= 'sunday';
weekday[1] = 'monday';
weekday[2] = 'tuesday';
weekday[3] = 'wednesday';
weekday[4] = 'thursday';
weekday[5] = 'friday';
weekday[6] = 'saturday';
var startDay = weekday[new Date(chartData[0].timestamp).getDay()];
var week = 1;
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.tickFormat(function() { return 'week ' + week++ })
.ticks(d3.time[startDay]);
<!DOCTYPE html>
<body>
<style>
path { fill: #CCC; }
.line { fill: none; stroke: #000; stroke-width: 5px;}
</style>
<div id="chart-container">
<svg id="chart"></svg>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var now = moment();
var chartData = [
{ timestamp: moment(now).subtract(27, 'days').format('DD-MMM-YY'), value: 40 },
{ timestamp: moment(now).subtract(25, 'days').format('DD-MMM-YY'), value: 36 },
{ timestamp: moment(now).subtract(24, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(21, 'days').format('DD-MMM-YY'), value: 35 },
{ timestamp: moment(now).subtract(20, 'days').format('DD-MMM-YY'), value: 35 },
{ timestamp: moment(now).subtract(18, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(17, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(16, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(15, 'days').format('DD-MMM-YY'), value: 32 },
{ timestamp: moment(now).subtract(13, 'days').format('DD-MMM-YY'), value: 35 },
{ timestamp: moment(now).subtract(11, 'days').format('DD-MMM-YY'), value: 31 },
{ timestamp: moment(now).subtract(10, 'days').format('DD-MMM-YY'), value: 28 },
{ timestamp: moment(now).subtract(9, 'days').format('DD-MMM-YY'), value: 32 },
{ timestamp: moment(now).subtract(8, 'days').format('DD-MMM-YY'), value: 30 },
{ timestamp: moment(now).subtract(7, 'days').format('DD-MMM-YY'), value: 33 },
{ timestamp: moment(now).subtract(6, 'days').format('DD-MMM-YY'), value: 36 }
];
//data could have a shorter date range of eg, 1 or 2 weeks
//ideally we want to still display 'week 1, 2, 3, 4' etc in the axis.
//alternatively display dates instead
// var chartData = [
// { timestamp: moment(now).subtract(27, 'days').format('DD-MMM-YY'), value: 40 },
// { timestamp: moment(now).subtract(25, 'days').format('DD-MMM-YY'), value: 36 },
// { timestamp: moment(now).subtract(24, 'days').format('DD-MMM-YY'), value: 33 },
// { timestamp: moment(now).subtract(21, 'days').format('DD-MMM-YY'), value: 35 },
// { timestamp: moment(now).subtract(20, 'days').format('DD-MMM-YY'), value: 35 }
// ];
let lastObj = chartData[chartData.length - 1];
let lastObjTimestamp = lastObj.timestamp;
let lastAndNow = moment(lastObjTimestamp).diff(now, 'days');
console.log('difference between last entry ' + lastObjTimestamp + ' and today: ' + lastAndNow);
var chartWrapperDomId = 'chart-container';
var chartDomId = 'chart';
var chartWrapperWidth = document.getElementById(chartWrapperDomId).clientWidth;
var margin = 40;
var width = chartWrapperWidth - margin;
var height = 500 - margin * 2;
var xMin = d3.time.format('%d-%b-%y').parse(chartData[0].timestamp);
var xMax = d3.time.format('%d-%b-%y').parse(chartData[chartData.length-1].timestamp);
//set the scale for the x axis
var xScale = d3.time.scale();
xScale.domain([xMin, xMax]);
xScale.range([0, width]);
var yScale = d3.scale.linear()
.range([height, 0])
.nice();
console.log('no5 ', chartData[5].timestamp)
var weekday = new Array(7);
weekday[0]= 'sunday';
weekday[1] = 'monday';
weekday[2] = 'tuesday';
weekday[3] = 'wednesday';
weekday[4] = 'thursday';
weekday[5] = 'friday';
weekday[6] = 'saturday';
var startDay = weekday[new Date(chartData[0].timestamp).getDay()];
var week = 1;
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
//.tickFormat(d3.time.format('%d-%b'));
//.tickFormat(d3.time.format('%b'))
//tickFormat(d3.time.format('%W'));
.tickFormat(function() { return 'week ' + week++ })
.ticks(d3.time[startDay]);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left');
var line = d3.svg.line()
.x(function(d) {
return xScale(d.timestamp);
})
.y(function(d) {
return yScale(d.value);
});
var svg = d3.select('#' + chartDomId)
.attr('width', width + margin * 2)
.attr('height', height + margin * 2)
.append('g')
.attr('transform', 'translate(' + margin + ',' + margin + ')');
chartData.forEach(function(d) {
d.timestamp = d3.time.format('%d-%b-%y').parse(d.timestamp);
d.value = +d.value;
});
yScale.domain(d3.extent(chartData, function(d) {
return d.value;
}));
svg.append('g')
.attr('class', 'axis x-axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'axis y-axis')
.call(yAxis)
.append('text')
.attr('transform', 'rotate(-90)')
.attr('y', 6)
.attr('dy', '.71em')
.style('text-anchor', 'end');
svg.append('path')
.datum(chartData)
.attr('class', 'line')
.attr('d', line);
</script>
</body>
A: Since in many cases d3 forces judgments on how many ticks to place along your axes regardless of how many you specify, this is how I went about defining the specific ticks that I wanted:
var tickLabels = ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5'];
d3.svg.axis()
.scale(x)
.orient("bottom")
.tickValues([0, 7, 14, 21, 28])
.tickFormat(function(d, i) {
return tickLabels[i]
});
.tickValues specifies the data points (aka dates) where I want my ticks to be placed, while tickFormat changes each of those respective numbers to "Week 1", "Week 2", etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36128327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unexpected NestJs error: Nest can't resolve dependencies of the UserService I'm trying to build a simple api in NestJs with authentication to save recipes to a MongoDB.
I was trying to add an email service to send a confirmation email for new users and ran into a dependency error I'm not able to figure out myself.
The error in question:
Error: Nest can't resolve dependencies of the UserService (?). Please make sure that the argument UserModel at index [0] is available in the EmailModule context.
Potential solutions:
- Is EmailModule a valid NestJS module?
- If UserModel is a provider, is it part of the current EmailModule?
- If UserModel is exported from a separate @Module, is that module imported within EmailModule?
@Module({
imports: [ /* the Module containing UserModel */ ]
})
at Injector.lookupComponentInParentModules (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:241:19)
at Injector.resolveComponentInstance (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:194:33)
at resolveParam (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:116:38)
at async Promise.all (index 0)
at Injector.resolveConstructorParams (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:131:27)
at Injector.loadInstance (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:57:13)
at Injector.loadProvider (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:84:9)
at async Promise.all (index 4)
at InstanceLoader.createInstancesOfProviders (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\instance-loader.js:47:9)
at C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\instance-loader.js:32:13
It states the UserModel is missing in the EmailModule but that doesn't seem to be the case.
EmailModule:
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { UserModule } from "src/user/user.module";
import { JwtService } from "@nestjs/jwt";
import { UserService } from "src/user/user.service";
@Module({
imports: [ConfigModule, UserModule],
controllers: [],
providers: [JwtService, UserService],
})
export class EmailModule {}
Email Service:
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { createTransport } from "nodemailer";
import * as Mail from "nodemailer/lib/mailer";
@Injectable()
export default class EmailService {
private nodemailerTransport: Mail;
constructor(private readonly configService: ConfigService) {
this.nodemailerTransport = createTransport({
service: configService.get("EMAIL_SERVICE"),
auth: {
user: configService.get("EMAIL_USER"),
pass: configService.get("EMAIL_PASSWORD"),
},
});
}
sendMail(options: Mail.Options) {
return this.nodemailerTransport.sendMail(options);
}
}
Email Confirmation Service:
import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { ConfigService } from "@nestjs/config";
import EmailService from "./email.service";
import { UserService } from "src/user/user.service";
import { AccountStatus } from "src/types";
import { BadRequestException } from "@nestjs/common/exceptions";
interface VerificationTokenPayload {
email: string;
}
@Injectable()
export class EmailConfirmationService {
constructor(
private jwtService: JwtService,
private configService: ConfigService,
private emailService: EmailService,
private userService: UserService,
) {}
sendVerificationLink(email: string) {
const payload: VerificationTokenPayload = { email };
const token = this.jwtService.sign(payload, {
secret: this.configService.get("JWT_VERIFICATION_TOKEN_SECRET"),
expiresIn: `${this.configService.get("JWT_VERIFICATION_TOKEN_EXPIRATION_TIME")}s`,
});
const url = `${this.configService.get("EMAIL_CONFIRMATION_URL")}?token=${token}`;
const text = `Welcome to Pantry! To confirm the email address, click here: ${url}`;
return this.emailService.sendMail({
to: email,
subject: "Pantry Account Confirmation",
text,
});
}
async confirmEmail(email: string) {
const user = await this.userService.findOne(email);
if (user && user.status !== AccountStatus.Created)
throw new BadRequestException("Email already confirmed");
await this.userService.markEmailAsConfirmed(email);
}
async decodeConfirmationToken(token: string) {
try {
const payload = await this.jwtService.verify(token, {
secret: this.configService.get("JWT_VERIFICATION_TOKEN_SECRET"),
});
if (typeof payload === "object" && "email" in payload) {
return payload.email;
}
throw new BadRequestException();
} catch (error) {
if (error?.name === "TokenExpiredError") {
throw new BadRequestException("Email confirmation token expired");
}
throw new BadRequestException("Bad confirmation token");
}
}
public async resendConfirmationLink(email: string) {
const user = await this.userService.findOne(email)
if (user.status === AccountStatus.Confirmed) {
throw new BadRequestException('Email already confirmed');
}
await this.sendVerificationLink(user.email);
}
}
I will add the other services & modules below in case they are of any use.
User Module:
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { User, UserSchema } from "./schemas/user.schema";
import { UserController } from "./user.controller";
import { UserService } from "./user.service";
@Module({
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
controllers: [UserController],
providers: [UserService]
})
export class UserModule {}
User Service:
import { BadRequestException, Injectable } from "@nestjs/common";
import { NotFoundException } from "@nestjs/common/exceptions";
import { InjectModel } from "@nestjs/mongoose";
import { Model, isValidObjectId } from "mongoose";
import { AccountStatus } from "src/types";
import { User, UserDocument } from "./schemas/user.schema";
import { MSG_USER_NOT_FOUND } from "./user-messages";
@Injectable()
export class UserService {
constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}
private readonly defaultProjection = {
__v: false,
password: false,
};
async findOne(email: string): Promise<User> {
const user = this.userModel.findOne({ email }, this.defaultProjection);
if (user === null) throw new NotFoundException(MSG_USER_NOT_FOUND);
return user;
}
async deleteOne(id: string): Promise<any> {
if (!isValidObjectId(id)) throw new BadRequestException();
const result = await this.userModel.deleteOne({ _id: id }).exec();
if (result.deletedCount !== 1) throw new NotFoundException(MSG_USER_NOT_FOUND);
return result;
}
async updateOne(id: string, userData: User) {
if (!isValidObjectId(id)) throw new BadRequestException();
let result;
try {
result = await this.userModel.findByIdAndUpdate(id, userData).setOptions({ new: true });
} catch (e) {
throw new BadRequestException();
}
if (result === null) throw new NotFoundException(MSG_USER_NOT_FOUND);
return result;
}
async markEmailAsConfirmed(email: string) {
const user = await this.findOne(email);
return this.updateOne(user.email, {...user, status: AccountStatus.Confirmed})
}
}
Auth Module:
import { Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { JwtModule } from "@nestjs/jwt";
import { MongooseModule } from "@nestjs/mongoose";
import { PassportModule } from "@nestjs/passport";
import { EmailModule } from "src/email/email.module";
import { EmailConfirmationService } from "src/email/emailConfirmation.service";
import { User, UserSchema } from "src/user/schemas/user.schema";
import { UserModule } from "src/user/user.module";
import { UserService } from "src/user/user.service";
import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service";
import { JwtStrategy } from "./jwt.strategy";
import { LocalStrategy } from "./local.auth";
@Module({
imports: [
UserModule,
EmailModule,
PassportModule,
JwtModule.register({ secret: "secretKey", signOptions: { expiresIn: "10m" } }),
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
],
providers: [
AuthService,
JwtStrategy,
UserService,
LocalStrategy,
EmailConfirmationService,
ConfigService,
],
controllers: [AuthController],
})
export class AuthModule {}
Auth Service:
import { Injectable, NotAcceptableException, BadRequestException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { InjectModel } from "@nestjs/mongoose";
import * as bcrypt from "bcrypt";
import {
MSG_USER_EMAIL_TAKEN,
MSG_USER_NAME_TAKEN,
MSG_USER_NOT_FOUND,
MSG_USER_WRONG_CRED,
} from "src/user/user-messages";
import { UserService } from "../user/user.service";
import { LoginDto } from "./dto/login.dto";
import { RegisterDto } from "./dto/register.dto";
import { Model } from "mongoose";
import { User, UserDocument } from "src/user/schemas/user.schema";
import { AccountStatus } from "src/types";
@Injectable()
export class AuthService {
constructor(
@InjectModel(User.name) private userModel: Model<UserDocument>,
private userService: UserService,
private jwtService: JwtService,
) {}
async validateUser({ email, password }: LoginDto) {
const user = await this.userService.findOne(email);
if (!user) throw new NotAcceptableException(MSG_USER_NOT_FOUND);
const passwordValid = await bcrypt.compare(password, user.password);
if (user && passwordValid) return user;
return null;
}
async register({ email, username, password }: RegisterDto) {
const userWithEmail = await this.userModel.findOne({ email });
if (userWithEmail) throw new BadRequestException(MSG_USER_EMAIL_TAKEN);
const userWithName = await this.userModel.findOne({ username });
if (userWithName) throw new BadRequestException(MSG_USER_NAME_TAKEN);
const createdUser = new this.userModel({email, username, password});
createdUser.status = AccountStatus.Created;
const newUser = await createdUser.save();
return newUser;
}
async login(login: LoginDto) {
const user = await this.validateUser(login);
if (!user) throw new NotAcceptableException(MSG_USER_WRONG_CRED);
const payload = { email: user.email, sub: user._id };
return {
access_token: this.jwtService.sign(payload),
};
}
}
I hope this is enough to get some help, it's hard for me to share the entire repository at this point since it's work related
A: as you're trying to use UserService in another module other than where it was registered (which was UserModule), you need to expose it, like this:
@Module({
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
controllers: [UserController],
providers: [UserService]
exports: [UserService], // <<<<
})
export class UserModule {}
then remove UserService from EmailModule.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75160406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# Visual studio : adding columns to localdb reset all data I was working with VisualStudio 2017 C# and localdb2016 I created a table in server explorer's database desginer window with 10 columns added X rows.
I have already set copy if newer so rows wont get deleted everytime
but when i try to add a new column (11th column) all of my rows (even in other tables!) get deleted !
why ?
Here is my Table code generated from desginer .... :
CREATE TABLE [dbo].[CustomerTable] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[name] NVARCHAR (50) NULL,
[company] NVARCHAR (50) NULL,
[email] NVARCHAR (50) NULL,
[phone1] NVARCHAR (50) NULL,
[phone2] NVARCHAR (50) NULL,
[address] NVARCHAR (50) NULL,
[fax] NVARCHAR (50) NULL,
[phone3] NVARCHAR (50) NULL,
[date] DATETIME DEFAULT (getdate()) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
UPDATE 1 :
ALTER TABLE dbo.CustomerTable ADD column_b VARCHAR(20) NULL, column_c INT NULL ;
does that code remove old columns (b and c) if they exists?
is it a good idea to do that everytime app starts? (for upgrading purpose)
A: Try this Transact-SQL query
ALTER TABLE dbo.CustomerTable ADD column_b VARCHAR(20) NULL, column_c INT NULL ;
This query will add 2 columns in your table -> First, b (VARCHAR[20]) & Second, c (INT).
To read more,
ALTER TABLE (Transact-SQL)
The query will not remove any existing column because it is an alter query that means it alter the table as you mention. Adding existing column doesn't alter table. So, no changes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51054762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to loop over viewbuilder content subviews in SwiftUI So I’m trying to create a view that takes viewBuilder content, loops over the views of the content and add dividers between each view and the other
struct BoxWithDividerView<Content: View>: View {
let content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
VStack(alignment: .center, spacing: 0) {
// here
}
.background(Color.black)
.cornerRadius(14)
}
}
so where I wrote “here” I want to loop over the views of the content, if that makes sense. I’ll write a code that doesn’t work but that explains what I’m trying to achieve:
ForEach(content.subviews) { view in
view
Divider()
}
How to do that?
A: I just answered on another similar question, link here. Any improvements to this will be made for the linked answer, so check there first.
GitHub link of this (but more advanced) in a Swift Package here
However, here is the answer with the same TupleView extension, but different view code.
Usage:
struct ContentView: View {
var body: some View {
BoxWithDividerView {
Text("Something 1")
Text("Something 2")
Text("Something 3")
Image(systemName: "circle") // Different view types work!
}
}
}
Your BoxWithDividerView:
struct BoxWithDividerView: View {
let content: [AnyView]
init<Views>(@ViewBuilder content: @escaping () -> TupleView<Views>) {
self.content = content().getViews
}
var body: some View {
VStack(alignment: .center, spacing: 0) {
ForEach(content.indices, id: \.self) { index in
if index != 0 {
Divider()
}
content[index]
}
}
// .background(Color.black)
.cornerRadius(14)
}
}
And finally the main thing, the TupleView extension:
extension TupleView {
var getViews: [AnyView] {
makeArray(from: value)
}
private struct GenericView {
let body: Any
var anyView: AnyView? {
AnyView(_fromValue: body)
}
}
private func makeArray<Tuple>(from tuple: Tuple) -> [AnyView] {
func convert(child: Mirror.Child) -> AnyView? {
withUnsafeBytes(of: child.value) { ptr -> AnyView? in
let binded = ptr.bindMemory(to: GenericView.self)
return binded.first?.anyView
}
}
let tupleMirror = Mirror(reflecting: tuple)
return tupleMirror.children.compactMap(convert)
}
}
Result:
A: So I ended up doing this
@_functionBuilder
struct UIViewFunctionBuilder {
static func buildBlock<V: View>(_ view: V) -> some View {
return view
}
static func buildBlock<A: View, B: View>(
_ viewA: A,
_ viewB: B
) -> some View {
return TupleView((viewA, Divider(), viewB))
}
}
Then I used my function builder like this
struct BoxWithDividerView<Content: View>: View {
let content: () -> Content
init(@UIViewFunctionBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
VStack(spacing: 0.0) {
content()
}
.background(Color(UIColor.AdUp.carbonGrey))
.cornerRadius(14)
}
}
But the problem is this only works for up to 2 expression views. I’m gonna post a separate question for how to be able to pass it an array
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64238485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: permission denied while using fb_graph rails3 SA
I have a application written in RubyonRails and I want to make him post periodically on facebook fan page.
I used fb_graph gem to do that.
I created my facebook app and I get my Access Token to use it but when I use this peace of code
me = FbGraph::User.me(ACCESS_TOKEN)
me.feed!(
:message => 'Updating via FbGraph',
:picture => 'https://graph.facebook.com/matake/picture',
:link => 'http://github.com/nov/fb_graph',
:name => 'FbGraph',
:description => 'A Ruby wrapper for Facebook Graph API'
)
I get permission denied error message.
How can I get the permission to post on my fan page wall?
Thanks in advance.
A: Link to the docs:
http://developers.facebook.com/docs/authentication/
There are several flows, but essentially, you provide a link for the client to authenticate at facebook:
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=publish_stream,manage_pages
After authing this redirects to a URL on your site prepared to handle the param code, which you then turn around and send back to facebook for your access_token, which you provide to fb_graph.
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URLclient_secret=YOUR_APP_SECRET&code=CODE
There are other permissions as well, so you might want to check the facebook docs to see if there are more you need.
Facebook uses OAuth 2 for auth, and there are several ruby gems you can use to facilitate this process slightly, including the oauth2 gem.
A: The app ID you specified must be wrong. please cross check that. A sample appID looks like this
APP_ID="162221007183726"
Also check whether you have used any call back url. The url should point to a server. Your cannot use your localhost/ local IP there.
A similar nice rails plugin for Facebook app using Rails3 is Koala gem
https://github.com/arsduo/koala/wiki/Koala-on-Rails
http://blog.twoalex.com/2010/05/03/introducing-koala-a-new-gem-for-facebooks-new-graph-api/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7027325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XQuartz Gnuplot Mac Sierra trackpad issue I'm using Mac Sierra and plot with XQuartz Gnuplot version 5.0. I can plot but after that not much else with the plot. I cannot zoom, double click to get coordinates to clipboard etc (and all the other keyboard commands don't work) as it is said in gnuplot bind that it should.
I have a trackpad without any extra buttons on it so I guess this is where the issue arises (I have checked/unchecked "emulate three button mouse" nothing helps). Any suggestions on how to fix this so I can zoom parts of the plot like they do on those d#mn smoothly working linux computers?
Btw not even a connected mouse does the job.
When I enter gnuplot in terminal and then show mouse (as suggested in the comments) I receive the following info
mouse is on
zoom coordinates will be drawn
no polar distance to ruler will be shown
double click resolution is 300 ms
formatting numbers with "% #g"
format for Button 2 is 0
Button 2 draws temporary labels
zoom factors are x: 1 y: 1
zoomjump is off
communication commands will not be shown
EDIT: I actually uninstalled and reinstalled gnuplot this time with
brew uninstall gnuplot
brew install gnuplot --with-qt
and now I do have the zoom buttons on a gnuplot. For example when I write in terminal gnuplot plot x I can zoom and everything with the trackpad, good. But the issue that still remains is when I call on gnuplot from another code e.g. with a pipe. Then I do get the plot with the zoom buttons and all but when I click them nothing happens. Any ideas.
btw brew installing with qt was some trouble on Sierra I had to consult this page How to fix homebrew permissions?.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43846976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# Unable to Select Specific Fields into DataTable from ListItemCollection Connecting to a SharePoint list I'm pulling back a ListItemCollection, which is being fed into a DataTable, however I only want to select certain fields from the ListItemCollection into the DataTable. Can anyone advise how to do this. New to C#.
Web site = cc.Web;
List targetList = site.Lists.GetByTitle("Team");
DataTable dtData = new DataTable();
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><Query><Where><Contains><FieldRef Name='TeamClass'/><Value Type='Text'>Retail</Value></Contains></Where></Query></View>";
ListItemCollection collListItem = targetList.GetItems(query);
cc.Load(collListItem);
cc.ExecuteQuery();
for (int iCntr1 = 0; iCntr1 < collListItem.Count; iCntr1++)
{
foreach (var field in collListItem[0].FieldValues.Keys)
{
dtData.Columns.Add(field);
}
foreach (var item in collListItem)
{
DataRow dr = dtData.NewRow();
}
}
A: Iterating through a collection of list items is not a good solution.
If you're interested in the graph API, then you can just return specific fields when getting a collection of list items.
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var queryOptions = new List<QueryOption>()
{
new QueryOption("expand", "fields(select=Name,Color,Quantity)")
};
var items = await graphClient.Sites["{site-id}"].Lists["{list-id}"].Items
.Request( queryOptions )
.GetAsync();
A: Resolved the issue by adding the <ViewFields> clause to the xml.
CamlQuery query = new CamlQuery();
query.ViewXml =
"<View>
<Query>
<Where>
<Contains>
<FieldRef Name='Name' /><Value Type='Text'>House</Value>
</Contains></Where></Query>" +
"<ViewFields>" +
"<FieldRef Name=Ref />" +
"<FieldRef Name=Name />" +
"</ViewFields>
</View>";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75473743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gatsby WhereInput query compiles with errors I have a GraphQL query which I can run perfectly using GraphQL playground.
However, when I put it within Gatsby page it throws an error and gives no further diagnostic.
export const query = graphql`
query($path: String!) {
cms {
headerActions: callToActions(
where: { placement: Header, AND: { pages_some: { path: $path } } }
) {
url
label
}
}
}
`
The Error:
error GraphQL Error Expected a value matching type `[CMS_CallToActionWhereInput!]`, but got an object value
I'm puzzled which direction to even dig as Gatsby gives no error details.
A: The error says it expecting an Array but I don't see any array in your calToAction Query, I guess this might fix your problem:
export const query = graphql`
query($path: String!) {
cms {
headerActions: callToActions(
where: [ { placement: Header, AND: { pages_some: { path: $path } } } ]
) {
url
label
}
}
}
`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53921926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TensorFlow object detection fails on Xamarin Android with a reshape issue I am following this blog post and GitHub almost exactly:
Blog
Github
But when I run, take a picture and call this line:
var outputs = new float[tfLabels.Count];
tfInterface.Feed("Placeholder", floatValues, 1, 227, 227, 3);
tfInterface.Run(new[] { "loss" });
tfInterface.Fetch("loss", outputs);
The app actually crashes and generates the error below on the .Run line.
I get this error in the output window (and the app crashes):
04-04 17:39:12.575 E/TensorFlowInferenceInterface( 8017): Failed to
run TensorFlow inference with inputs:[Placeholder], outputs:[loss]
Unhandled Exception:
Java.Lang.IllegalArgumentException: Input to reshape is a tensor with
97556 values, but the requested shape requires a multiple of 90944
[[Node: block0_0_reshape0 = Reshape[T=DT_FLOAT, Tshape=DT_INT32,
_device="/job:localhost/replica:0/task:0/device:CPU:0"](block0_0_concat,
block0_0_reshape0/shape)]]
According to the posts I am reading from the searching I am doing on this error, I sort of understand this is due to the image not fitting the expected size exactly but in the example I am following, this is resized to fit 227x227 everytime and converted to float like in these lines:
var resizedBitmap = Bitmap.CreateScaledBitmap(bitmap, 227, 227, false).Copy(Bitmap.Config.Argb8888, false);
var floatValues = new float[227 * 227 * 3];
var intValues = new int[227 * 227];
resizedBitmap.GetPixels(intValues, 0, 227, 0, 0, 227, 227);
for(int i = 0; i < intValues.Length; i++)
{
var val = intValues[i];
floatValues[i * 3 + 0] = ((val & 0xFF) - 104);
floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - 117);
floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - 123);
}
So, I don't understand what is causing this or how to fix it. Please help!
UPDATE: I found out the issue is with my model or my labels. I found this out by simply swapping in the model and label file from the sample/github above while leaving all my code the same. When I did this, I no longer get the error. HOWEVER, this still doesn't tell me much. The error is not very explanatory to point me in a direction of what could be wrong with my model. I assume it is the model because the labels file is simply just a text file with labels on each line. I used Custom Vision Service on Azure to create my model. It trained fine and tests just fine on the web portal. I then exported it as TensorFlow. So, I am not sure what I could have done wrong or how to fix it.
Thanks!
A: After no answers here and several days of searching and trial and error, I have found the issue. In general, I guess this reshape error I was getting you can get if you are feeding the model with an image size other that it is expecting or setup to receive.
The issue is that, everything I have read says that typically you must feed the model with a 227 x 227 x 3 image. Then, I started noticing that size varies on some posts. Some people say 225 x 225 x 3, others say 250 x 250 x 3 and so on. I had tried those sizes as well with no luck.
As you can see in my edit in the question, I did have a clue. When using somebody else's pretrained model, my code works fine. However, when I use my custom model which I created on the Microsoft Azure CustomVision.ai site, I was getting this error.
So, I decided I would try to inspect the models to see what was different. I followed this post: Inspect a pre trained model
When I inspected the model that works using TensorBoard, I see that the input is 227 x 227 x 3 which is what I expected. However, when I viewed my model, I noticed that it was 224 x 224 x 3! I changed my code to resize the image to that size and it works! Problem went away.
So, to summarize, for some reason Microsoft Custom Vision service model generated a model to expect an image size of 224 x 224 x 3. I didn't see any documentation or setting for this. I also don't know if that number will change with each model. If you get a similar shape error, the first place I would check is the size of the image you are feeding your model and what it expects as an input. The good news is you can check your model, even if pre-trained, using TensorBoard and the post I linked above. Look at the input section, it should look something like this:
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55526797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I use Rails Selectize in my Rails Project? I'm getting the error
Selectize: Dependency MicroPlugin is missing
Make sure you either: (1) are using the "standalone" version of Selectize, or (2) require MicroPlugin before you load Selectize.
application.js:
//= require jquery
//= require jquery_ujs
//= require selectize
//= require turbolinks
//= require bootstrap-sprockets
//= require jquery.validate
//= require jquery.validate.additional-methods
//= require_tree .
A: I changed my application.js to
//= require selectize/standalone/selectize
I figured it out by looking at the load paths
~/.rvm/gems/ruby-2.3.1/gems/rails-assets-selectize-0.12.3/app/assets/javascripts
and found standalone was in /selectize/standalone/selectize.js
I knew to look there by looking at their examples.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39556778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to enable javascript alert and confirm boxes in Microsoft Edge when a website installed as PWA? I'm testing the installation of a Progressive Web App with the new Windows 10 support (https://blogs.windows.com/msedgedev/2018/02/06/welcoming-progressive-web-apps-edge-windows-10/#La19KKkTBKLj90k8.97 ).
I generated an AppX package then I installed it locally on my PC.
The PWA starts in an interface-less Edge window.
Everything works fine, except to javascript confirm and alert boxes that are totally ignored.
The exact same webapp works fine installed as PWA in Android, with working alert and confirm boxes.
How can enable these boxes?
A: Finally I had to resign not to use alert() and confirm() anymore.
I just made two simple functions that replace the standard ones:
function async_alert(message) {
$("body").append("<div class='alert-box'>\
<div class='alert-surface'>\
<h2>Alert</h2></header>\
<p>" + message + "</p>\
<button type='button' class='alert-remove'>OK</button>\
</div>\
<div class='alert-backdrop'></div>\
</div>");
$(".alert-remove").off("click").on("click", function() { $(".alert-box").remove(); });
}
function async_confirm(message, onAcceptFunction) {
$("body").append("<div class='confirm-box'>\
<div class='confirm-surface'>\
<h2>Confirm</h2>\
<p>" + message + "</p>\
<button type='button' class='confirm-remove'>Cancel</button>\
<button type='button' class='confirm-accept'>OK</button>\
</div>\
<div class='confirm-backdrop'></div>\
</div>");
$(".confirm-remove").off("click").on("click", function() { $(".confirm-box").remove(); });
$(".confirm-accept").off("click").on("click", onAcceptFunction);
}
You should adjust your styles achieving that .alert-box div covers view-port entirey and .alert-surface div becomes a centered rectangle containing informations. E.g.:
.alert-box, .confirm-box {
position: fixed;
top: 0;
left: 0;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
z-index: 100000;
display: flex;
align-items: flex-start;
}
.alert-surface, .confirm-surface {
opacity: 1;
visibility: visible;
box-shadow: 0 11px 15px -7px rgba(0,0,0,.2), 0 24px 38px 3px rgba(0,0,0,.14), 0 9px 46px 8px rgba(0,0,0,.12);
background-color: #fff;
display: inline-flex;
flex-direction: column;
width: calc(100% - 30px);
max-width: 865px;
transform: translateY(50px) scale(.8);
border-radius: 2px;
}
.alert-backdrop, .confirm-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,.87);
opacity: .3;
z-index: -1;
}
You can use async_alert() just as the original alert() function, but keep in mind that this newly defined function is just asynchronous while the other is synchronous (so it doesn't stop your runtime javascript execution waiting your click).
You can also replace the standard browser alert function:
window.alert = async_alert;
To use async_confirm() function you should slightly change your code from:
if(confirm("Do something?") {
console.log("I'm doing something");
}
to:
async_confirm("Do something?", function() {
console.log("I'm doing something");
});
Once again, pay attention that async_confirm() il an asynchronous function compared to the standard confirm().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49360231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Populating a FlowLayoutPanel with a large number of controls and painting thumbnails on demand I'm trying to make an ImageListBox kind of control that will display a large numbers of thumbnails, like the one that Picasa uses.
This is my design:
I have a FlowLayoutPanel that is populated with a lot of UserControl objects, for example 4,000.
Each UserControl is assigned a delegate for the Paint event.
When the Paint event is called, it checks a memory cache for the thumbnail and if the image is not in cache, it retrieves it from the disk.
I have two problems that I'm trying to solve:
*
*It seems that WinForms will trigger a Paint event even if the UserControl is not in view. Only 10 or so controls are in fact in view, the rest are not (the FlowLayoutPanel.AutoScroll is set to true). As a result, it tries to retrieve thumbnails for all the images and that takes a long time.
*Adding the UserControl objects to the FlowLayoutPanel takes a somewhat long time, about 2-3 seconds. I can live with it but I'm wondering if there is a better way to do it than:
UserControl[] boxes = new UserControl[N];
// populate array
panel.SuspendLayout();
panel.Controls.AddRange(boxes);
panel.ResumeLayout();
A: To improve the speed of populating the FlowLayoutPanel with your user controls, disable layout updating while you add the controls.
Immediately before your loop, call SuspendLayout() and then at the end call ResumeLayout(). Make sure to use a try-finally to guarantee the ResumeLayout() runs even if an exception occurs.
A: I wouldn't add that many user controls. Rather, I'd have a series of data structures that stores information about what thumbnail to use, positioning, etc, etc, and then handle the rendering of each thumbnail required.
Of course, you would only render what you need, by checking the paint event args in your control and rendering the thumbnails that are in view and that require rendering.
A: Aha! I found something.
When the UserControl is not in view and it receives a Paint event, then e.ClipRectangle.IsEmpty is true!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/470863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Command line escaping single quote for PowerShell I have a Windows application and on events, it calls a command like this:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name '%x' -data '%y'"
The name parameter sometimes has ' in it. Is it possible to escape that somehow?
A: I'm slightly unclear in the question whether %x and %y are CMD variables (in which case you should be using %x% to substitute it in, or a substitution happening in your other application.
You need to escape the single quote you are passing to PowerShell by doubling it in the CMD.EXE command line. You can do this by replacing any quotes in the variable with two single quotes.
For example:
C:\scripts>set X=a'b
C:\scripts>set Y=c'd
C:\scripts>powershell .\test.ps1 -name '%x:'=''%' '%y:'=''%'
Name is 'a'b'
Data is 'c'd'
where test.ps1 contains:
C:\scripts>type test.ps1
param($name,$data)
write-output "Name is '$name'"
write-output "Data is '$data'"
If the command line you gave is being generated in an external application, you should still be able to do this by assigning the string to a variable first and using & to separate the commands (be careful to avoid trailing spaces on the set command).
set X=a'b& powershell .\test.ps1 -name '%x:'=''%'
The CMD shell supports both a simple form of substitution, and a way to extract substrings when substituting variables. These only work when substituting in a variable, so if you want to do multiple substitutions at the same time, or substitute and substring extraction then you need to do one at a time setting variables with each step.
Environment variable substitution has been enhanced as follows:
%PATH:str1=str2%
would expand the PATH environment variable, substituting each occurrence
of "str1" in the expanded result with "str2". "str2" can be the empty
string to effectively delete all occurrences of "str1" from the expanded
output. "str1" can begin with an asterisk, in which case it will match
everything from the beginning of the expanded output to the first
occurrence of the remaining portion of str1.
May also specify substrings for an expansion.
%PATH:~10,5%
would expand the PATH environment variable, and then use only the 5
characters that begin at the 11th (offset 10) character of the expanded
result. If the length is not specified, then it defaults to the
remainder of the variable value. If either number (offset or length) is
negative, then the number used is the length of the environment variable
value added to the offset or length specified.
%PATH:~-10%
would extract the last 10 characters of the PATH variable.
%PATH:~0,-2%
would extract all but the last 2 characters of the PATH variable.
A: This is actually a lot trickier than you'd think. Escaping nested quotes in strings passed from cmd to PowerShell is a major headache. What makes this one especially tricky is that you need to make the replacement in a variable expanded by cmd in the quoted argument passed to powershell.exe within a single-quoted argument passed to a PowerShell script parameter. AFAIK cmd doesn't have any native functionality for even basic string replacements, so you need PowerShell to do the replacement for you.
If the argument to the -data paramater (the one contained in the cmd variable x) doesn't necessarily need to be single-quoted, the simplest thing to do is to double-quote it, so that single quotes within the value of x don't need to be escaped at all. I say "simplest", but even that is a little tricky. As Vasili Syrakis indicated, ^ is normally the escape character in cmd, but to escape double quotes within a (double-)quoted string, you need to use a \. So, you can write your batch command like this:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name \"%x%\" -data '%y%'"
That passes the following command to PowerShell:
G:\test.ps1 -name "value of x, which may contain 's" -data 'value of y'
If, however, x can also contain characters that are special characters in PowerShell interpolated strings (", $, or `), then it becomes a LOT more complicated. The problem is that %x is a cmd variable that gets expanded by cmd before PowerShell has a chance to touch it. If you single-quote it in the command you're passing to powershell.exe and it contains a single quote, then you're giving the PowerShell session a string that gets terminated early, so PowerShell doesn't have the opportunity to perform any operations on it. The following obviously doesn't work, because the -replace operator needs to be supplied a valid string before you can replace anything:
'foo'bar' -replace "'", "''"
On the other hand, if you double-quote it, then PowerShell interpolates the string before it performs any replacements on it, so if it contains any special characters, they're interpreted before they can be escaped by a replacement. I searched high and low for other ways to quote literal strings inline (something equivalent to perl's q//, in which nothing needs to be escaped but the delimiter of your choice), but there doesn't seem to be anything.
So, the only solution left is to use a here string, which requires a multi-line argument. That's tricky in a batch file, but it can be done:
setlocal EnableDelayedExpansion
set LF=^
set pscommand=G:\test.ps1 -name @'!LF!!x!!LF!'@ -data '!y!'
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass "!pscommand!"
*
*This assumes that x and y were set earlier in the batch file. If your app can only send a single-line command to cmd, then you'll need to put the above into a batch file, adding the following two lines to the beginning:
set x=%~1
set y=%~2
Then invoke the batch file like this:
path\test.bat "%x%" "%y%"
The ~ strips out the quotes surrounding the command line arguments. You need the quotes in order to include spaces in the variables, but the quotes are also added to the variable value. Batch is stupid that way.
*The two blank lines following set LF=^ are required.
That takes care of single quotes which also interpreting all other characters in the value of x literally, with one exception: double quotes. Unfortunately, if double quotes may be part of the value as you indicated in a comment, I don't believe that problem is surmountable without the use of a third party utility. The reason is that, as mentioned above, batch doesn't have a native way of performing string replacements, and the value of x is expanded by cmd before PowerShell ever sees it.
BTW...GOOD QUESTION!!
UPDATE:
In fact, it turns out that it is possible to perform static string replacements in cmd. Duncan added an answer that shows how to do that. It's a little confusing, so I'll elaborate on what's going on in Duncan's solution.
The idea is that %var:hot=cold% expands to the value of the variable var, with all occurrences of hot replaced with cold:
D:\Scratch\soscratch>set var=You're such a hot shot!
D:\Scratch\soscratch>echo %var%
You're such a hot shot!
D:\Scratch\soscratch>echo %var:hot=cold%
You're such a cold scold!
So, in the command (modified from Duncan's answer to align with the OP's example, for the sake of clarity):
powershell G:\test.ps1 -name '%x:'=''%' -data '%y:'=''%'
all occurrences of ' in the variables x and y are replaced with '', and the command expands to
powershell G:\test.ps1 -name 'a''b' -data 'c''d'
Let's break down the key element of that, '%x:'=''%':
*
*The two 's at the beginning and the end are the explicit outer quotes being passed to PowerShell to quote the argument, i.e. the same single quotes that the OP had around %x
*:'='' is the string replacement, indicating that ' should be replaced with ''
*%x:'=''% expands to the value of the variable x with ' replaced by '', which is a''b
*Therefore, the whole thing expands to 'a''b'
This solution escapes the single quotes in the variable value much more simply than my workaround above. However, the OP indicated in an update that the variable may also contain double quotes, and so far this solution still doesn't pass double quotes within x to PowerShell--those still get stripped out by cmd before PowerShell receives the command.
The good news is that with the cmd string replacement method, this becomes surmountable. Execute the following cmd commands after the initial value of x has already been set:
*
*Replace ' with '', to escape the single quotes for PowerShell:
set x=%x:'=''%
*Replace " with \", to escape the double quotes for cmd:
set x=%x:"=\"%
The order of these two assignments doesn't matter.
*Now, the PowerShell script can be called using the syntax the OP was using in the first place (path to powershell.exe removed to fit it all on one line):
powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name '%x' -data '%y'"
Again, if the app can only send a one-line command to cmd, these three commands can be placed in a batch file, and the app can call the batch file and pass the variables as shown above (first bullet in my original answer).
One interesting point to note is that if the replacement of " with \" is done inline rather than with a separate set command, you don't escape the "s in the string replacement, even though they're inside a double-quoted string, i.e. like this:
powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name '%x:"=\"' -data '%y'"
...not like this:
powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name '%x:\"=\\"' -data '%y'"
A: I beleive you can escape it with ^:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name ^'%x^' -data ^'%y^'"
A: Try encapsulating your random single quote variable inside a pair of double quotes to avoid the issue.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass "G:\test.ps1 -name `"%x`" -data `"%y`""
The problem arises because you used single quotes and the random extra single quote appearing inside the single quotes fools PowerShell. This shouldn't occur if you double quote with backticks, as the single quote will not throw anything off inside double quotes and the backticks will allow you to double/double quote.
A: Just FYI, I ran into some trouble with a robocopy command in powershell and wanting to exclude a folder with a single quote in the name (and backquote didn't help and ps and robocopy don't work with double quote); so, I solved it by just making a variable for the folder with a quote in it:
$folder="John Doe's stuff"
robocopy c:\users\jd\desktop \\server\folder /mir /xd 'normal folder' $folder
A: One wacky way around this problem is to use echo in cmd to pipe your command to 'powershell -c "-" ' instead of using powershell "arguments"
for instance:
ECHO Write-Host "stuff'" | powershell -c "-"
output:
stuff'
Couple of notes:
*
*Do not quote the command text you are echoing or it won't work
*If you want to use any pipes in the PowerShell command they must be triple-escaped with carats to work properly
^^^|
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20958388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Custom camera UI for wp8 I tried to create an image based app that actually uses camera task when the app is opened. But instead of using the default camera app, I am trying to create a custom UI for the camera like other third-party apps does. Well, my camera UI will be basic, so i would like to know whether this can be achieved within the CameraCaptureTask or do i need to create some separate UserControl page?
I am not able to find any resource or samples for this issue.
Thanks in advance for your help.
A: You can use PhotoCamera class for this.
This MSDN page clearly explains how to stream and capture images using camera
The code given below shows how to initialize PhotoCamera
PhotoCamera myCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
//viewfinderBrush is a videobrush object declared in xaml
viewfinderBrush.SetSource(myCamera);
myCamera.Initialized += myCamera_Initialized;
myCamera.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
myCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30383023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change location.href with jQuery I need to change the location.href of some URLs on my site. These are product cards and they do not contain "a" (which would make this a lot easier).
Here is the HTML:
<div class="product-card " onclick="location.href='https://www.google.com'">
I mean it is pretty simple, but I just cannot get it to work. Did not find any results from Google without this type of results, all of which contain the "a":
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
Any ideas on how to get this to work with jQuery (or simple JS)?
I cannot change the code itself unfortunaltely, I can just manipulate it with jQuery and JS.
A: To change the onClick for all the class='product-card', you can do something like this:
// All the links
const links = document.getElementsByClassName('product-card');
// Loop over them
Array.prototype.forEach.call(links, function(el) {
// Set new onClick
el.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
});
<div class="product-card " onclick="location.href='https://www.google.com'">Test</div>
Will produce the following DOM:
<div class="product-card " onclick="location.href = 'http://www.live.com/'">Test</div>
Another option, is to loop over each <div> and check if something like google.com is present in the onClick, if so, we can safely change it without altering any other divs with the same class like so:
// All the divs (or any other element)
const allDivs = document.getElementsByTagName('div');
// For each
Array.from(allDivs).forEach(function(div) {
// If the 'onClick' contains 'google.com', lets change
const oc = div.getAttributeNode('onclick');
if (oc && oc.nodeValue.includes('google.com')) {
// Change onClick
div.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
}
});
<div class="product-card" onclick="location.href='https://www.google.com'">Change me</div>
<div class="product-card">Don't touch me!</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67723886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Current location using an IP address and the iPhone SDK In an application there is extreme use of the current location, and I got success in using the current location, but I am not able to find the current location in a house or basement, etc. So what I think that we can use is the IP address to get the location and then I will get the longitude and latitude.
I am not getting the current location while using the IP address (I can find the IP address) in iPhone. How do I sort out the issue.
A: First check whether your GPS is on in your device. You can use CLLocationManager to get your current location.
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
//Get your current location here
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error{
}
Use these methods to get the location.
A: I am not sure what the question is, but I think you have an IP address and you want to know which location is associated with it, right ? If so, you're out of luck. There are some databases to map these, but they can only tell you where the owner of the IP is located... and that is your ISP, not you (the customer).
On iOS, there's Core Location, doesn't that work for you ?
A: I am using the same, and it works fine when I am outside of my house, but in case I am inside the house or in basement it doesn't get the current location.
I am saying while using the IP address we can get the location so we will have a current location and then we can get the longitude and latitude of a particular location using g.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5141380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Django, passing JSON to frontend, 'str' doesn't have 'iteritems' I'm creating json data this way:
def get_all_from_database():
urls = Url.objects.all()
ips = Ip.objects.all()
urls_json = serializers.serialize('json', urls)
ips_json = serializers.serialize('json', ips)
return urls_json, ips_json
and I try to pass it to frontend using ajax:
@csrf_exempt
def send_results(request):
if request.is_ajax():
address = request.POST.get('url')
urls, ips = get_all_from_database()
return HttpResponse(urls, ips)
js code:
$.ajax({
type: "POST",
url: "/link_finder/send_results/",
data: {
url : web_page,
},
success: function(data) {
alert(data);
},
error: function(xhr, textStatus, errorThrown) {
alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText);
}
And I get this error:
INTERNAL SERVER ERROR500AttributeError at /link_finder/send_results/
'str' object has no attribute 'iteritems'
Why? And what should I change?
A: HttpResponse takes only one body argument, you are passing in two.
Don't create two JSON strings, build one, using a custom serializer to handle multiple querysets:
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.core import serializers
from django.db.models.query import QuerySet
def get_all_from_database():
urls = Url.objects.all()
ips = Ip.objects.all()
return urls, ips
class HandleQuerySets(DjangoJSONEncoder):
""" JSONEncoder extension: handle querysets """
def default(self, obj):
if isinstance(obj, QuerySet):
return serializers.serialize("python", obj, ensure_ascii=False)
return super(HandleQuerySets, self).default(obj)
@csrf_exempt
def send_results(request):
if request.is_ajax():
address = request.POST.get('url')
urls, ips = get_all_from_database()
data = HandleQuerySets().encode({'urls': urls, 'ips': ips})
return HttpResponse(data, content_type='application/json')
I've also set the correct Content-Type header for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21701475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set type for variables from form data in Lumen framework. If I send form in Lumen, data can be validated via validate method. For example, in some method in some controller:
$this->validate($request, [
'id' => 'required|integer|exists:user',
]);
$user_id = $request->input('id');
But variable type of $user_id still string. Is there any built in (in framework) methods for getting variable in type which I write? In this case is integer.
I use intval() now.
A: Unfortunately, to my knowledge there's no way to define what types input should have in Laravel/Lumen when the value is accessed.
PHP interprets all user input as strings (or arrays of strings).
In Illuminate\Validation\Validator, the method that determines if a value is an integer uses filter_var() to test if the string value provided by the user conforms to the rules of the int type.
Here's what it's actually doing:
/**
* Validate that an attribute is an integer.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
protected function validateInteger($attribute, $value)
{
if (! $this->hasAttribute($attribute)) {
return true;
}
return is_null($value) || filter_var($value, FILTER_VALIDATE_INT) !== false;
}
Alas, it does not then update the type of the field it checks, as you have seen.
I think your use of intval() is probably the most appropriate option if you absolutely need the value of the user_id field to be interpreted as an integer.
Really the only caveat of using intval() is that it is limited to returning integers according to your operating system.
From the documentation (http://php.net/manual/en/function.intval.php):
32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.
So as long as you keep your user-base to less than 2,147,483,647 users, you shouldn't have any issues with intval() if you're on a 32-bit system. Wouldn't we all be so lucky as to have to worry about having too many users?
Joking aside, I bring it up because if you're using intval() for a user-entered number that might be huge, you run the risk of hitting that cap. Probably not a huge concern though.
And of course, intval() will return 0 for non-numeric string input.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35577313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mixing script and static in app.yaml I wish to use Google App Engine for serve static files and REST request in one application.
I use this app.yaml
application: test
version: 1
runtime: go
api_version: go1
default_expiration: "7d 5h"
handlers:
- url: /(index.html)?
static_files: static/app/index.html
upload: static/app/index.html
http_headers:
Content-Type: text/html; charset=UTF-8
- url: /
static_dir: static/app/
http_headers:
Vary: Accept-Encoding
- url: /.*
script: _go_app
It works for static files, but I can't access to my script.
package main
import (
"fmt"
"net/http"
)
func init() {
http.HandleFunc("/hello_world", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, world!")
}
It's possible? If yes, how I can to proceed?
A: Yes, it's possible for an app to serve both static files and dynamic content. Actually there's nothing magical required for it, this is normal for most web applications.
Your configuration looks ok. One thing you should change: the package of your go file.
Don't use package main, instead use another package and make sure your .go file is put into that. For example if you name your package mypackage, use this folder structure:
+ProjectRoot
app.yaml
+mypackage
myfile.go
And start your myfile.go with line:
package mypackage
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30664333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How reduce stock quantity in SQL Server and show messagebox when is zero in C# The update is working fine, but stock value when is purchased I want to show messagebox, and stop the purchase when the value is zero in the stock update code.
I tried this code, but he only reduces value if the quantity is zero showing minus in the stock value when to stop when the value is equal to zero.
private void updateQty()
{
try
{
int newqty = stock - Convert.ToInt32(txtnumberofunit.Text);
con.Open();
SqlCommand cmd = new SqlCommand("Update medic Set quantity=@q where id=@Xkey ", con);
//stock=Convert.ToInt32(dr)
cmd.Parameters.AddWithValue("@q", newqty);
cmd.Parameters.AddWithValue("@Xkey", key);
cmd.ExecuteNonQuery();
MessageBox.Show("Medicine updated!!");
con.Close();
//showExpenses();
//Reset();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
A: The following first asserts there is sufficient stock, if not, alert caller else update the stock. This assumes no other users are working with the same item.
Note the use of delegates and that the database does not match your database but the same will work for your code with adjustments.
public class DataOperations
{
private const string ConnectionString
= "Data Source=.\\sqlexpress;Initial Catalog=NorthWind2020;Integrated Security=True";
public delegate void OnProcessing(string text);
public static event OnProcessing Processed;
public static void UpdateProductStockCount(int id, int amount)
{
using (var cn = new SqlConnection(ConnectionString))
{
using (var cmd = new SqlCommand() { Connection = cn })
{
cmd.CommandText = "SELECT UnitsInStock FROM dbo.Products WHERE ProductID = @Id";
cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id;
cn.Open();
var currentCount = (short)cmd.ExecuteScalar();
if (currentCount - amount <0)
{
Processed?.Invoke("Insufficient stock");
}
else
{
cmd.CommandText = "UPDATE dbo.Products SET UnitsInStock = @InStock WHERE ProductID = @Id";
cmd.Parameters.Add("@InStock", SqlDbType.Int).Value = currentCount - amount;
cmd.ExecuteNonQuery();
Processed?.Invoke("Processed");
}
}
}
}
}
Form code
public partial class StackoverflowForm : Form
{
public StackoverflowForm()
{
InitializeComponent();
DataOperations.Processed += DataOperationsOnProcessed;
}
private void DataOperationsOnProcessed(string text)
{
if (text == "Insufficient stock")
{
MessageBox.Show($"Sorry {text} ");
}
else
{
MessageBox.Show(text);
}
}
private void updateButton_Click(object sender, EventArgs e)
{
DataOperations.UpdateProductStockCount(21,1);
}
}
A: As @BagusTesa suggested, a simple if could do the trick:
private void updateQty()
{
try
{
int newqty = stock - Convert.ToInt32(txtnumberofunit.Text);
if (newqty >= 0) // proceed
{
con.Open();
SqlCommand cmd = new SqlCommand("Update medic Set quantity=@q where id=@Xkey ", con);
cmd.Parameters.AddWithValue("@q", newqty);
cmd.Parameters.AddWithValue("@Xkey", key);
cmd.ExecuteNonQuery();
MessageBox.Show("Medicine updated!!");
con.Close();
}
else // cancel purchase
{
MessageBox.Show("New quantity is below 0, purchase cancelled");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74506455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Defining a number as an image So I am making a 2d game hardcoded with wxWidgets, and I'd like at the top to say something like #Define 2 hero.png or wall.png or monster.png, etc. So my idea was originally to just swap values in the matrix, and move the png around but how can I define the object so when the program reads my grid, it know what png to use? All help is greatly appreciated.
My Grid is like:
{0,0,0,0,0,0}
{0,0,0,0,0,0}
{0,0,2,1,1,1}
{0,0,0,0,0,1}
{0,0,0,0,0,1}
{0,3,1,1,1,0}
A: You can create a dictionary that relates the number to the image name.
You can use the following syntax:
std::map<char, const char*> my_map = {
{ '1', 'hero.png' },
{ '2', 'wall.png' },
{ '3', 'monster.png' }
};
And you can search by the number inside this map. The docs are:
http://www.cplusplus.com/reference/map/map/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43288949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Handling conflicts in CouchDB Say I have a doc with two properties, "Start" and "End." One revision may have a time for Start and null for End, and vice versa. Rather than choosing a single revision as the winner, I want the final doc to contain the Start time from the revision where it is not null, and same for End.
Are there any best practices for handling this type of conflict resolution during a sync? Documentation I have found contains instructions for choosing a single revision as the winner, but I'd like to select values from multiple revs.
Examples specific to C#/MyCouch library would be great, but any general or other language advice is also much appreciated.
A: You cannot specify a custom way of conflict resolution during replication (a.k.a. sync). CouchDB automatically chooses the winning revision, and you cannot influence that:
By default, CouchDB picks one arbitrary revision as the "winner",
using a deterministic algorithm so that the same choice will be made
on all peers.
You can wait for the replication to finish and handle conflicts afterwards, by performing application-specific merging of document revisions.
Looking into the documentation for Working with conflicting documents, I found the following pseudocode example:
*
*GET docid?conflicts=true
*For each member in the _conflicts array:
GET docid?rev=xxx
If any errors occur at this stage, restart from step 1.
(There could be a race where someone else has already resolved this
conflict and deleted that rev)
*Perform application-specific merging
*Write _bulk_docs with an update to the first rev and deletes of
the other revs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38727207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the difference between these statements I have these two statements. What is the difference between
string(sample_string).erase(i,j)
and
sample_string.erase(i,j) ?
A:
sample_string.erase(i,j)
Calls the erase method on the sample_string object (assuming that this is an instance of a class that implements this method).
string(sample_string).erase(i,j)
Creates a temporary instance of the string class, calling a string constructor using the sample_string object for initialization of the string, and then calls the erase method on that temporary object.
A: I suppose the type of simple_string is std::string. the code
string(sample_string).erase(i, j)
looked cannot work because string(sample_string) returns a temp obj, and then called erase method on the temporary string object. There is nothing to do with sample_string.
A: The first one, string(sample_string).erase(i,j) creates a temporary string, and erases from that temporary string.
The second erases from the string object sample_string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30613707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I declare GlyphRun object? I need to draw just a couple of digits. Is it enough to define only GlyphRun and FontRenderingEmSize? If not, please, suggest me, how to draw, for example, string "123" (how to define GlyphRun object for that). I wrote this code:
var gr = new GlyphRun();
gr.Characters = new List<char>() { '1', '2' }; //Mistake
gr.FontRenderingEmSize = 20;
var Glyph = new GlyphRunDrawing(Brushes.Black, gr);
A: I found this old helper class of mine. Maybe you can make use of it.
public static class GlyphRunText
{
public static GlyphRun Create(
string text, Typeface typeface, double emSize, Point baselineOrigin)
{
GlyphTypeface glyphTypeface;
if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
{
throw new ArgumentException(string.Format(
"{0}: no GlyphTypeface found", typeface.FontFamily));
}
var glyphIndices = new ushort[text.Length];
var advanceWidths = new double[text.Length];
for (int i = 0; i < text.Length; i++)
{
var glyphIndex = glyphTypeface.CharacterToGlyphMap[text[i]];
glyphIndices[i] = glyphIndex;
advanceWidths[i] = glyphTypeface.AdvanceWidths[glyphIndex] * emSize;
}
return new GlyphRun(
glyphTypeface, 0, false, emSize,
glyphIndices, baselineOrigin, advanceWidths,
null, null, null, null, null, null);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73101580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Class Name does not declare type C++ I am trying to compile my code, but I am getting an error with classes. One of the classes compiled fine(Example.h), but the other(Name.h) keeps giving me the class does not name type error. I think it has something to do with circular dependency, but how do I fix that without a forward deceleration?
Name.h
#ifndef _NAME
#define _NAME
#include <iostream>
#include <string>
using namespace std;
#include "Example.h"
class Name{
};
#endif
Example.h
#ifndef _EXAMPLE
#define _EXAMPLE
#include <iostream>
#include <string>
using namespace std;
#include "Name.h"
class Example{
};
#endif
I saw a post about using forward deceleration, but I need to access memebers from the Example class..
A: You have a circular dependency, where each header tries to include the other, which is impossible. The result is that one definition ends up before the other, and the name of the second is not available within the first.
Where possible, declare each class rather than including the entire header:
class Example; // not #include "Example.h"
You won't be able to do this if one class actually contains (or inherits from) another; but this will allow the name to be used in many declarations. Since it's impossible for both classes to contain the other, you will be able to do this (or maybe just remove the #include altogether) for at least one of them, which should break the circular dependency and fix the problem.
Also, don't use reserved names like _NAME, and don't pollute the global namespace with using namespace std;
A: see, here you are including #include "Example.h" in Name.h and #include "Name.h" in Example.h. suppose compiler compiles Name.h file first so _NAME is defined now, then it tries to compile Example.h here compiler wants to include Name.h but the content of Name.h will not be included in Example.h since _NAME is already defined, hence class Name is not defined inside Example.h.
you can explicitly do forward declaration of class Name; inside Example.h
A: Try this:
Name.h
#ifndef NAMEH
#define NAMEH
#include <iostream>
#include <string>
using namespace std;
//#include "Example.h"
class Example;
class Name{
};
#endif
Name.cpp
#include "Name.h"
#include "Example.h"
...
Example.h
#ifndef EXAMPLEH
#define EXAMPLEH
#include <iostream>
#include <string>
using namespace std;
//#include "Name.h"
class Name;
class Example{
};
#endif
Example.cpp
#include "Example.h"
#include "Name.h"
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22627682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Facebook Android API- How to know when friend list of a user has updated? Currently i am working on facebook based android application and i store all friends of user to a sqlite database on login. I want to update this database only when user adds or removes a friend. How to know friend list updated not?? any FQL or Graph api calls regarding this??
Note: checking friend count is not a good solution because if user adds a new friend and removes an existing one then we go wrong!
Another solution is comparing our database friends with the friend list from facebook server, but its long process if user have large number of friends.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18372997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calculating distance between latitude and longitude in python? I need help calculating the distance between two points-- in this case, the two points are longitude and latitude. I have a .txt file that contains longitude and latitude in columns like this:
-116.148000 32.585000
-116.154000 32.587000
-116.159000 32.584000
The columns do not have headers. I have many more latitudes and longitudes.
So far, i have come up with this code:
from math import sin, cos, sqrt, atan2, radians
R = 6370
lat1 = radians() #insert value
lon1 = radians()
lat2 = radians()
lon2 = radians()
dlon = lon2 - lon1
dlat = lat2- lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1-a))
distance = R * c
print (distance)
Many of the answers/code i've seen on stack overflow for calculating the distance between longitude and latitude have had longitude and latitude assigned as specific values.
I would like the longitude and latitude to equal the values in the columns they are in and for the equation to go through all of the longitudes and latitudes and calculate the distance.
I have not been able to come up with something to do this. Any help would be appreciated
A: Based on the question it sounds like you would like to calculate the distance between all pairs of points. Scipy has built in functionality to do this.
My suggestion is to first write a function that calcuates distance. Or use an exisitng one like the one in geopy mentioned in another answer.
def get_distance(point1, point2):
R = 6370
lat1 = radians(point1[0]) #insert value
lon1 = radians(point1[1])
lat2 = radians(point2[0])
lon2 = radians(point2[1])
dlon = lon2 - lon1
dlat = lat2- lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1-a))
distance = R * c
return distance
Then you can pass this function into scipy.spatial.distance.cdist
all_points = df[[latitude_column, longitude_column]].values
dm = scipy.spatial.distance.cdist(all_points,
all_points,
get_distance)
As a bonus you can convert the distance matrix to a data frame if you wish to add the index to each point:
pd.DataFrame(dm, index=df.index, columns=df.index)
NOTE: I realized I am assuming, possibly incorrectly that you are using pandas
A: If you don't mind importing a few libraries, this can be done very simply.
With pandas, you can read your text file into a dataframe, which makes working with tabular data like this super easy.
import pandas as pd
df = pd.read_csv('YOURFILENAME.txt', delimiter=' ', header=None, names=('latitude', 'longitude'))
Then you can use the geopy library to calculate the distance.
A: Another solution is using the haversine equation with numpy to read in the data and calculate the distances. Any of the previous answers will also work using the other libraries.
import numpy as np
#read in the file, check the data structure using data.shape()
data = np.genfromtxt(fname)
#Create the function of the haversine equation with numpy
def haversine(Olat,Olon, Dlat,Dlon):
radius = 6371. # km
d_lat = np.radians(Dlat - Olat)
d_lon = np.radians(Dlon - Olon)
a = (np.sin(d_lat / 2.) * np.sin(d_lat / 2.) +
np.cos(np.radians(Olat)) * np.cos(np.radians(Dlat)) *
np.sin(d_lon / 2.) * np.sin(d_lon / 2.))
c = 2. * np.arctan2(np.sqrt(a), np.sqrt(1. - a))
d = radius * c
return d
#Call function with your data from some specified point
haversine(10,-110,data[:,1],data[:,0])
In this case, you can pass a single number for Olat,Olon and an array for Dlat,Dlon or vice versa and it will return an array of distances.
For example:
haversine(20,-110,np.arange(0,50,5),-120)
OUTPUT
array([2476.17141062, 1988.11393057, 1544.75756103, 1196.89168113,
1044.73497113, 1167.50120561, 1499.09922502, 1934.97816445,
2419.40097936, 2928.35437829])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57294120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Could not cast value of type NSSingleObjectArray to NSMutableArray Since iOS10, i am facing to this issue :
Could not cast value of type '__NSSingleObjectArrayI' to
'NSMutableArray' .
There is my code :
manage.POST( url, parameters: params,
constructingBodyWithBlock: { (data: AFMultipartFormData!) in
//Some stuff here
},
success: { (operation: NSURLSessionDataTask?, responseObject: AnyObject?) in
var array : NSMutableArray!
if AppConfig.sharedInstance().OCR == "2"{
let dictionnary = responseObject as! NSDictionary
array = dictionnary["data"]! as! NSMutableArray
}else{
//!!!!CRASH HERE!!!!!
array = responseObject as! NSMutableArray
}
//Some stuff after
}
When i look for responseObject value, i have this in my console :
Printing description of responseObject:
▿ Optional<AnyObject>
▿ Some : 1 elements
- [0] : Test
How can i extract value "Test" from responseObject ?
Many thanks
A: When we deal with response from web server then we can't sure about objects and types. So it is better to check and use objects as per our need. See for your reference related to your question.
if let dictionnary : NSDictionary = responseObject as? NSDictionary {
if let newArr : NSArray = dictionnary.objectForKey("data") as? NSArray {
yourArray = NSMutableArray(array: newArr)
}
}
By this your app will never crashed as it is pure conditional for your needed objects with checking of types. If your "data" key is array then only it will proceed for your array. Thanks.
A: The crash happens because you assume that the object you receive is NSMutableArray, even though the object has been created outside your code.
In this case, an array that your code gets is an instance of an array optimized for handling a single element; that is why the cast is unsuccessful.
When this happens, you can make a mutable copy of the object:
array = (dictionnary["data"]! as! NSArray).mutableCopy() as! NSMutableArray
and
array = (responseObject as! NSArray).mutableCopy() as! NSMutableArray
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39723539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: syntax error near unexpected token - R package Install I am trying to install an R package along with its dependencies. But it is throwing error.
$ install.packages(rvest_0.3.5.tar.gz, dependencies=True)
-bash: syntax error near unexpected token `rvest_0.3.5.tar.gz,'
I am new to R please help me how can I download this along with it dependencies.
Before this, I tried following
$ R CMD INSTALL rvest_0.3.5.tar.gz
* installing to library ‘/Library/Frameworks/R.framework/Versions/4.0/Resources/library’
ERROR: dependencies ‘httr’, ‘magrittr’, ‘selectr’ are not available for package ‘rvest’
But it failed with dependent packages are missing error. And obviously it is cumbersome to install the dependent packages manually. Hence I tried package.install
A: You need to run it with quotes and capital TRUE:
install.packages("rvest_0.3.5.tar.gz", dependencies = TRUE)
Note this will only work if you have unix-like system and the file is located in your current working directory (check with running getwd() from your R session). Otherwise you need to provide full path to the file (like "~/somefolder/mydata/rvest_0.3.5.tar.gz").
If you run Windows, then you need .zip file instead of .tar.gz.
If you are connected to internet, just run:
install.packages("rvest")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62356163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Snakemake: Random FileNotFoundError for a shared file in a rule when submitting jobs in parallel I have the following rule:
rule run_example:
input:
counts=config['output_dir'] + "/Counts/skin.txt"
params:
chrom=lambda wildcards: gene_chrom()[wildcards.SigGene]
output:
config['out_refbias'] + "/{SigGene}.txt"
script:
"Scripts/run_example.R"
with SigGene=["gene1", "gene2"]
I define the following function:
def gene_chrom(File=config['output_dir'] + "/genes2test.txt", sep=" "):
""" Makes a dictionary with keys gene and values chromosome from a file with first col gene_id and second col CHROM """
data=pd.read_csv(File, sep=sep)
keys=list(data['gene_id'])
values=[str(x) for x in data['CHROM']]
dic=dict(zip(keys,values))
return dic
I submit the rule to a cluster to run jobs in parallel. For some jobs I get the following error message:
FileNotFoundError in line 67 of Snakefile:
[Tue Jun 23 09:47:16 2020] [Errno 2] File b'/scratch/genes2test.txt' does not exist: b'/scratch/genes2test.txt'
The file exist and is shared among all instances of the rule. Most jobs were able to read the file and run to completion but some failed with above error message.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62531737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using @use "sass:math" in a Vue component In a Nuxt 2 project i have created a button component with the following style:
<style lang="scss">
.my-button {
// lots of cool styles and stuff here
$height: 28px;
height: $height;
border-radius: $height / 2;
}
</style>
The problem is the border-radius: $height / 2; line gives this warning:
╷
182 │ border-radius: $height / 2;
│ ^^^^^^^^^^^
╵
components/MyButton.vue 182:20 button-size()
components/MyButton.vue 186:5 root stylesheet
: Using / for division is deprecated and will be removed in Dart Sass
2.0.0.
Recommendation: math.div($height, 2)
It also links to this page describing the deprecation.
However if i add @use "sass:math" to the top of my style tag like so:
<style lang="scss">
@use "sass:math";
//Cool styles and stuff
$height: 28px;
height: $height;
border-radius: math.div($height, 2);
</style>
I get this error:
[Vue warn]: Error in render: "Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): 12:13:59
SassError: @use rules must be written before any other rules.
╷
102 │ @use "sass:math";
│ ^^^^^^^^^^^^^^^^
╵
components/MyButton.vue 102:1 root stylesheet"
I think i need to add the import of @use "sass:math" somewhere in nuxt.config.js file to load it in all components or similar, but i am not able to figure out where.
The css related blocks in my nuxt.config.js currently looks like:
build: {
postcss: {
plugins: {
'postcss-easing-gradients': {},
},
},
},
styleResources: {
scss: [
'~/assets/global-inject.scss',
],
},
css: [
'~/assets/base.scss',
'~/assets/reset.scss',
],
A: Updating @nuxtjs/style-resources to above version 1.1 and using hoistUseStatements fixed it.
I changed the styleResources object in nuxt.config.js to:
styleResources: {
scss: [
'~/assets/global-inject.scss',
],
hoistUseStatements: true,
},
and added @use "sass:math"; to the top of global-inject.scss.
A: Updated answer
What if you try this in your nuxt.config.js file?
{
build: {
loaders: {
scss: {
additionalData: `
@use "@/styles/colors.scss" as *;
@use "@/styles/overrides.scss" as *;
`,
},
},
...
}
Or you can maybe try one of the numerous solutions here: https://github.com/nuxt-community/style-resources-module/issues/143
Plenty of people do have this issue but I don't really have a project under my belt to see what is buggy. Playing with versions and adding some config to the nuxt config is probably the way to fix it yeah.
Also, if it's a warning it's not blocking so far or does it break your app somehow?
Old answer
My answer here can probably help you: https://stackoverflow.com/a/68648204/8816585
It is a matter of upgrading to the latest version and to fix those warnings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69161159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Collapsing a data frame over one variable I have a data frame in the following format:
Site Year Month Count1 Count2 Count3 Patch
1 1 May 15 12 10 1
1 1 May 8 0 5 2
1 1 May 3 1 2 3
1 1 May 4 4 1 4
1 1 June 6 5 1 1
1 1 June 9 1 3 2
1 1 June 3 0 0 3
1 1 June 5 5 2 4
1 1 July 4 0 3 1
..........
And I wish to collapse the data frame across the levels of patch such that the three count variables are summed. i.e.
Site Year Month Count1 Count2 Count3
1 1 May 30 17 18
1 1 June 23 11 6
1 1 July 4 0 3
.........
I've looked at the aggregate and tapply commands, but they do not seem to sum across patch as required.
Can somebody please advise on a command that will convert the data accordingly.
Thank you.
A: library(dplyr)
dat %>%
group_by(Site, Year, Month) %>%
summarise_each(funs(sum=sum(., na.rm=TRUE)), Count1:Count3)
# Source: local data frame [3 x 6]
#Groups: Site, Year
# Site Year Month Count1 Count2 Count3
# 1 1 1 July 4 0 3
# 2 1 1 June 23 11 6
# 3 1 1 May 30 17 18
A: Or data.table solution (which will keep your data sorted by the original month order)
library(data.table)
setDT(df)[, lapply(.SD, sum),
by = list(Site, Year, Month),
.SDcols = paste0("Count", seq_len(3))]
# Site Year Month Count1 Count2 Count3
# 1: 1 1 May 30 17 18
# 2: 1 1 June 23 11 6
# 3: 1 1 July 4 0 3
A: With aggregate:
> ( a <- aggregate(.~Site+Year+Month, dat[-length(dat)], sum) )
# Site Year Month Count1 Count2 Count3
# 1 1 1 July 4 0 3
# 2 1 1 June 23 11 6
# 3 1 1 May 30 17 18
Where dat is your data.
Note that your July results in the post are seem to be incorrect.
For the result in the order of the original data, you can use
> a[order(as.character(unique(dat$Month))), ]
# Site Year Month Count1 Count2 Count3
# 3 1 1 May 30 17 18
# 2 1 1 June 23 11 6
# 1 1 1 July 4 0 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25555154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where can I find an extension or website with PHP user snippets to be used in an HTML file? (Visual Studio Code) I recently installed the extension PHP Awesome Snippets of Visual Studio Code, which includes lots of useful snippets for PHP programming. However, the snippets of this extension can only be used within php tags.
For example, if you want to get the following structure in HTML:
<?php if(): ?>
<?php endif; ?>
You won't be able to get it by typing the 'ifen' snippet of this extension in HTML.
Now the question is: do you know any extension for Visual Code Studio that provides a list of snippets similar to PHP Awesome Snippets but that are also available to use in an HTML file? In case there isn't such extension, do you know of any website where someone has shared a list of them (with the code to incorporate in the HTML.json file)?
I can't imagine everyone is hardcoding User Snippets for this, when it seems to me something that is very often repeated by many people, but so far I haven't found any extension nor website for this purpose.
A: Edit: Relevant extension is this PHP Snippets VS Code on the marketplace which works even inside html files without the <?php tag declaration.
Since that extension doesn't have any settings for itself. The easy way of doing this is to create a workspace setting file, settings.json in you project/.vscode/ folder.
And add this to the settings
settings.json
{
// all other settings
"files.associations": {
"*.html": "php",
}
}
.code-workspace file
{
"folders": [
{
"path": "."
}
],
"settings": {
"files.associations": {
"*.html": "php",
}
}
}
What this does is tell VScode to treat all HTML files as PHP. It shouldn't be much of an issue because, Emmet snippets will work along with the snippets from this extension.
This is better to be added as workspace/project setting because, it won't affect other projects where you might be working on another language.
One more way is to doing manually file by file, if you want to. You can click on the language identifier in the status bar and change it to PHP and you will enable snippets in the file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62533059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble with Rails assets in production I've ran
rake assets:precompile
RAILS_ENV=production rake assets:precompile
git add -A
git commit -m "message"
git push heroku master
This is the live site - http://www.collegeinsideview.com/.
It seems that none of the assets are available. I can't figure out why.
*
*Both of the precompile commands seem to have worked.
*In development, my public/assets/ folder is filled with the assets (with the fingerprints at the end; ex. adelphi_social_atmosphere_7-c13258f14849b2f66e162688b9c9228f.png).
*There weren't any errors with pushing to heroku.
production.rb
Collegeanswers::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Add the fonts path
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( about_college.css college_pages.css colleges.css essay_list.css
essays.css home.css layout.css static_pages.css tldr.css college_pages.js essays.js home.js static_pages.js favicon.ico .svg .eot .woff .ttf)
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# config.action_controller.asset_host = "https://#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com"
config.eager_load = true
end
home.html
<% content_for(:title, 'College Inside View') %>
<div id="home_css">
<!--<%= link_to "Get Paid to Answer Questions", "/the-deal", id: "the_deal", class: "btn btn-link" %>-->
<h1 id="heading">In-Depth Reviews of Colleges</h1>
<div class="tabbable">
<div class="tab-content">
<div class="tab-pane fade active in" id="columbia">
<div class="left_pane">
<%= image_tag "columbia1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "columbia2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "columbia3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Columbia • •".html_safe, "/columbia/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>How does the workload impact your social life?</strong></p>
<%= image_tag "columbia_social_atmosphere_7.png", class: 'answers' %>
<%= link_to '--read more--', '/columbia/social-life/social-atmosphere/7', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="princeton">
<div class="left_pane">
<%= image_tag "princeton1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "princeton2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "princeton3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Princeton • •".html_safe, "/princeton/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>How would you make your classes better?</strong></p>
<%= image_tag "princeton_classes_6.png", class: 'answers' %>
<%= link_to '--read more--', '/princeton/academics/classes/6', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="brown">
<div class="left_pane">
<%= image_tag "brown1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "brown2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "brown3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Brown • •".html_safe, "/brown/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>Are people intellectual? Do they have thoughtful conversations with each other?</strong></p>
<%= image_tag "brown_social_atmosphere_5.png", class: 'answers' %>
<%= link_to '--read more--', '/brown/social-life/social-atmosphere/5', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="penn">
<div class="left_pane">
<%= image_tag "university-of-pennsylvania1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "university-of-pennsylvania2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "university-of-pennsylvania3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Penn • •".html_safe, "/university-of-pennsylvania/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>Are your classes too hard, or too easy? Why?</strong></p>
<%= image_tag "penn_dificulty_4.png", class: 'answers' %>
<%= link_to '--read more--', '/university-of-pennsylvania/academics/difficulty/4', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="yale">
<div class="left_pane">
<%= image_tag "yale1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "yale2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "yale3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Yale • •".html_safe, "/yale/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>Is it easy to make friends? How did you make friends?</strong></p>
<%= image_tag "yale_social_atmosphere_1.png", class: 'answers' %>
<%= link_to '--read more--', '/yale/social-life/social-atmosphere/1', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="cornell">
<div class="left_pane">
<%= image_tag "cornell1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "cornell2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "cornell3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Cornell • •".html_safe, "/cornell/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>Mary Donlon Hall</strong></p>
<%= image_tag "cornell_housing_mary_donlon_hall.png", class: 'answers' %>
<%= link_to '--read more--', '/cornell/living-environment/housing/mary-donlon-hall', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="harvard">
<div class="left_pane">
<%= image_tag "harvard1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "harvard2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "harvard3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Harvard • •".html_safe, "/harvard/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>Are there comfortable places to study?</strong></p>
<%= image_tag "harvard_campus_2.png", class: 'answers' %>
<%= link_to '--read more--', '/harvard/academics/classes/5', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="dartmouth">
<div class="left_pane">
<%= image_tag "dartmouth1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "dartmouth2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "dartmouth3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Dartmouth • •".html_safe, "/dartmouth/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>Do professors make things easy to understand?</strong></p>
<%= image_tag "dartmouth_professors_1.png", class: 'answers' %>
<%= link_to '--read more--', '/dartmouth/academics/professors/1', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="pitt">
<div class="left_pane">
<%= image_tag "university-of-pittsburgh1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "university-of-pittsburgh2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "university-of-pittsburgh3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Pitt • •".html_safe, "/university-of-pittsburgh/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>Neuroscience: What are people in the major like? How would you stereotype them?</strong></p>
<%= image_tag "pitt_neuroscience_8.png", class: 'answers' %>
<%= link_to '--read more--', '/university-of-pittsburgh/academics/majors/neuroscience/8', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="wisconsin">
<div class="left_pane">
<%= image_tag "university-of-wisconsin1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "university-of-wisconsin2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "university-of-wisconsin3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Wisconsin • •".html_safe, "/university-of-wisconsin/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>How much will not partying limit your social life?</strong></p>
<%= image_tag "wisconsin_parties_3.png", class: 'answers' %>
<%= link_to '--read more--', '/university-of-wisconsin/social-life/parties/3', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="colgate">
<div class="left_pane">
<%= image_tag "colgate1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "colgate2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "colgate3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Colgate • •".html_safe, "/colgate/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>Who wouldn't fit in?</strong></p>
<%= image_tag "colgate_social_atmosphere_2.png", class: 'answers' %>
<%= link_to '--read more--', '/colgate/social-life/social-atmosphere/2', class: 'read_more' %>
</div>
</div>
<div class="tab-pane fade" id="adelphi">
<div class="left_pane">
<%= image_tag "adelphi-university1.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "adelphi-university2.jpg", size: "297x187", class: 'picture' %>
<%= image_tag "adelphi-university3.jpg", size: "297x187", class: 'picture' %>
<%= link_to "• • Read more about Adelphi • •".html_safe, "/adelphi-university/academics/professors/1", class: 'school_link' %>
</div>
<div class="right">
<p class="question" class="well"><strong>How's the on-campus food (taste, price, health, convenience, hours, variety...)?</strong></p>
<%= image_tag "adelphi_food_1.png", class: 'answers' %>
<%= link_to '--read more--', '/adelphi-university/living-environment/food/1', class: 'read_more' %>
</div>
</div>
</div>
<ul id="left" class="nav nav-pills nav-stacked">
<li id="columbia" class="active"><a href="#columbia">Columbia</a></li>
<li id="princeton"><a href="#princeton">Princeton</a></li>
<li id="brown"><a href="#brown">Brown</a></li>
<li id="penn"><a href="#penn">Penn</a></li>
<li id="yale"><a href="#yale">Yale</a></li>
<li id="cornell"><a href="#cornell">Cornell</a></li>
<li id="harvard"><a href="#harvard">Harvard</a></li>
<li id="dartmouth"><a href="#dartmouth">Dartmouth</a></li>
<li id="pitt"><a href="#pitt">Pitt</a></li>
<li id="wisconsin"><a href="#wisconsin">Wisconsin</a></li>
<li id="colgate"><a href="#colgate">Colgate</a></li>
<li id="adelphi"><a href="#adelphi">Adelphi</a></li>
</ul>
</div>
<div id="notify">
<p>Right now I only have reviews for those 12 schools. Enter your email below to be notified when there's more!</p>
<span id="notify_span">
<%= simple_form_for :subscribe, url: 'subscribe' do |f| %>
<%= f.input :email, placeholder: '[email protected]', label: false, required: true %> <br/>
<%= f.button :submit, "1-Click Sign Up", class: "btn btn-primary", data: { :disable_with => "Submitting..." } %>
<% end %>
</span>
</div>
<ul id="bottom_links">
<li><%= link_to "I Graduated High School. Now What?", "/i-graduated-high-school-now-what" %></li>
<li><%= link_to "How to Choose a College", "/how-to-choose-a-college" %></li>
<li><%= link_to "How College Inside View Got Started", "https://medium.com/what-i-learned-building/322e8668ed6f" %></li>
</ul>
<!--<section id="section1">
<h1 id="main_head">Answers to the questions<br />
that go unasked.<br /><br />
<em>Finally!</em></h1>
<section id="example_questions">
<ul>
<li><span class="label label-info">Academics</span> What are the people in the economics major like? How would you stereotype them?</li>
<li><span class="label label-info">Academics</span> Would you go to class if you didn't have to?</li>
<li><span class="label label-info">Living Environment</span> Where can you go to get groceries?</li>
<li><span class="label label-info">Living Environment</span> What is Panther Hall like (social, comfortable, location...)?</li>
<li><span class="label label-info">Social Life</span> Are people intellectual? Do they have thoughtful conversations with each other?</li>
<li><span class="label label-info">Social Life</span> Are there any good school sponsored events, or do they all suck?</li>
<li><span class="label label-info">Social Life</span> How much will not partying limit your social life?</li>
<li><span class="label label-info">About College</span> Who are the people involved in teaching a class? What is a TA? UTA? What background/training/qualifications do they have?</li>
<li><span class="label label-info">About College</span> How does social life change as you become an upperclassman?</li>
</ul>
</section>
</section>
<section id="section2" class="bottom_sections">
<br /><br /><br /><br />
<ul>
<li>The best way to choose a college is to read student reviews. <%= image_tag "reviews.jpg", size: "200x200", id: 'reviews' %></li>
<hr />
<li>But student reviews are only as good as the questions that they ask. <%= image_tag "question_mark.jpg", size: "200x200", id: 'question_mark' %></li>
<hr />
<li>Right now, student reviews only ask <%= link_to "a small fraction", "https://www.dropbox.com/s/p75pspbd5suzz19/Questions%20Comparison%20pdf.pdf" %> of the questions that you want answered. <br /><%= image_tag "partial_chart.jpg", size: "200x200", id: 'partial_chart' %></li>
<hr />
<li>College Inside View asks them all. <%= image_tag "full_chart.jpg", size: "200x200", id:'full_chart' %></li>
<hr />
<li class="wide">
Right now I'm doing a pilot program at the Ivies, and have over 4,000 answers for them so far. Previously I did a pilot program at <%= link_to "Pitt", "/university-of-pittsburgh/academics/professors/1" %>, <%= link_to "Wisconsin", "/university-of-wisconsin/academics/professors/1" %>, <%= link_to "Colgate", "/colgate/academics/professors/1" %> and <%= link_to "Adelphi", "/adelphi-university/academics/professors/1" %>. If you'd like to be notified when more schools get reviews, enter your email below:
<span id="notify">
<%= simple_form_for :subscribe, url: 'subscribe' do |f| %>
<%= f.input :email, label: false, required: true %> <br/>
<%= f.button :submit, "Notify me", class: "btn btn-primary", data: { :disable_with => "Submitting..." } %>
<% end %>
</span>
</li>
<hr />
<li class="wide">
<small><em>*Also, if you like what I'm doing and know someone in college, please ask them to answer some questions about their school on this site!*</em></small>
<p id="sample_post">Sample post: "College reviews are too broad. Please help answer some more specific questions about your school!"</p>
<p><%= social_share_button_tag('College reviews are too broad. Please help answer some more specific questions about your school!') %></p>
</li>
</ul>
</section>
<section id="section3" class="bottom_sections">
<h1>Where to start</h1>
<ul>
<li>Check out some of the articles in the <%= link_to "Advice Section", "/advice" %>. I'd start with this sequence:
<ul>
<li><%= link_to "I Graduated High School, Now What?", "/i-graduated-high-school-now-what" %></li>
<li><%= link_to "The Process of Exploring Your Interests", "/the-process-of-exploring-your-interests" %></li>
<li><%= link_to "How to Choose a College", "/how-to-choose-a-college" %></li>
</ul>
</li>
<li>If you're unclear as to what college is like, check out the <%= link_to "About College", "/about-college/college-life/1" %> section.</li>
<li>If you're ready to look for a school, start off by narrowing it down with the <%= link_to "Advanced Search", tools_advanced_search_url %> and <%= link_to "College Comparison", tools_comparison_url %> tools. Then <%= link_to "read about", "/colleges" %> the schools that you're interested in.</li>
<li>If you have any questions about anything whatsoever, please <%= mail_to "[email protected]", "shoot me an email" %>. I want to help. I just graduated Pitt as a neuroscience major, and can help you with anything from high school troubles, to the choosing a school, to succeeding in college.</li>
</ul>
</section>
<section id="section4" class="bottom_sections">
<h1>More information</h1>
<ul>
<li>See <%= link_to "my pitch", "/pitch" %> for an explanation of what makes College Inside View great.</li>
<li>See also <%= link_to "how College Inside View got started", "https://medium.com/what-i-learned-building/322e8668ed6f" %>.</li>
<li>Angel List <%= link_to "profile", "https://angel.co/college-inside-view" %></li>
<li>Stuff I've <%= link_to "wrote", "https://medium.com/@adamzerner/latest" %>.</li>
</ul>
</section> -->
</div>
Gemfile
source 'https://rubygems.org'
ruby '2.0.0'
gem 'rails', '~>4.0.0'
gem 'bootstrap-sass', '2.3.2.0'
gem "actionmailer", "~> 4.0.3" #
gem "jquery-tablesorter", "~> 1.5.0"
gem 'jquery-rails'
gem 'meta-tags', :require => 'meta_tags'
gem "simple_form", "~> 3.0.1"
gem 'rails4_upgrade'
gem 'sass-rails', '~>4.0.0'
gem 'coffee-rails', '~>4.0.0'
gem 'uglifier', '>=1.3.0'
# gem 'asset_sync'
gem 'gibbon', '~> 1.1.2'
gem 'activerecord-tableless'
gem 'social-share-button'
# Rails 4 gems
gem 'actionpack-action_caching', '~>1.0.0'
gem 'actionpack-page_caching', '~>1.0.0'
gem 'actionpack-xml_parser', '~>1.0.0'
gem 'actionview-encoded_mail_to', '~>1.0.4'
gem "activerecord-session_store", "~> 0.1.0"
gem "activeresource", "~> 4.0.0" #
gem "actionpack", "~> 4.0.3" #
gem 'protected_attributes' #
gem "activemodel", "~> 4.0.3" #
gem 'rails-observers', '~>0.1.1'
gem 'dalli', '~> 2.6.2' #
# gem 'turbolinks'
# gem 'jquery-turbolinks'
group :production do
gem 'pg'
gem 'rails_12factor'
end
group :development do
gem 'sqlite3'
gem 'annotate', '2.5.0'
end
# Don't think I'm using these
gem 'jquery-ui-rails'
gem 'jquery-ui-themes'
some heroku logs
2014-12-28T20:26:25.937063+00:00 app[web.1]:
2014-12-28T20:26:25.937075+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
2014-12-28T20:26:25.937071+00:00 app[web.1]:
2014-12-28T20:26:25.937042+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/request_id.rb:21:in `call'
2014-12-28T20:26:25.927220+00:00 app[web.1]: vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
2014-12-28T20:26:25.937040+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/rack/logger.rb:20:in `call'
2014-12-28T20:26:25.937072+00:00 app[web.1]: ActionController::RoutingError (No route matches [GET] "/assets/adelphi_food_1-30d1a701653e3ce27c72d338a617333a.png"):
2014-12-28T20:26:25.937093+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/sendfile.rb:112:in `call'
2014-12-28T20:26:25.937100+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:60:in `service'
2014-12-28T20:26:25.937095+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/application.rb:97:in `call'
2014-12-28T20:26:25.937084+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/rack/logger.rb:20:in `call'
2014-12-28T20:26:25.937085+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/request_id.rb:21:in `call'
2014-12-28T20:26:25.937087+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/methodoverride.rb:21:in `call'
2014-12-28T20:26:25.937088+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/runtime.rb:17:in `call'
2014-12-28T20:26:25.937061+00:00 app[web.1]: vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
2014-12-28T20:26:25.937062+00:00 app[web.1]: vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
2014-12-28T20:26:25.937051+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/engine.rb:511:in `call'
2014-12-28T20:26:25.937098+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/content_length.rb:14:in `call'
2014-12-28T20:26:25.937101+00:00 app[web.1]: vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
2014-12-28T20:26:25.937113+00:00 app[web.1]:
2014-12-28T20:26:25.937114+00:00 app[web.1]:
2014-12-28T20:26:25.937091+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/static.rb:64:in `call'
2014-12-28T20:26:25.937078+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/railties-4.0.3/lib/rails/rack/logger.rb:20:in `block in call'
2014-12-28T20:26:25.937090+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/activesupport-4.0.3/lib/active_support/cache/strategy/local_cache.rb:83:in `call'
2014-12-28T20:26:25.937097+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lock.rb:17:in `call'
2014-12-28T20:26:25.937103+00:00 app[web.1]: vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
2014-12-28T20:26:25.937111+00:00 app[web.1]: vendor/ruby-2.0.0/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
A: In order to deploy and serve Rails 4 static assets on Heroku you must include the rails12_factor Gem in the prod group of your Gemfile.
gem 'rails_12factor', group: :production
In addition you must confirm that config/application.rb serve_static_assets is set to true.
config.serve_static_assets = true
Check out Heroku documentation for more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27649691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Login does not work in django I want to login with a username and password that is in the database. I get the error 'object has no attribute 'authenticate'.
My code for views.py
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('polls/login.html', context_instance=RequestContext(request))
def auth(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('polls/create')
else:
return HttpResponseRedirect('polls/login')
My login.html:
<form action="/polls/auth/" method="post">
{% csrf_token %}
<label for = "username"> User name: </label>
<input type="text" name="username" value="" id="username">
<label for="password" > Password: </label>
<input type="text" name="password" value="" id="password">
<input type="submit" value="login">
</form>
A: Your are overriding the auth functionality by your view function auth.
For example if I import sys and create a same function name as sys then it overrides its functionality in the local namespace.
>>> import sys
>>> sys.path[0]
''
>>> sys.path[1]
'/usr/local/lib/python2.7/dist-packages'
>>> def sys():
... return "Hello"
...
>>> sys.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'path'
So just change your view function name auth to some other name.
OR
Try to import your auth feature with different name.
from django.contrib import auth as django_auth
def auth(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = django_auth.authenticate(username=username, password=password)
if user is not None:
django_auth.login(request, user)
return HttpResponseRedirect('polls/create')
else:
return HttpResponseRedirect('polls/login')
A: Your function name is 'auth' and this clashes with the 'auth' module you are importing. Change your function name or you could use the 'as' import syntax:
from django.contrib import auth as django_auth
and then use it in your function:
user = django_auth.authenticate(username=username, password=password)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27040036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: asp.net framework plugin application I really don't know if someone else has already written down a question similar to this one. I searched on google but maybe i don't know the right tag to search for.
I'd like to project and develop a web-based framework with a number of functionalities like a cms (user management, be able to write articles and so on). The focal point is that i'd like to architect it allowing administrator to activate or disactivate more functionalities by adding a new plugin (ie: he could do that by uploading an xml - as joomla does - or by clicking on 'activate' button - as wordpress does.)
Does exist any tutorial or open source project? Is MEF the way i have to go into?
A: Look for existing solutions. Things like Umbraco ( http://umbraco.org) and N2CMS ( http://umbraco.org) and Microsoft Orchard ( http://orchard.codeplex.com) and others are simple open source (not complicated) and should all be good things to start your project from them and develop any functionality you need that doesn't exist as a per their existing plugin architecture.
This will save you not just from re-inventing the wheel but also save a lot of time and effort in stuff that is already out there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5061497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can we use KeyStore to store sensitive data This is in addition to my previous question answered by Makoto object or container used to store sensitive information
After reading some articles, I see that in Java we can use KeyStore to store web certificates, but can I use this object to store application-specific data for example Bank details, Credit card information, etc? I have not seen any examples in this regard.
A: No. You can only store keys and certificates in a keystore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48246805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to fetch data from oracle in xml format using php I would be very happy if anyone help me :)
I am trying to write php web service that read a query from Oracle DB and display the result as XML. I spent days in searching for solution but unfortunately it didn't work
Below is some queries I tried it:
<?php
$db ="(DESCRIPTION=
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=TCP)(HOST=xxxx)(PORT=1530))
)
(CONNECT_DATA=(SID=DEV))
)";
$c = oci_connect("uname", "pass", $db);
$q = "select dbms_xmlgen.getxml(
'select user_name
from fnd_user
where user_name = 007144') xml
from dual";
$s = oci_parse($c, $q);
oci_execute($s);
$r = oci_fetch_array($s, OCI_ASSOC);
$mylob = $r['XML']->load(); // Treat column data as a LOB descriptor
echo "<pre>";
echo htmlentities($mylob);
echo "</pre>";
?>
The second code:
<?php
//File: DOM.php
$db="(DESCRIPTION=
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=TCP)
(HOST=xxx)(PORT=1530)
) )
(CONNECT_DATA=(SID=DEV))
)";
$conn = OCILogon("uname","pass",$db);
if ($conn) {
//echo "Successfully connected to Oracle.";
} else {
$err = oci_error();
echo "Oracle Connect Error " . $err['text'];
}
$query = "SELECT user_name from fnd_user where user_name = '007144'";
$stmt = oci_parse($conn,$query);
if (!oci_execute($stmt, OCI_DEFAULT)) {
$err = oci_error($stmt);
trigger_error('Query failed: ' . $err['message'], E_USER_ERROR);
}
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('EMPLOYEES', 'Root');
$dom->appendChild($root);//$root = $dom->appendChild($root);
while ($row = oci_fetch_array($stmt, OCI_RETURN_NULLS))
{
$emp = $dom->createElement('EMPLOYEE', 'emp');
$emp = $root->appendChild($emp);
$emp->setAttribute('id', $row['user_name']);
/*
$emp = $dom->createElement('EMPLOYEE', '');
$emp = $root->appendChild($emp);
$emp->setAttribute('id', $row['user_name']);
$ename = $dom->createElement('ENAME', $row['user_name']);
$ename = $emp->appendChild($ename);
$salary = $dom->createElement('SALARY', $row['user_name']);
$salary = $emp->appendChild($salary);
*/
}
echo $dom->saveXML();
//$dom->save("employees.xml");
oci_close($conn);
?>
The above code give me XML without data as the below picture!
http://i48.tinypic.com/2lnv5eo.jpg
Third Code
<?php
//File: XMLFromSQL.php
$user = 'uname';
$pswd = 'pass';
$db ='(DESCRIPTION=
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=TCP)(HOST=xxx)(PORT=1530))
)
(CONNECT_DATA=(SID=DEV))
)';
$sql = "SELECT user_name as RESULT FROM fnd_user
WHERE user_name=:deptno";
$deptno = 007144;
//Connect to the database and obtain info on a given department in XML format
$conn = oci_connect($user, $pswd, $db);
$query = oci_parse($conn, $sql);
oci_bind_by_name($query, ":deptno", $deptno, 2);
oci_execute($query);
oci_fetch($query);
$strXMLData = oci_result($query, 'RESULT');
//Create a new DOM document and load XML into its internal XML tree
$doc = new DOMDocument("1.0", "UTF-8");
$doc->loadXML($strXMLData);
//For simplicity, just print out the XML document
print $doc->saveXML();
?>
If you have another way please help me or I will be crazy :(
A: i tested your file :
with $row['user_name']
C:\Apps\PHP>php c:\temp\test.php
PHP Notice: Undefined index: user_name in C:\temp\test.php on line 25
Notice: Undefined index: user_name in C:\temp\test.php on line 25
<?xml version="1.0" encoding="UTF-8"?>
<EMPLOYEES>Root<EMPLOYEE id="">emp</EMPLOYEE></EMPLOYEES>
with $row['USER_NAME']
C:\Apps\PHP>php c:\temp\test.php
<?xml version="1.0" encoding="UTF-8"?>
<EMPLOYEES>Root<EMPLOYEE id="007144">emp</EMPLOYEE></EMPLOYEES>
does that solve your problem?
edit:
for solution 1 (PLSQL side)
$s = oci_parse($c, $q);
oci_execute($s, OCI_DEFAULT);
$r = oci_fetch_array($s, OCI_RETURN_NULLS+OCI_RETURN_LOBS);
echo "<pre>";
echo htmlentities($r["XML"]);
echo "</pre>";
or to give more control over the names of elements
$q = "select xmlelement(
\"EMPLOYEES\",
xmlagg(
xmlelement(
\"EMPLOYEE\",
xmlforest(user_name as \"EmpName\",
id as \"EmpID\",
email as \"email\"
)
)
)
).getclobval() xml
from fnd_user";
$s = oci_parse($c, $q);
oci_execute($s, OCI_DEFAULT);
$r = oci_fetch_array($s, OCI_RETURN_NULLS+OCI_RETURN_LOBS);
echo "<pre>";
echo htmlentities($r["XML"]);
echo "</pre>";
example output with xmlforest version is:
C:\Apps\PHP>php c:\temp\test3.php
<pre><EMPLOYEES><EMPLOYEE><EmpName>John Doe</EmpName><EmpID>1</EmpID><email>[email protected]</email></EMPLOYEE><EMPLOYEE><
EmpName>Alan Smith</EmpName><EmpID>2</EmpID><email>[email protected]</email></EMPLOYEE></EMPLOYEES></pre>
C:\Apps\PHP>
ie:
<EMPLOYEES>
<EMPLOYEE>
<EmpName>John Doe</EmpName>
<EmpID>1</EmpID>
<email>[email protected]</email>
</EMPLOYEE>
<EMPLOYEE>
<EmpName>Alan Smith</EmpName>
<EmpID>2</EmpID>
<email>[email protected]</email>
</EMPLOYEE>
</EMPLOYEES>
A: Finally, I get this XML
<?php
//File: DOM.php
$db="(DESCRIPTION=
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=TCP)
(HOST=xxx)(PORT=1530)
)
)
(CONNECT_DATA=(SID=DEV))
)";
$conn = OCILogon("uname","pass",$db);
if ($conn) {
//echo "Successfully connected to Oracle.";
} else {
$err = oci_error();
echo "Oracle Connect Error " . $err['text'];
}
//$dept_id = 007144;
$query = "SELECT user_name from fnd_user where user_name = '007144'";
$stmt = oci_parse($conn,$query);
//oci_bind_by_name($stmt, ':deptid', $dept_id);
if (!oci_execute($stmt, OCI_DEFAULT)) {
$err = oci_error($stmt);
trigger_error('Query failed: ' . $err['message'], E_USER_ERROR);
}
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('EMPLOYEES', '');
$dom->appendChild($root);//$root = $dom->appendChild($root);
while ($row = oci_fetch_array($stmt, OCI_RETURN_NULLS))
{
//var_dump($row);
//$emp = $dom->createElement('EMPLOYEE', 'emp');
//$emp = $root->appendChild($emp);
//$emp->setAttribute('id', $row['EMPLOYEE_NUMBER']);
$emp = $dom->createElement('EMPLOYEE', '');
$emp = $root->appendChild($emp);
//$emp->setAttribute('id', $row['FULL_NAME']);
$EmpName = $dom->createElement('EmpName', $row['FULL_NAME']);
$EmpName = $emp->appendChild($EmpName);
$empid = $dom->createElement('EmpID', $row['EMPLOYEE_NUMBER']);
$empid = $emp->appendChild($empid);
$email = $dom->createElement('email', $row['EMAIL_ADDRESS']);
$email = $emp->appendChild($email);
}
echo $dom->saveXML();
$dom->save("employees.xml");
oci_close($conn);
?>
And the result here:
http://filedb.experts-exchange.com/incoming/2012/11_w47/617768/XMLinPHP4.jpg
Now, I will start parsing this XML and I hope it will work out in the end, otherwise i will come back and disturb you again, Sorry :(
I will let you know tomorrow, Wait for me :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13516370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Parse Json in VB.NET into listview I'm developing a costum launcher for Minecraft, with more functions. I have a problem with parsing this json file:https://s3.amazonaws.com/Minecraft.Download/versions/versions.json (I'm using Newtonsoft.json to parse), I want to parse, and display result in listview (like this: http://pbrd.co/1ueP2Su) , but I don't know what code can do this.
Sory for my bad English, Thanks for help!
A: If you make a new structure that might look like this:
Public Structure Version
Public ID As String
Public TIME As String
Public releaseTime As String
Public type As String
End Structure
And then, maybe on a button click, write this
Dim allVersions = New List(Of Version)
Using wc = New WebClient() With {.Proxy = Nothing}
Dim JSON = Await wc.DownloadStringTaskAsync("https://s3.amazonaws.com/Minecraft.Download/versions/versions.json") 'Downloads the JSON file
Dim values = JsonConvert.DeserializeObject(Of JObject)(JSON) 'Converts it to JObject
For Each i In values("versions").Children() 'Gets the versions
YOUR_LISTBOX.Items.Add(i.ToObject(Of Version).ID)
Next
End Using
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27055138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add/Remove Items to Android ListView I am creating a listview as ListView listView = new ListView(context); in my activity and I code MyCustomAdapter that extends BaseAdaptor.setting this custom adapter to my listView.setAdapter(myCustomAdpObj) object that I created as above.Now at run time I want to add/remove elements from this listView.I did't find the method how I can do this?any suggestion?thanks
A: from your item array just remove or add item and call your adapter's notifyDataSetChanged()
A: remove/add an element and use this.
((BaseAdapter) listView.getAdapter()).notifyDataSetInvalidated();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7712321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: assign userID as value and username as ng-model to a select tag My question is probably easy, but I am having difficulties to solve it. I am developing an application using ASP.Net MVC and AngularJS. And I am using select tag to list users. I assigned to the select tag the same ng-model that I have assigned to div for real-time binding (user names).
My question is, when I change the item (user) in the select tag and save, I want to save using ID not username.
As you know, ng-model is equals username and I want it that way, but when it comes to saving the data, I want to use value and I want it the same as userID not name.
<div>{{supervisor}}</div>
<select ng-model="supervisor">
<option ng-repeat="x in supervisors" ng-selected='supervisor == (x.supervisorfName+" "+x.supervisorlName)'>{{x.supervisorfName+" "+x.supervisorlName}}</option>
</select>
<a href="javascript:void(0)" ng-click="updateUserSupervisor()"><i class="fa fa-floppy-o fa-lg" aria-hidden="true"></i></a>
The above select tag is listing users from database table. It has the same ng-model as the div in the top... When I click on the save icon below the select tag, I want to update the database table but not using ng-model because it is the name. Instead, I want to use ID.
So, how can I add ID in addition to ng-model in a select tag??
Below is the angularJS controller code that calls the database:
$http.get('/Home/GetSupervisor')
.then(function (response) {
$scope.supervisors = response.data;
})
.catch(function (e) {
console.log("error", e);
throw e;
})
.finally(function () {
console.log("This finally block");
});
And finally, below is the MVC code:
public JsonResult GetSupervisor()
{
var db = new scaleDBEntities();
return this.Json((from userObj in db.Users
select new
{
supervisorId = userObj.Id,
supervisorfName = userObj.usrFirstName,
supervisorlName = userObj.usrLastName,
})
, JsonRequestBehavior.AllowGet
);
}
As requested, below is my angular controller:
var myApp = angular.module('myApp', []);
myApp.controller('mainController', function ($scope, $http) {
$http.get('/Home/GetUser')
.then(function (response) {
$scope.users = response.data;
$scope.itmNo = response.length;
})
.catch(function (e) {
console.log("error", e);
throw e;
})
.finally(function () {
console.log("This finally block");
});
$http.get('/Home/GetSupervisor')
.then(function (response) {
$scope.supervisors = response.data;
})
.catch(function (e) {
console.log("error", e);
throw e;
})
.finally(function () {
console.log("This finally block");
});
});
A: You can set your ng-model to be an object( which represent your user/supervisor entity) instead of just the name.
So add a new property to your scope called supervisor.
myApp.controller('mainController', function ($scope, $http) {
$scope.supervisor=null;
//your existing code goes here
};
Now in your view, you can use the name property to display the selected supervisor name.
<div>{{supervisor.supervisorfName}} {{supervisor.supervisorlName}}</div>
<select ng-options="option.supervisorfName for option in supervisors"
ng-model="supervisor"></select>
When you have to save, you can get the id of the selected supervisor from the id property like $scope.supervisor.supervisorId
And to show both first name and last name in the option, you simply need to concatenate
<select ng-options="option.supervisorfName+' '
+option.supervisorlName for option in supervisors"
ng-model="supervisor"></select>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37933595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: EclipseLink converts Enum to BigDecimal I try to convert an Enum into a BigDecimal using the Converter of EclipseLink. The conversion works, but the resulting database column has a type of String. Is it possible to set a parameter, that EclipseLink builds a decimal column type within the database?
I use a class, which implements org.eclipse.persistence.mappings.converters.Converter.
The application server logs
The default table generator could not locate or convert a java type (null) into a database type for database field (xyz). The generator uses java.lang.String as default java type for the field.
This message is generated for every field, which uses a converter. How can I define a specific database type for these fields?
public enum IndirectCosts {
EXTENDED {
public BigDecimal getPercent() {
return new BigDecimal("25.0");
}
},
NORMAL {
public BigDecimal getPercent() {
return new BigDecimal("12.0");
}
},
NONE {
public BigDecimal getPercent() {
return new BigDecimal("0.0");
}
};
public abstract BigDecimal getPercent();
public static IndirectCosts getType(BigDecimal percent) {
for (IndirectCosts v : IndirectCosts.values()) {
if (v.getPercent().compareTo(percent) == 0) {
return v;
}
}
throw new IllegalArgumentException();
}
}
The database has to store the numeric values. I use such a converter:
public class IndirectCostsConverter implements Converter {
@Override
public Object convertObjectValueToDataValue(Object objectValue, Session session) {
if (objectValue == null) {
return objectValue;
} else if (objectValue instanceof IndirectCosts) {
return ((IndirectCosts) objectValue).getPercent();
}
throw new TypeMismatchException(objectValue, IndirectCosts.class);
}
@Override
public Object convertDataValueToObjectValue(Object dataValue, Session session) {
if (dataValue == null) {
return dataValue;
} else if (dataValue instanceof String) {
return IndirectCosts.getType(new BigDecimal((String) dataValue));
}
throw new TypeMismatchException(dataValue, BigDecimal.class);
}
@Override
public boolean isMutable() {
return false;
}
@Override
public void initialize(DatabaseMapping databaseMapping, Session session) {
}
}
Within convertDataValueToObjectValue(Object I have to use String because the SQL generator defines the database column as varchar(255). I would like to have decimal(15,2) or something.
Thanks a lot
Andre
A: The EclipseLink Converter interface defines a initialize(DatabaseMapping mapping, Session session); method that you can use to set the type to use for the field. Someone else posted an example showing how to get the field from the mapping here: Using UUID with EclipseLink and PostgreSQL
The DatabaseField's columnDefinition, if set, will be the only thing used to define the type for DDL generation, so set it carefully. The other settings (not null, nullable etc) will only be used if the columnDefinition is left unset.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13307452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c# convert yyyymmdd text to dd/MM/yyyy I have some text in rows as yyyymmdd (eg: 20181211) which I need to convert to dd/MM/yyyy
I am using:
cashRow["BusinessDate"] = Convert.ToDateTime(row.Cells[ClosingDate.Index].Value.ToString()).ToString("dd/MM/yyyy");
I get the error "string was not recognized as a valid DateTime.
Any ideas where I am going wrong?
A: You'll need to use ParseExact (or TryParseExact) to parse the date:
var date = "20181217";
var parsedDate = DateTime.ParseExact(date, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var formattedDate = parsedDate.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Here we tell ParseExact to expect our date in yyyyMMdd format, and then we tell it to format the parsed date in dd/MM/yyyy format.
Applying it to your code:
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
A: You have to use ParseExact to convert your yyyyMMdd string to DateTime as follows and then everything is okay.
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
A: As you already know the exact format of your input yyyyMMdd (eg: 20181211), just supply it to DateTime.ParseExact() and then call ToString() on the returned DateTime object.
string YourOutput = DateTime.ParseExact(p_dates, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
A: Try this:
cashRow["BusinessDate"] = row.Cells[ClosingDate.Index].Value.ToString("dd/MM/yyyy");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53809405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular 2 component .html path I try to use relative paths for html in component also i am mapping my js files in dist folder.. my component code is
app/app.component.ts
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html'
})
export class AppComponent { }
the html file is in same directory i.e
app/app.component.html
<h1> Wolaa </h1>
I am getting following error
Its totally clear that angular is finding app.component.html file at "dist/app/app.component.html" which is not there how can i fix this??
My systemjs.config.js file is
/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function(global) {
// map tells the System loader where to look for things
var map = {
'app': 'dist', //'app',
'@angular': 'node_modules/@angular',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
};
var ngPackageNames = [
'common',
'compiler',
'core',
'forms',
'http',
'platform-browser',
'platform-browser-dynamic',
'router',
'router-deprecated',
'upgrade',
];
// Individual files (~300 requests):
function packIndex(pkgName) {
packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
}
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['@angular/'+pkgName] = { main: 'bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
}
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
ngPackageNames.forEach(setPackageConfig);
var config = {
map: map,
packages: packages
};
System.config(config);
})(this);
and my tsconfig.json is
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"outDir": "dist"
}
}
A: Here are some details about template relative paths in the documentation that may help:
https://angular.io/docs/ts/latest/cookbook/component-relative-paths.html
A: Try placing a "./" before your relative path like:
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent { }
A: This is the best solution that I could find so far:
moduleId: module.id.replace("/dist/", "/src/"); where src in my case is app.
Taken from here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39319517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Laravel 5 and Carbon discrepancy on Forge Hopefully I'm not mad and I'm only missing something. I have a project on Laravel 5.0 and I have a requestExpired function called every time I have an incoming request. Now, to calculate the difference between current time on the server and the timestamp within the request I'm using:
$now = Carbon::now('UTC');
$postedTime = Carbon::createFromTimestamp($timestamp, 'UTC');
For some reason request is always rejected because it's expired. When I debug these two lines from above and just dump data, I get:
REQUEST'S TIMESTAMP IS: 1423830908279
$NOW OBJECT: Carbon\Carbon Object
(
[date] => 2015-02-13 12:35:08.000000
[timezone_type] => 3
[timezone] => UTC
)
$POSTEDTIME OBJECT: Carbon\Carbon Object
(
[date] => 47089-05-28 09:37:59.000000
[timezone_type] => 3
[timezone] => UTC
)
Any ideas why $postedTime is so wrong? Thanks!
A: To answer my own question: for some strange reason webhook calls from remote API have 13 digits long timestamps and that's why my dates were so wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28499941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: End-of-Session Handling in EmberJS I have an Ember application that requires user authentication on the server side. Once authenticated (via login), application runs normally. The application shows a logout button. Pressing this logout button sends a message to the server, which causes the server to terminate the session, does some clean up, and sends the login page for the client to display. All this works fine.
But here's the problem: if the user hits the browser's 'back' button after logging off, he will see the app again and can interact with it. The app can still send messages to the server. Currently, the server will always respond by sending back the login page when the session is already terminated. How do I get ember to transition to this login page received from the server? The fact that users can still get back to a running application (at least on the client side) after logging off would cause some confusion.
What's the recommended method for handling this? Is there anyway to make the Ember application end when the user hits the logout button? Maybe just disable the browser's back button when the user logs off (how do you do this in Ember?)?
A: You can either check in every route if the session is loggedIn or not in activate hook of route like this..
if you are setting a variable loggedIn true here is how to do it.
App.PostRoute = Ember.Route.extend({
activate: function() {
if (!loggedIn){
this.tansitionTo('login');
}
}
});
If you want to remove totally PostRoute from history you can use replaceWith rather transitionTo.
.or use these for authentication ember-auth or simple-auth
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20851263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Deploy Azure Container App to different Resource Group in Azure pipeline I´m playing around with Azure Container Apps, but I'm running into a small issue when trying to deploy through Azure Pipelines, the thing is that I have one Azure Container Registry and I want to create a new Revision for ca-sandbox-1 and ca-sandbox-2, but since there are in different Resource Group I always get a "Forbidden" when executing Azure Pipelines
If I create the Azure Container Registry in the same Resource Group the pipeline works well.
Now If I try to create a new revision in two different Resource Group, only works from AzureCLI or VSCode. Is there a way of making this work from Azure Pipelines?
Azure
rg-core (Resource Group)
*
*acrcore (Azure Container Registry)
*ca-core (Azure Container App)
rg-sandbox-1 (Resource Group)
*
*ca-sandbox-1 (Azure Container App)
rg-sandbox-2 (Resource Group)
*
*ca-sandbox-2 (Azure Container App)
Azure-pipeline.yml
- main
stages:
- stage: Build
displayName: Build and push stage
jobs:
- job: Build
displayName: Build
pool:
vmImage: 'ubuntu-latest'
steps:
- task: Docker@2
displayName: 'docker build and publish'
inputs:
containerRegistry: 'acr-core-connection'
repository: 'ca-core'
command: 'buildAndPush'
Dockerfile: '**/Dockerfile'
buildContext: '.'
- task: AzureContainerAppsRC@0
inputs:
azureSubscription: 'subs-rg-core'
acrName: 'acrcore'
imageToDeploy: 'acrcore.azurecr.io/api-sandbox:$(Build.BuildId)'
containerAppName: 'ca-sandbox-1'
resourceGroup: 'rg-sandbox-1'
targetPort: '80'
A:
Is there a way of making this work from Azure Pipelines?
From your description, you need to access the azure container registry and azure container app in different Resource Groups.
To meet your requirement, you need to create a Service Connection at Subscription Level.
Navigate to Project Settings -> Service Connections -> Select Azure Resource Manager Service Connection. Then you can only select Azure Subscription.
In this case, the Service Connection will have access to whole Azure Subscription.
For example:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74854822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I use windbg as a post mortem debugger for Windows services? I have Windbg set as the default post mortem debugger. I did this by running windbg -I. However, this only appears to catch unhandled exceptions from applications run by the user I'm logged on as, not Windows services. Does anyone know how I can configure windbg to catch these too?
A: If you plan to debug the service application from the beginning of its execution, including its initialization code, this preparatory step is required.
http://msdn.microsoft.com/en-us/library/windows/hardware/ff553427(v=vs.85).aspx
A: When WinDbg is running as postmortem debugger it is launched by the process that is crashing. In case of a service it is launched by a process running in session 0 and has no access to the desktop.
You can configure AeDebug registry to launch a process that creates a crash dump and debug the crash dump. You can use ntsd -server and connect to the server.
A: You should be able to use WinDbg to attach or launch any service even those not run by the user: http://support.microsoft.com/kb/824344
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13798220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using ajax with MVC I see my product’s bag ViewShoppingCart.ascx
<%= Ajax.ActionLink("Посмотреть карзину",
"ViewShoppingCart", "Products",
new AjaxOptions { UpdateTargetId = "content" })%>
And I want to change the quantity in ViewShoppingCart.ascx.
<%using (Ajax.BeginForm("UpdateItem", "Products",
new AjaxOptions { UpdateTargetId = "content" }))
{%>
<%=Html.Hidden("productid", shoppingCartItem.Product.ProductID.ToString())%>
<%=Html.TextBox("Quantity", shoppingCartItem.Quantity.ToString(), new { size = 2,
maxlength = 2, onchange = "this.form.submit();" })%>
<%} %>
When I enter a new value quantity and I press "enter" everything works as expected. If I press "Tab" instead "Enter" a new window appears instead of ajax form
What I do wrong?
A: One way would be to add a submit button to your form (it could be hidden) and invoke the click action so that it will trigger an asynchronous form postback:
<%using (Ajax.BeginForm("UpdateItem", "Products",
new AjaxOptions { UpdateTargetId = "content" })) {%>
<%=Html.Hidden("productid", shoppingCartItem.Product.ProductID.ToString())%>
<%=Html.TextBox("Quantity", shoppingCartItem.Quantity.ToString(), new { size = 2,
maxlength = 2, onchange = "document.getElementById('button').click();" })%>
<input type="submit" id="button" style="display: none" />
<% } %>
And if you don't like the idea of putting hidden buttons this also works but one may find it ugly:
<%using (Ajax.BeginForm(
"UpdateItem",
"Products",
new AjaxOptions {
UpdateTargetId = "content"
},
new {
id = "myForm"
}))
{ %>
<%=Html.Hidden("productid", shoppingCartItem.Product.ProductID.ToString())%>
<%=Html.TextBox("Quantity", shoppingCartItem.Quantity.ToString(),
new {
size = 2,
maxlength = 2,
onchange = "var event = new Object(); event.type='submit'; $get('myForm').onsubmit(new Sys.UI.DomEvent(event));"
})
%>
<% } %>
Off-topic: simplify your life with unobtrusive javascript and jQuery.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1610531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to click on an image area with bootstrap I am using the Bootstrap CDN library building my website. (And I'm new to HTML in general)
I'm trying to use an Image as index page.
The Image contains 2 places where buttons should be:
I managed to determine and calculate the areas, but I can't make it work...
<div id= "wrap">
<div class="container" id = "c_1">
<img id="imag-main" src="pic/start.jpg" class="img-responsive" alt="" usemap="#Map" />
<map name="Map" id="Map">
<area alt="" title="" href="empty.html" shape="poly" coords="3379,2255,3380,2711,2422,2712,2425,2256" />
<area alt="" title="" href="login.html" shape="poly" coords="3458,2256,4430,2255,4415,2711,3458,2711" />
</map>
</div>
</div>
any thoughts? all HTML files are in same file.
A: You can place a div with that img as background-image and set 2 buttons/divs with position absolute.
Like this:
.home {
background-color:red;
width:100%;
height:100vh;
position:relative;
}
.btn1 {
width:200px;
height:200px;
background-color:blue;
position:absolute;
top:20%;
left:30%;
}
.btn2 {
width:200px;
height:200px;
background-color:green;
position:absolute;
top:20%;
left:50%;
}
<div class="home">
<a class="btn1" href="#">
page one
</a>
<a class="btn2" href="#">
page two
</a>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41700468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to place text on a diagonal line?
Hey guyz, I guess you got my concept by seeing the above picture. I'm unable to place diagonal line behind the text and it should get masked by the content placed on it. I wanted it in pure css. Background should be visible through the text.
A: You can use a rotated pseudo element. Make it 1px wide and make the lines with top/bottom borders :
body {
padding: 0;
margin: 0;
background-image: url('https://farm7.staticflickr.com/6083/6055581292_d94c2d90e3.jpg');
background-size: cover;
}
div {
position: relative;
width: 150px;
margin: 130px auto;
padding: 10px 0;
}
div:before {
content: '';
position: absolute;
top: -120px;
left: 50%;
width: 1px;
height: 100%;
border-top: 120px solid #000;
border-bottom: 120px solid #000;
-webkit-transform: rotate(8deg);
-ms-transform: rotate(8deg);
transform: rotate(8deg);
}
<div>
<h1>Title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec luctus condimentum mi sit amet iaculis. Aliquam erat volutpat. Maecenas eleifend commodo rutrum.</p>
</div>
A: I think you are looking for this-
body{background: url('http://i.imgur.com/Kv22GCi.png');}
div {
position: relative;
width: 120px;
margin: 100px auto;
padding: 5px 0;
}
div:before {
content: '';
position: absolute;
top: -100px; left: 45%;
width: 1px; height: 100%;
border-top: 120px solid #000;
border-bottom: 120px solid #000;
-webkit-transform: rotate(8deg);
-ms-transform: rotate(8deg);
transform: rotate(8deg);
}
<div>
<h2>dsfsd jf fkljdsfjdsj</h2>
<p>Loream ipsum dolor shit amet</p>
</div>
I hope this will help you.
A: You can do using pseudo selectors :after or :before
Download this png image for background http://i.imgur.com/Kv22GCi.png
.container {
position: relative;
width: 300px;
height: 548px;
border: 1px solid #ccc;
background-image: url(http://i.imgur.com/Kv22GCi.png);
padding: 50px;
-moz-box-sizing: border-box;
box-sizing: border-box;
font-family: sans-serif
}
/*For the diagonal line*/
.container:after {
content: "";
position: absolute;
height: 100%;
border: 1px solid #000;
top: 0;
left: 70px;
z-index: -1;
-moz-transform: rotate(10deg);
-ms-transform: rotate(10deg);
-o-transform: rotate(10deg);
-webkit-transform: rotate(10deg);
transform: rotate(10deg)
}
h1 {
font-size: 50px
}
p {
font-size: 22px
}
<div class="container">
<h1>About Us.</h1>
<p>"Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet."
<p/>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29604553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: I'm trying to perform a delete request but I'm facing this error Front End
import React,{useState, useEffect} from 'react'
import axios from 'axios'
function Renderreview() {
const [renderReview, setRenderReview] = useState([])
useEffect(()=>{
axios.get('/reviews')
.then(res => {
console.log(res)
setRenderReview(res.data)
})
.catch(err => {
console.log(err)
})
},[])
function handleDelete (id){
console.log(renderReview.id)
axios.delete(`/reviews/${renderReview.id}`,)
}
return (
<div className='card1'>
<h2>reviews</h2>
{renderReview.map((renderReview) => {
return(
<div className='renderedreviews'>{renderReview.review}
<button onClick={handleDelete} key={renderReview.review}>Delete</button>
</div>
)
})}
</div>
)
}
export default Renderreview
Back End
def destroy
review =Review.find_by(id: params[:id])
if review.destroy
head :no_content
else
render json: {error: review.errors.messages}, status: 422
end
end
This is the error displaying on my console
DELETE http://localhost:4000/reviews/undefined 500 (Internal Server Error)
Uncaught (in promise)
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
A: Try this, you were not using the correct id:
import React, { useState, useEffect } from 'react'
import axios from 'axios'
function Renderreview() {
const [renderReview, setRenderReview] = useState([])
useEffect(() => {
axios.get('/reviews')
.then(res => {
console.log(res)
setRenderReview(res.data)
})
.catch(err => {
console.log(err)
})
}, [])
function handleDelete(id) {
axios.delete(`/reviews/${id}`,)
}
return (
<div className='card1'>
<h2>reviews</h2>
{renderReview.map((renderReview) => {
return (
<div className='renderedreviews'>{renderReview.review}
<button
onClick={() => {
handleDelete(renderReview.id);
}}
key={renderReview.review}>
Delete
</button>
</div>
)
})}
</div>
)
}
export default Renderreview
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74735050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: sizeof is used to calculate the size of any datatype, measured in the number of bytes. Doesn't it mean that number of bytes is an integer? When I run these two programs which uses sizeof() operator produces the following output. The only difference between 2 codes is that d is initialized to 0 in first code and -1 in second one. Why second program is not entering in the loop body?
1)
#include<stdio.h>
int main()
{
int d;
printf("Before loop\n");
for(d=0;d<=sizeof(int);d++)
{
printf("sizeof operator\n");
}
printf("After loop\n");
return 0;
}
Output:
Before loop
sizeof operator
sizeof operator
sizeof operator
sizeof operator
sizeof operator
After loop
2)
#include<stdio.h>
int main()
{
int d;
printf("Before loop\n");
for(d=-1;d<=sizeof(int);d++)
{
printf("sizeof operator\n");
}
printf("After loop\n");
return 0;
}
Output:
Before loop
After loop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27793137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kafka duplicate read I am using Kafka version 0.10.2.1 and Spring boot for my project.
I have 5 partitions of a topic which can be consumed by multiple consumers (having the same Group-Id) which are running on different machine.
What Problem I am facing is :
I am getting duplicate read of a single message with these Kafka warning logs
Auto offset commit failed for group my-consumer-group: Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than the configured max.poll.interval.ms, which typically implies that the poll loop is spending too much time message processing. You can address this either by increasing the session timeout or by reducing the maximum size of batches returned in poll() with max.poll.records.
As logs indicate that this problem arises because Kafka consumer failed to commit.
Here are few details about my use-case :
*
*I have multiple consumers of a topic My-Topic that belongs to the same group-Id my-consumer-group
*Consumer consumes messages from Kafka, apply business logic and store processed data in Cassandra
*The process for consuming message from Kafka, applying business logic and then saving it to Cassandra takes around 10 ms per message consumed from Kafka.
I am using following code to create Kafka-consumer bean
@Configuration
@EnableKafka
public class KafkaConsumer {
@Value("${spring.kafka.bootstrap-servers}")
private String brokerURL;
@Value("${spring.kafka.session.timeout}")
private int sessionTimeout;
@Value("${spring.kafka.consumer.my-group-id}")
private String groupId;
@Value("${spring.kafka.listener.concurrency}")
private int concurrency;
@Value("${spring.kafka.listener.poll-timeout}")
private int timeout;
@Value("${spring.kafka.consumer.enable-auto-commit}")
private boolean autoCommit;
@Value("${spring.kafka.consumer.auto-commit-interval}")
private String autoCommitInterval;
@Value("${spring.kafka.consumer.auto-offset-reset}")
private String autoOffsetReset;
@Bean
KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setConcurrency(concurrency);
factory.getContainerProperties().setPollTimeout(timeout);
return factory;
}
@Bean
public ConsumerFactory<String, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerConfigs());
}
@Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> propsMap = new HashMap<>();
propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerURL);
propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, autoCommit);
propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, autoCommitInterval);
propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeout);
propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
return propsMap;
}
}
These are the kafka-configuration I am using
spring.kafka.listener.concurrency=2
spring.kafka.listener.poll-timeout=3000
spring.kafka.consumer.auto-commit-interval=1000
spring.kafka.consumer.enable-auto-commit=true
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.session.timeout=50000
spring.kafka.connection.timeout=10000
spring.kafka.topic.partition=5
spring.kafka.message.replication=2
My main concern is of duplicate read of a message by multiple Kafka consumers belonging to same consumer group and in my application, I have to avoid duplicate entry to the database.
Could you please help me and review my above Kafka configurations and Kafka-consumer-code so that I can avoid duplicate read.
A: The simple answer is don't use autoCommit - it commits on a schedule.
Instead, let the container do the commits; using AckMode RECORD.
However you should still make your code idempotent - there is always a possibility of redelivery; it's just that the probability will be smaller with a more reliable commit strategy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45470749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how retrieve metadata from shoutcast on android? I am developing a player that plays a url of the form
shoucast http://292.3.23.23:8000 is, as I can restore the
metadata? artist name mediaplayer use the title etc.
play no problem, but I can not retrieve metadata
anyone know how I can do it and display it in a text
titulo.settext (title);
A: check this out http://developer.android.com/reference/android/media/MediaMetadataRetriever.html but it is on API LEVEL 10
Thank you.
I have done using the thread,not the great solution but it works
public class IcyStreamMeta {
protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;
public IcyStreamMeta(URL streamUrl) {
setStreamUrl(streamUrl);
isError = false;
}
/**
* Get artist using stream's title
*
* @return String
* @throws IOException
*/
public String getArtist() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String title = streamTitle.substring(0, streamTitle.indexOf("-"));
return title.trim();
}
/**
* Get title using stream's title
*
* @return String
* @throws IOException
*/
public String getTitle() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
return artist.trim();
}
public Map<String, String> getMetadata() throws IOException {
if (metadata == null) {
refreshMeta();
}
return metadata;
}
public void refreshMeta() throws IOException {
retreiveMetadata();
}
private void retreiveMetadata() throws IOException {
URLConnection con = streamUrl.openConnection();
con.setRequestProperty("Icy-MetaData", "1");
con.setRequestProperty("Connection", "close");
con.setRequestProperty("Accept", null);
con.connect();
int metaDataOffset = 0;
Map<String, List<String>> headers = con.getHeaderFields();
InputStream stream = con.getInputStream();
if (headers.containsKey("icy-metaint")) {
// Headers are sent via HTTP
metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
} else {
// Headers are sent within a stream
StringBuilder strHeaders = new StringBuilder();
char c;
while ((c = (char)stream.read()) != -1) {
strHeaders.append(c);
if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
// end of headers
break;
}
}
// Match headers to get metadata offset within a stream
Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
Matcher m = p.matcher(strHeaders.toString());
if (m.find()) {
metaDataOffset = Integer.parseInt(m.group(2));
}
}
// In case no data was sent
if (metaDataOffset == 0) {
isError = true;
return;
}
// Read metadata
int b;
int count = 0;
int metaDataLength = 4080; // 4080 is the max length
boolean inData = false;
StringBuilder metaData = new StringBuilder();
// Stream position should be either at the beginning or right after headers
while ((b = stream.read()) != -1) {
count++;
// Length of the metadata
if (count == metaDataOffset + 1) {
metaDataLength = b * 16;
}
if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
inData = true;
} else {
inData = false;
}
if (inData) {
if (b != 0) {
metaData.append((char)b);
}
}
if (count > (metaDataOffset + metaDataLength)) {
break;
}
}
// Set the data
metadata = IcyStreamMeta.parseMetadata(metaData.toString());
// Close
stream.close();
}
public boolean isError() {
return isError;
}
public URL getStreamUrl() {
return streamUrl;
}
public void setStreamUrl(URL streamUrl) {
this.metadata = null;
this.streamUrl = streamUrl;
this.isError = false;
}
public static Map<String, String> parseMetadata(String metaString) {
Map<String, String> metadata = new HashMap();
String[] metaParts = metaString.split(";");
Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
Matcher m;
for (int i = 0; i < metaParts.length; i++) {
m = p.matcher(metaParts[i]);
if (m.find()) {
metadata.put((String)m.group(1), (String)m.group(2));
}
}
return metadata;
}
}
make thread call each 10 sec
public void startThread(){
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
URL url;
Message msg = handler.obtainMessage();
try {
url = new URL(URL);
IcyStreamMeta icy = new IcyStreamMeta(url);
Log.d("SONG",icy.getTitle());
msg.obj = icy.getTitle();
Log.d("ARTITSi",icy.getArtist());
handler.sendMessage(msg);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 10000);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6638251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Delete row from its id in table using ajax I want to delete spacific row after clicking button from the reference of its id,
here is my php code,
while($row = mysqli_fetch_array($values)) {
echo "<tbody>";
echo "<tr id=\"12\">";
echo "<td>" . $row['pid'] . "</td>";
echo "<td>'<img src='/Login/product_avtar/".$row['pic']."' width=\"80\" height=\"60\">'</td>";
echo "<td>" . $row['pname'] . "</td>";
echo "<td>" . $row['pprice'] . "</td>";
echo "<td>" . $row['pdes'] . "</td>";
echo "<td>" . $row['qnt'] . "</td>";
echo "<td><button class=\"btn btn-sm btn-danger delete_class\" id=\"".$row['pid']."\">Delete</button></td>";
echo "</tr>";
echo "</tbody>";
this is ajax,
$(function() {
$( ".delete_class" ).click(function(){
var element = $(this);
var del_id = element.attr("pid");
var info = 'pid=' + del_id;
if(confirm("Are you sure you want to delete this Record?")){
$.ajax({
type: "POST",
url: ajax_url,
data: info,
success: function(){
alert('Successfully Deleted');
}
});
}
return false;
});
});
and this is ajax_url,
if(($_POST['pid']))
{
$id=$_POST['pid'];
$id = mysqli_real_escape_string($id);
$option = mysqli_query($conn,"DELETE * FROM product where pid = ".$id."");
}
Please help to find out the solution,
thanks
A: You have used the attribute pid:
var del_id = element.attr("pid");
But the attribute specified in your HTML is id, not pid.
Change this:
<button class=\"btn btn-sm btn-danger delete_class\" id=\"".$row['pid']."\">Delete</button>
To this:
<button class=\"btn btn-sm btn-danger delete_class\" pid=\"".$row['pid']."\">Delete</button>
And try debugging in your jQuery:
var del_id = element.attr("pid");
console.log(del_id); // On chrome, go to the Inspect Element > console tab and check if the id retrieved is correct.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38968144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Update ttl of all documents I have a Document Collection which already have a property named ttl and have values which is greater than 0. Now I need to implement the actual ttl which is provided by Azure. How can I do that ?
A: Not exactly sure how to answer what's in your question's title, aside from running some type of update operation to update all of the ttl properties.
As far as enabling TTL itself: TTL is enabled in the collection settings:
You'll need to choose a default ttl for documents without a ttl property (which can be -1 for a default of "do not expire."
A: You are out of luck. The ttl field is hard-coded. You'll need to migrate your existing ttl field to a new field name, maybe old_ttl and enable DocumentDB's ttl functionality after that migration is done. No other choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37650118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wait for submit to explode data in php So I'm basically trying to wait for the user to input a series of numbers before exploding them into an array. Its attempting to explode the data before it is actually entered so I'm getting a Undefined index: numbers error.
<form>
<input type="text" name="numbers"/>
<div><input type="submit" value="submit"></div>
</form>
<?php
if(!isset($_POST['submit']))
{
$arrayNums = explode(",", $_GET['numbers']);
}
A: <form method="post">
<input type="text" name="numbers"/>
<div><input type="submit" value="submit"></div>
</form>
<?php
if(isset($_POST['numbers']))
{
$arrayNums = explode(",", $_POST['numbers']);
var_dump($arrayNums);
}
?>
Submitting a form will not pass a submit value in your html designed.
Instead, you could check for the numbers that are posted.
A: You must use $_POST[] superglobal if you are posting the form data to the server and not $_GET[].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49441931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Is it possible to block IDM on my website? I don't know how the chrome extensions work, but I just want to know. Is it possible to block Internet Download Manager to not run on my website.
For example if a user plays a video the IDM should not show a download option
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45654159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to dynamically send category, cation, label and value to Analytics via Tag Manager? I have managed to create an event to register data on my Google Analytics account with Google Tag Manager. But I can't set any information dynamically.
Here is my current setting:
I'm firing this event with:
dataLayer.push({'event': 'event_name'});
The event is working fine, my data is being registered at Google Analytics, but I can't overwrite "My Category", "My action" and "My Label", "My Value".
Pretty much like Google Analytics used to do with:
ga('send', 'event', 'My Category', 'My Action');
It was very easy to set any value to and fire an event, but now I am confused on how to do it via Google Tag Manager.
What would be the best way to send any value to these fields? Or I need to create a tag for each event I want to fire (that would not make any sense)?
A: The solution depends on where you are acquiring the event parameters from. Are they coming from text that is being clicked, or are they coming from the page path, etc. One possible solution would require that you push your dynamic category, action, label values with your dataLayer push:
dataLayer.push({
'event': 'event_name',
'category': 'your category',
'action': 'your action',
'label': 'your label'
})
In GTM, you would then need to define new dataLayer variables that would correspond to the category, action, and label. In your event tag, you would then just use the new dataLayer variables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41770529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trying to Create Python Package for Internal Use I am trying to create a package of my simple python program, so that i could distribute it to other developers internally. I am able to import the package in my virtual environment but when I try to install it through pip outside of that virtual environment, I get following error:
C:\mypackages\cmk>python -m pip install cmk
ERROR: Could not find a version that satisfies the requirement cmk (from versions: none)
ERROR: No matching distribution found for cmk
Following is my directory structure:
C:\mypackages\cmk>dir
29/07/2021 09:05 PM <DIR> .
29/07/2021 09:05 PM <DIR> ..
29/07/2021 08:55 PM <DIR> .venv
29/07/2021 09:00 PM <DIR> cmk
29/07/2021 05:53 PM 1,312 config.yml
29/07/2021 08:57 PM 201 requirements.txt
29/07/2021 08:34 PM 290 setup.py
29/07/2021 09:04 PM 98 test.py
In above directory structure, the cmk contains my actual program and my setup.py looks like this:
from setuptools import setup
setup(name='cmk',
version='0.1',
packages=['cmk'],
)
I have checked and all the dependencies in requirements.txt are installed already.
C:\mypackages\cmk>pip freeze
awscli==1.19.98
boto3==1.16.53
botocore==1.20.98
click==7.1.2
colorama==0.4.3
docutils==0.15.2
jmespath==0.10.0
pyasn1==0.4.8
python-dateutil==2.8.1
PyYAML==5.3.1
retrying==1.3.3
rsa==4.5
s3transfer==0.4.2
six==1.15.0
urllib3==1.26.2
Please advise. Thanks.
A: You should deploy to pypi or to local repository.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68575222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Firebase Auth failing to render Sign In Pop-up on mobile Chrome App sometimes My mobile web apps Firebase auth is failing sometimes on Android devices in Chrome
It's failing across all 3 federated services: Google, Facebook, Twitter - with newest versions of Chrome and Google Play Services installed.
It is failing on the following mobile devices in regular and incognito mode:
Pixel 2 - Android 10
Nexus 7 - Android 6.0.1
It's succeeding on the following devices:
Samsung S6 - 6.0.1
Nexus 5 - 6.0.1
Samsung GN4 - 5.0.1
It seems to be failing to render the pop-up window and just returns to the sign-in page. On the first attempt on a failing device, it will actually render the pop-up window (for Google I am selecting) and let me select an account before it gets in the constantly failing state
Thanks for any help and happy 2020!
A: add this if you haven't added in your manifest
<gap:config-file platform="android" parent="/manifest">
<application android:largeHeap="true"
android:hardwareAccelerated="false"></application>
A: in some of the web apps sometimes you have to downgrade the library of googleAuth you are using and it can be library conflict we can say.
Some libs are working in Latest versions, so maybe you should try downgrading the libraries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59597670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Error RECURSIVE data type Persistent model with YESOD TL;DR How to make (Key record) an instance of Eq/Show/Read in Yesod
I'm having a problem with module recursion. I've declared some of my own data types in a file which I want to be available to Models.hs, since I need to use it in the config/models file.
But one of the types needs data types from the DB. A FooId (i.e. Key Foo) to be precise.
It looks something like this:
config/models
Foo
name Text
thingy (Bar Foo) Maybe
UniqueName name
deriving Eq Show Read Typeable
My own file contains these
data Bar record = Bar { a :: [Jab record] }
deriving (Eq, Show, Read, Typeable)
data Jab record = Jab { b :: Key record
, c :: Int
}
deriving (Eq, Show, Read, Typeable)
Now I need to import Model.hs to get Key to work, but I also need to import my file into Model.hs for it to work.
I've also tried adding my own types to Models.hs, but I get these errors:
Model.hs:24:13:
No instance for (Eq (Key record))
arising from the first field of ‘Jab’ (type ‘Key record’)
Possible fix:
use a standalone 'deriving instance' declaration,
so you can specify the instance context yourself
When deriving the instance for (Eq (Jab record))
And adding a "deriving instance Eq a => Eq (Key a)"
together with the {-# LANGUAGE StandaloneDeriving #-} doesn't work either.
If anyone knows how to remedy this, it'd help me immensely.
A: Turns out writing my own instances for (Jab record) fixed this issue.
This is how I fixed it, for reference:
*
*Removing the Eq, Show and Read from the deriving clause of Jab
*Making my own Eq, Show and Read instances for (Jab record)
*After that compiled I had to consequently make a PersistField instance for (Bar record)
(The following is all put in a separate file to be imported to Models.hs)
module Custom.TypesAndInstances where
import ClassyPrelude.Yesod
import Prelude (read)
import qualified Data.Text as T
import qualified Text.Read.Lex as L
import Text.ParserCombinators.ReadPrec
import GHC.Read
import GHC.Show (appPrec)
-- instance for PersistField (Bar record)
instance (PersistEntity record, PersistField record) => PersistField (Bar record) where
toPersistValue = PersistText . T.pack . show
fromPersistValue (PersistText t) = Right $ read $ T.unpack t
-- instances for Jab Eq, Read and Show
instance PersistEntity record => Eq (Jab record) where
Jab x a == Jab y b = x == y && a == b
instance PersistEntity record => Show (Jab record) where
show (Jab x a) = "Jab " ++ show x ++ " " ++ show a
instance PersistEntity record => Read (Jab record) where
readPrec = parens
(prec appPrec (do
expectP (L.Ident "Jab")
x <- step readPrec
y <- step readPrec
return (Jab x y))
)
readListPrec = readListPrecDefault
readList = readListDefault
----------------------
data Bar record = Bar { a :: [Jab record]
}
deriving (Eq, Show, Read, Typeable)
data Jab record = Jab { b :: Key record
, c :: Int
}
deriving (Typeable)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35368294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Transform and copy all properties of an object I have a large monthly summary object with lots of fields. When creating a new one, I need to calculate the amount / percent diff for each field from the previous month, something like so:
public Summary addSummary(Summary current) {
Summary previous = getPreviousSummary(getPreviousMonth();
current.setPropertyA(NumUtil.getFormattedValue(current.getPropertyA(), previous.getPropertyA()));
// repeat 80 more times
...
}
currently I'm doing it manually, which is tedious and super ugly, is there a way to loop through all the properties / set them after running them through a function?
I did some searching and BeanUtils can copy properties, but not transform them.
A: You can use reflection to solve your problem. As I don't know actually what you're gonna get and set from those two objects, I am giving a minimal example to show what you can do in this case.
You can get all the declared fields in your Summary class as follows:
Field[] arrayOfFields = Summary.class.getDeclaredFields();
As you have all the fields of the class summary, you can iterate through each field and do the get and set easily for different objects of that class as follows. Remember to set field.setAccessible(true) if the fields are private inside the class:
for (Field field: arrayOfFields) {
try {
field.setAccessible(true);
if (field.getType() == Double.class) {
Double prevVal = field.get(previous);
Double currentVal = field.get(current);
//do calculation and store to someval
field.set(resultSummary, someval);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Well, you may need to check all type of classes that your class Summary has and do the get and set according to that type. Please keep in mind that you cannot use primitive type fields for this if condition check as they are not Class. So, you may need to convert the primitive type variables in the summary class to corresponding Object Class. Like double to Double etc.
The field.get(Object obj) method gets the value for the field in the Object obj. Similarly, field.set(Object obj, Object value) sets the Object value to the field in the Object obj
With this approach you can achieve the goal easily with less hassle and dynamic coding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68489334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Creating ad for someone else's page using the Marketing API I'm trying to create an ad for someone else's page using the Marketing API.
So far I have
*
*My own access token which works fine for creating and managing ads for my own page
*Another user's access token with pages_manage_ads and ads_management permissions given for one of their pages
The rest is very confusing. pages_manage_ads is supposedly for creating and managing ads for a page, but the documentation only mentions reading page ads, not creating or editing.
Has anyone gotten this to work?
A: I've done it before, but some time ago and it often changes in detail. What I would do is going to API Explorer and try to get to the first success by first reading the ads related to the Page and then creating them by leveraging existing posts there. You can create them in a paused state.
https://developers.facebook.com/docs/marketing-api/reference/adgroup
Facebook is all about experimenting, so if you don't want to experiment with your user's page you can create your own dummy page and try it there first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64656258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Objective-c: passing data from UITable to ViewController with prepareForSegue this is my very first app and, basically, this part consists in passing data from a UItableView to a second View Controll. I managed to learn how to pass data from a simple NSarray (also in a UITable), but my goal is to pass values from a NSDictionary. Everything is set up, but I can't figure out how to write the PrepareForSegue method properly. The app runs, but the label on the "DetailView" stays empty. What I got so far:
@implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
_citySpots = @{@"Bars" : @[@"Hurricane", @"Black Swan", @"Texas"],
@"Clubs" : @[@"Electric Wizard", @"Offspring", @"The Tunnel"],
@"Restaurants" : @[@"Nando's", @"1/2 Burguer", @"Satellite"],
};
_sectionTitles = [[_citySpots allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}
PrepareForSegue Method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"spotsDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *destViewController = segue.destinationViewController;
NSString *sectionTitle = [_sectionTitles objectAtIndex:indexPath.section];
NSArray *citySpots = [_citySpots objectForKey:sectionTitle];
destViewController.receiver = [citySpots objectAtIndex:indexPath.row];
}
}
And the receiver(header):
#import <UIKit/UIKit.h>
#import "TableViewController.h"
@interface DetailViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *receiver;
@property (nonatomic, strong) NSString *spot;
@end
Main:
#import "DetailViewController.h"
@interface DetailViewController ()
@end
@implementation DetailViewController
- (void)viewDidLoad {
[super viewDidLoad];
_receiver.text =_spot;
}
Can someone help me out? Thanks
A: Try to use setters:
[destViewController setReceiver:[citySpots objectAtIndex:indexPath.row]];
[destViewController setSpot:[citySpots objectAtIndex:indexPath.row]];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42007888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.