text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Javascript Rich Text Editor and associated class to filter and clean the input? I realise there are several rich text editors for jQuery but I cannot find any that have an associated class that does the filtering and cleaning required to accept the input into a database.
Does such a class exist?
I am particularly interested for a PHP library, but .NET would be interesting too.
A: If you would use FCKeditor it would allow to you get clean HTML or XHTML (editor.GetXHTML()) which you could then write into DB.
Actually it's not that much important what you write into DB, because usially you write original HTML (you can always strip from it saspicious tags if needed). In order to prevent XSS attacks it is essential to properly encode content before displaying it on the web-page. For .NET there is AntiXSS library for that at CodePlex.com
For PHP you may want to look at the following libraries:
*
*Zend_Filter
*HTML Sanitizer
*PHP Input Filter
And also this article:
*
*Avoiding XSS security attacks to sites that use HTML editors
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/689369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ionic 3: Menutoggle keeps getting hidden I have implemented a hamburgermenu in Ionic 3, but I am facing an issue. When I run the application on my Android device the hamburgermenu keeps disappearing i.e. the button to open the side menu is gone. However, it only happens sometimes. I tried to run the application while inspecting it with Google Chrome, and what I noticed is that the menutoggle gets hidden for some reason, but I don't know why. I don't control the visibility in the .ts class.
<ion-header>
<div>
<ion-navbar>
<button ion-button menuToggle> // this becomes "<button ion-button menuToggle hidden>"
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Frontpage</ion-title>
</ion-navbar>
</div>
</ion-header>
A: I am having similar issue for menu toggle.
I added below code for my page.
Header html code:
<ion-header>
<ion-navbar text-center color="navBar">
<ion-buttons right>
<button class="menu" ion-button menuToggle="right" icon-only>
<ion-icon name="menu"></ion-icon>
</button>
</ion-buttons>
<ion-title>Password Reset</ion-title>
</ion-navbar>
</ion-header>
Header css code:
.menu {
display: block !important;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50068182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: delete Single Core Data Item from a uicollectionviewCell using a button I am trying to delete a single element of the coreData set using a button inside a collectionviewcell. So the cell has a label with the result of the core data fetch. When I hit the button it should delete the cell making it no longer appear. Also the the core data single set item should be perementley deleted. I have scence this used before in protocols but not using core data.The core data is var itemName.
class CustomCell: UICollectionViewCell {
@objc func delete() {
}}
class ViewController: UIViewController {
var itemName : [Item] = []
}
A: In My Case Working 100%
Try This
import CoreData
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell Identifier name ", for: indexPath) as! Cellname
cell.YourButtonNamw.tag = indexPath.row
cell.YourButtonNamw.addTarget(self, action: #selector(delete), for: .touchUpInside)
return cell
}
@objc func delete(_ sender:UIButton){
let itemName1 = itemName[sender.tag]
let context = APP_DELEGATE.persistentContainer.viewContext
var albums = [YourTableName]()
let request = NSFetchRequest<YourTableName>(entityName: YourTableName)
request.predicate = NSPredicate(format: "itemName = %@" , itemName1)
do
{
albums = try context.fetch(request)
for entity in albums {
context.delete(entity)
do
{
try context.save()
}
catch let error as Error?
{
print(error!.localizedDescription)
}
}
}
catch _ {
print("Could not delete")
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58293724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Counting unique variables within a unique variables [R] Suppose this is my data:
X Y Z
1 1 2323
1 1 45
1 1 67
1 2 1
1 2 90
1 3 34
1 3 1267
1 3 623
1 4 81
1 4 501
2 1 456
2 1 78
2 2 41
2 2 56
2 3 90
2 3 71
2 4 24
2 4 98
2 5 42
2 5 361
How do I count the values of Z for each unique variable Y for each separate X so that I can get a dataframe that looks like:
X Y Z
1 1 2435
1 2 91
1 3 1924
1 4 582
2 1 534
2 2 97
2 3 161
2 4 122
2 5 403
A: Assuming that dataframe is named 'dat' then aggregate.formula which is one of the generics of aggregate:
> aggregate( Z ~ X + Y, data=dat, FUN=sum)
X Y Z
1 1 1 2435
2 2 1 534
3 1 2 91
4 2 2 97
5 1 3 1924
6 2 3 161
7 1 4 582
8 2 4 122
9 2 5 403
Could also have used xtabs which returns a table object and then turn it into a dataframe with as.data.frame:
as.data.frame( xtabs( Z ~ X+Y, data=dat) )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22963799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Git Stash - Local Changes - Git Stash - Git Stash Apply - Undo Need some help, I screwed up. Please reserve judgement.
Alright, this is what I did.
*
*git stash
*made some changes to the code.
*git stash (again)
*git stash apply
Is there any way I can get back to the code I had before the first git stash.
Any help would be appreciated.
Thanks, in advance.
A: Appreciate that applying or popping a Git stash just alters the working directory and/or stage. It does not make a new commit. Therefore, simply doing a hard reset should get you back to where you were before the first stash:
# from your branch
git reset --hard
That being said, if you wanted to retain some permutation of the changes since the first stash, that is another story and would require more work and thought to pull off.
Note: Generally speaking, popping a Git stash is risky, because if something goes wrong along the way, you can't reapply the same stash as it has already been popped from the stack. Use git stash apply for best results.
A: git stash list
<shows all the saved stashes>
git stash show 'stash{0}'
<displays changes in this stash>
<change index according to the one you want, 0 is the last saved stash>
git stash apply 'stash{0}'
<applies the stash>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72751358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Triggering events from async/await functions in the right order I have problems ensuring the order of events in my asynchronous task. The class from which other async tasks inherit has the following functions and takes the EventHandlers (ExecutionProgress, ExecutionStarted, ExecutionCompleted) in the constructor arguments:
public abstract Task Operation(IProgress<EventArgs> progress);
public virtual void Execute()
{
ExecuteAsync()
}
private void ReportProgress(EventArgs args)
{
if(ExecutionProgress != null) ExecutionProgress(this, args);
}
private async Task ExecuteAsync()
{
if(ExecutionStarted != null) ExecutionStarted(this, EventArgs.Empty)
await Operation(new Progress<EventArgs>(ReportProgress));
if(ExecutionCompleted != null) ExecutionCompleted(this, EventArgs.Empty)
}
Now in one of my classes, that inherits from asynchronous tasks, i override Operation with the following:
public override async Task Operation(IProgress<EventArgs> progress)
{
// run the synchronous function in another thread
JobResults results = await Task.Run(() => worker.DoYourJob());
progress.Report(results);
}
Running this code often, but not always, results in NullReference Exception in the ExecutionCompleted event handler when trying to access the JobResults. This is because ExecutionProgress event which writes the member variable usually gets fired after ExecutionCompleted for whatever reason. I think the standard says nothing about event ordering, but I'm looking for a nice solution to ensure deterministic ordering here. I want to fire ExecutionCompleted only after all ExecutionProgress events have been handled.
What would be a nice looking solution here? Is there any way to await until all progress reporting events have been handled.
A: The events are all fired in order. If your event handlers are asynchronous, which seems to be the case, then the code firing the events is going to continue executing as soon as it starts the event handlers, not when they complete.
If the code firing the events needs to not continue on until all of the handlers have finished, then you need to restructure this class such that the event handlers have some means of indicating to this class when they're done. There are any number of ways to do this, from passing a parameter in the event that allows handlers to tell it when they're done, or to having the signature of the event handlers return a Task rather than being void (you'll need to await those tasks when firing the event).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30598345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Copy Woocommerce product short description to ACF I want to copy the short description of all the products to an acf custom field that i created. The custom field's name is sxolia . I don't know how can i catch this ACF Field with a query to the database.
UPDATE `wp_posts`
SET `post_excerpt` = `?`
WHERE `post_type` = 'product'
AND `post_status` = 'publish'
A: You can use ACF function update_field($selector, $value, $post_id); to set the value of a specific field.
More info here: https://www.advancedcustomfields.com/resources/update_field/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59838843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: testing monaca backend only possible on device, why? When I test my app on my device I'm able to connect to the backend user and collection features. Why isn't that working when I preview the app in the browser (Chrome)? Or is it possible and what should I do to fix this...
A: As stated in the Monaca Backend API Reference Guide, Monaca backend requires a phonegap plugin thus the browser does not have these installed and therefore you will not be able to access those systems.
Ultimately, there is nothing you can do other than to test in the app, although if you use the Monaca Cloud IDE, you do gain a web interface to manage the backend. It is very useful.
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37355199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: 2 SELECT in a query with ORDER BY I need to create a MYSQL query that will return the following:
excel
this is my query
SELECT t1.fecha_salida,
t1.agencia,
t2.fecha_salida,
t2.directa
FROM (SELECT fecha_salida, COUNT(*) AS agencia
FROM ventas
WHERE ventas.eliminado = 0 AND ventas.cliente_id !=2
GROUP BY fecha_salida) AS t1,
(SELECT fecha_salida, COUNT(*) AS directa
FROM ventas
WHERE ventas.eliminado = 0 AND ventas.cliente_id =2
GROUP BY fecha_salida) AS t2
GROUP BY t1.fecha_salida
my table is:
|------ |Columna|Tipo|Nulo|Predeterminado |------
|//**venta_id**//|int(11)|No| |usuario_id|int(11)|No|
|tour_id|int(11)|No| |cliente_id|int(11)|No| |vehiculo_id|int(11)|No|
|cashflow_id|int(11)|No| |total_compra|int(6)|No|
|total_pagado|int(6)|No| |total_iva|int(6)|No|
|total_comision|int(11)|No| |a_pagar|int(11)|No|
|fecha_venta|datetime|No| |fecha_salida|date|No|
|concretada|tinyint(1)|No| |pasajeros|int(3)|No|
|nombre|varchar(500)|Sí|NULL |direccion|varchar(500)|Sí|NULL
|observaciones|varchar(500)|Sí|NULL |forma_pago|tinyint(2)|No|
|eliminado|tinyint(1)|No|
Can you help me
A: You can use UNION to combine two queries that have same structure , also you should select from combined result and then order them
SELECT * FROM (
SELECT fecha_salida, COUNT(*) AS agencia
FROM ventas
WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00'
and ventas.eliminado = 0
AND ventas.cliente_id = 2
GROUP BY fecha_salida
UNION
SELECT fecha_salida, COUNT(*) AS agencia
FROM ventas
WHERE `fecha_venta` between '2012-03-11 00:00:00' and '2019-08-30 23:59:00'
and ventas.eliminado = 0
AND ventas.cliente_id != 2
GROUP BY fecha_salida
) RESULT
ORDER BY agencia
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56763696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How can you use subdirectories in a GitHub wiki checkout? I'd like to organize my GitHub wiki pages in subdirectories. How do we refer to the pages in subdirectories?
A: github wiki / gollum-wiki doesn't inherently provide anything explicit for organizing pages into sub-directories. Any page can be linked from any other page irrespective of where it logically belongs. This is a powerful feature that makes wikis very flexible.
One way to implement a sub-directories structure would be to follow a naming convention.
Example: Having all pages related to subject1 have names that start with subject1, and so on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14408376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How can I build a regex to match a value? I need a regex that matches this kind of strings:
brand-new-car
brand-new-car-1
brand-new-car-100
307
and I just need to catch the "name" regardless of whether the string has -count; like this:
brand-new-car
brand-new-car
brand-new-car
307
This regex does not work properly. Its $1 is the full string, not without -count.
(\S+)(?:-\d+|)$
A: You need to make the first capture group "lazy" or non-greedy.
var re = new RegExp("^(\\S+?)(?:-\\d+)?$");
var testStrings = [
"brand-new-car",
"brand-new-car-1",
"brand-new-car-100",
"307"
];
for (var i=0; i<testStrings.length; i++) {
var result = re.exec(testStrings[i]);
say("result: " + result);
}
The results:
result: brand-new-car,brand-new-car
result: brand-new-car-1,brand-new-car
result: brand-new-car-100,brand-new-car
result: 307,307
A: Try this (?xms)(^[\w-]+.*?)(?=[\w-]+|\Z)
Here, below is an image of regex buddy
where you can catch the "name" regardless of whether the string has -count the yellow and blue foreground highlights the different selections.
A: Just remove the pipe '|', then it works
(\S+)(?:-\d+)$
Checked here rubular
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5708165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to parameterize a jquery function name and call it? I'm trying to make a plugin for a modal and I want the users to be able to initialize the animate function picking from a jquery list of functions like fadeIn , SlideDown etc.
var myModal = new createModal({
content: myContent,
appendTo: ".modalSection"
});
$(".modal_trigger").on("click", function () {
myModal.open();
});
createModal.prototype.open = function () {
var functionVar = this.options.animateType;
$(this.modal).fadeIn();
//i want to replace this above line with the function name in this.options.animateType
}
Any way to do this ?
A: As a jQuery object is, as the name implies, an object, you can access its properties as you would any standard object.
In this case you can use bracket notation to call a function held in one of those properties. For example:
createModal.prototype.open = function () {
var functionVar = this.options.animateType;
$(this.modal)[functionVar]();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54649304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ending a while loop when it reaches matching numbers I need to end this while loop when it reaches a matching number such as 88, 77, and so on.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int userNum = scan.nextInt();
if ((userNum >= 20) && (userNum <= 98)){
System.out.print(userNum + " ");
while ((userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)){
userNum = userNum - 1;
System.out.print(userNum + " ");
}
}
else{
System.out.print("Input must be 20-98");
}
System.out.print("\n");
}
}
However, when it runs it never leaves the loop, even when the number reaches one of the matching ones I had in the while loop. please help.
A: if(userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)
Will always be true, because userNum cannot be all of those values at once. Substitute || for &&:
if(userNum != 11) && (userNum != 22) && (userNum != 33) && (userNum != 44) && (userNum != 55) && (userNum != 66) && (userNum != 77) && (userNum != 88) && (userNum != 99)
This can be made easier using the modulus operator:
if(userNum % 11 != 0)
A: The problem lies in this line.
if(userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)
If userNum is any number, it cannot be 11, 22, 33, 44, 55, 66, 77, 88, and 99 at once, which means your program will keep running. As @Carcigenicate stated, you want && (and) operators.
A: Try using the && operator here instead of OR
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int userNum = scan.nextInt();
if ((userNum >= 20) && (userNum <= 98)){
System.out.print(userNum + " ");
while (userNum != 11 && userNum != 22&& userNum != 33 && userNum != 44 && userNum != 55 && userNum != 66 && userNum != 77&& userNum != 88 && userNum != 99){
userNum = userNum - 1;
System.out.print(userNum + " ");
}
}
else{
System.out.print("Input must be 20-98");
}
System.out.print("\n");
}
}
A: Your code appears to be searching for multiples of 11, so I would prefer testing the remainder of eleven. Also, you can use x-- instead of x = x - 1. Finally, a do-while loop would make this a bit cleaner. Like,
Scanner scan = new Scanner(System.in);
int userNum = scan.nextInt();
if (userNum >= 20 && userNum <= 98) {
do {
System.out.print(userNum + " ");
userNum--;
} while (userNum % 11 != 0);
System.out.println();
}
A: You can use following code to ending a while loop when it reaches matching numbers using array.
public class stopWhileTest{
public static void main(String arg[]) {
int[] number = {11, 22, 33, 44, 55, 66, 77, 88};
Scanner scan = new Scanner(System.in);
int userNum = scan.nextInt();
if ((userNum >= 20) && (userNum <= 98)){
System.out.print(userNum + " ");
while(!contains(number,userNum)){
userNum = userNum - 1;
System.out.print(userNum + " ");
}
}
else{
System.out.print("Input must be 20-98");
}
System.out.print("\n");
scan.close();
}
public static boolean contains(final int[] array, final int v) {
boolean result = false;
for(int i : array){
if(i == v){
result = true;
break;
}
}
return result;
}
}
Hope this solution works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58479325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Set the title for the navigation control I converted window based application into navigation based but I am not able to set the title for the navigation bar.
controller = [[bookDisplayViewController alloc] initAndCreateView];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
nav.title=@"Application";
[window addSubview:nav.view];
A: Is it possible for you to place
self.navigationItem.title = @"YourName";
in the viewDidLoad of the other view? I'd try it that way and see if it works.
A: You must set the title from within the UIViewController. Try this:
controller.navigationItem.title=@"Application";
Infact apple docs on UINavigationItem for the "title" property states that:
title
A localized string that represents the view that this controller manages.
@property(nonatomic, copy) NSString *title
Discussion
Subclasses should set the title to a human-readable string that represents the view to the user. If the receiver is a navigation controller, the default value is the top view controller’s title.
Availability
Available in iOS 2.0 and later.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7696127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error connecting web3js to react native application I ran into a problem connecting web3 to a React Native app.
Initially, the connection was made according to this guide.
Everything worked, but as soon as I restart the application, an error appears:
ReferenceError: Property 'Buffer' doesn't exist, js engine: hermes
ERROR Invariant Violation: Module AppRegistry is not a registered
callable module (calling runApplication). A frequent cause of the
error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine:
hermes
Then I comment on these lines in Live reloading mode
const Web3 = require('web3')
const web3Rospen = new Web3('https://ropsten.infura.io/v3/myKey')
I save the code, the application works, again, in Live reloading mode, I uncomment these lines back - the application works.
But initially, just taking and running the application from web3 does not work. Maybe someone faced such a problem?
Versions:
"react-native": "0.66.4",
"web3": "^1.7.3"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72108832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: JAXB default value for null elements when marshalling At the time of marshalling of JAXB object I want to set some defult value to the resulting XML.
I do not want to use nillable=true as it generates empty tag with unnecessary xsi:nil="true", and this is not for setting default value. Instead I want to generate the XML with some placeholder characters such as '?'.
Use case : I am going to build a tool for WebService testing. There I need to present the entire request xml to the user (Like SOAPUI).
A:
Use case : I am going to build a tool for WebService testing. There I
need to present the entire request xml to the user (Like SOAPUI).
The idea of the place holder character isn't really going to work. For example ? is an ok default value for a string, but not an int, boolean, or for most complex values (i.e. representing the nested address information for a customer). Instead you will want a value that reflects the type.
Then I would have to write large and complex reflection based code. Just assume that
that is almost not possible in my case.
This reflection code probably won't be as bad as you are imagining. A quick search will probably also reveal libraries that populate objects with "dummy" data. When hooking it up with JAXB you could leverage a Marshaller.Listener to populate the object on the before marshal event.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27013103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Update on blur the first time only I can defer model updating until blur with ng-model-options="{ updateOn: 'blur' }". This prevents annoying the user with changing validation states while entering input the first time around. However, when a user returns to a failed validation to revise it, the updateOn: 'blur' prevents the validation state from being updated when the user has fixed it (but before they leave the field).
How can I reset the updateOn option to allow the default model update schedule after one blur?
A: ngModelOptions directive $evals its value, but doesn't observe it for changes. In other words, you cannot achieve what you are looking for with something like the following:
<input ng-model="foo" ng-model-options="fooOptions">
and then change it in the controller:
$scope.fooOptions = {updateOn: "blur"};
$scope.changeOptions = function(){
$scope.fooOptions = {updateOn: "default"};
}
For simple cases, you could add another variable that changes how you show validation messages:
<form name="form1">
<input name="foo"
ng-model="foo" ng-model-options="{updateOn: 'default'}"
ng-blur="startShowingErrors = true" minlength="3">
<span ng-show="startShowingErrors && form1.foo.$invalid">invalid entry</span>
</form>
But, if you want the actual form state not update, then you'd need another directive as a facade to ngModelOptions to cause a $compile on every change.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28397065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: AJAX not rendering as it should I am at a loss with what’s stopping my code not rendering AJAX where it should be, I have a less serious JS ‘Parse error’ which I can’t work out also.
I have a default prevented rails form_for where upon submit event jQuery finds the element and its attribute values, posts them to the model via appropriate action, model then responds with the new object and is supposed to render the JSON via a jbuilder form.
All is fine when I get the page to render via a redirect, but not by a render ‘create’, content_type: :json, error displayed is a missing template error. I also see from network response that it ‘failed to load response data’. views/reviews/create.json.jbuilder is saved is in the correct place I believe, class and id names are all correct I believe, files and folders are named correctly and in the right place I believe, I can’t see anything wrong? Unsure whether it’s a jbuilder error, a controller syntax error, or a jQuery syntax error. Here is my code:
controllers/reviews_controller.rb:
def create
@restaurant = Restaurant.find(params[:restaurant_id])
@review = @restaurant.reviews.new(params[:review].permit(:thoughts, :rating))
if @restaurant.reviews.find_by user_id: current_user.id
flash[:notice] = "You already reviewed this restaurant!"
redirect_to restaurants_path
else
@review.user = current_user
@review.save
# redirect_to restaurants_path, will do a redirect, but defeats AJAX purpose!
render 'create', content_type: :json # results in a missing template error #'missing templete reviews/create' error
end
end
Assets/restaurants/restaurants.js:
$(document).ready(function(){
$('.new_review').on('submit', function(event){
event.preventDefault();
var reviewList = $(this).siblings('ul');
var currentRestaurant = $(this).parent();
$.post($(this).attr('action'), $(this).serialize(), function(review){
if review # This line results in Uncaught SyntaxError: Unexpected Identifier
var newReview = Mustache.render($('#review_template').html(), review);
reviewList.append(newReview);
currentRestaurant.find('.review_count').text(review.restaurant.review_count)
currentRestaurant.find('.average_rating_number').text(review.restaurant.average_rating);
currentRestaurant.find('.average_rating_stars').text(review.restaurant.average_rating_stars);
}, 'json');
});
});
views/restaurants/index.html.erb (jbuilder template element):
<template id='review_template'>
<li>
<strong>{{ star_rating }}</strong> -*- {{ thoughts }}
</li>
</template>
views/reviews/create.json.jbuilder:
json.thoughts @review.thoughts
json.star_rating star_rating(@review.rating)
json.restaurant do
json.average_rating number_with_precision(@restaurant.average_rating,
precision: 1)
json.average_rating_stars star_rating(@restaurant.average_rating)
json.review_count pluralize(@restaurant.reviews.count, 'reviews')
end
Been on this for hours now trying to solve this one, pfff!! any idea where I’m going wrong folks? Am I doing something really dim somewhere here? Thank you.
A: As you can see in the error message, rails is looking for a file called reviews/create[extension] or application/create[extension] and extensions allowed are .erb, .builder, .raw, .ruby, .coffee or .jbuilder.
I suggest to change you ajax call to ask for js, not json, create a file called reviews/create.js.erb, and add this kind of code :
<% if @restaurant.reviews.find_by user_id: current_user.id %>
// do the code to show the error message in javascript
<% else %>
reviewList.append("<%= j(render('create')) %>");
currentRestaurant.find('.review_count').text(<%= pluralize(@restaurant.reviews.count, 'reviews') %>)
currentRestaurant.find('.average_rating_number').text(<%= number_with_precision(@restaurant.average_rating, precision: 1) %>);
currentRestaurant.find('.average_rating_stars').text(<%=star_rating(@restaurant.average_rating) %>);
<% end %>
This code should be executed after the success of the creation. You also have to create a file called reviews/_create.html.erb with the html you want to show. Finally, you have to delete some logic in the javascript and in the controller.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27693305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: where does llvm.memcpy.p0i8.p0i8.i64 come from i test clang and compile a simple C file including struct asigning.when I see the LLVM code ,there is llvm.memcpy.p0i8.p0i8.i64 ,where is from ? I not see the defination only see its declare as a fucntion.
A: It is a LLVM intrinsic function. As per the language reference:
LLVM provides intrinsics for a few important standard C library
functions. These intrinsics allow source-language front-ends to pass
information about the alignment of the pointer arguments to the code
generator, providing opportunity for more efficient code generation.
The llvm.memcpy intrinsic specifically:
The ‘llvm.memcpy.*’ intrinsics copy a block of memory from the source
location to the destination location.
Note that, unlike the standard libc function, the llvm.memcpy.*
intrinsics do not return a value, takes extra isvolatile arguments and
the pointers can be in specified address spaces.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55293471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to remove first two words of a strings output I want to remove the first two words that come up in my output string. this string is also within another string.
What I have:
for servers in `ls /data/field`
do
string=`cat /data/field/$servers/time`
This sends this text:
00:00 down server
I would like to remove "00:00 down" so that it only displays "server".
I have tried using cut -d ' ' -f2- $string which ends up just removing directories that the command searches.
Any ideas?
A: Use -d option to set the delimtier to space
$ echo 00:00 down server | cut -d" " -f3-
server
Note Use the field number 3 as the count starts from 1 and not 0
From man page
-d, --delimiter=DELIM
use DELIM instead of TAB for field delimiter
N- from N'th byte, character or field, to end of line
More Tests
$ echo 00:00 down server hello world| cut -d" " -f3-
server hello world
The for loop is capable of iterating through the files using globbing. So I would write something like
for servers in /data/field*
do
string=`cut -d" " -f3- /data/field/$servers/time`
...
...
A: You can use sed as well:
sed 's/^.* * //'
A: Please, do the things properly :
for servers in /data/field/*; do
string=$(cut -d" " -f3- /data/field/$servers/time)
echo "$string"
done
*
*backticks are deprecated in 2014 in favor of the form $( )
*don't parse ls output, use glob instead like I do with data/field/*
Check http://mywiki.wooledge.org/BashFAQ for various subjects
A: For the examples given, I prefer cut. But for the general problem expressed by the question, the answers above have minor short-comings. For instance, when you don't know how many spaces are between the words (cut), or whether they start with a space or not (cut,sed), or cannot be easily used in a pipeline (shell for-loop). Here's a perl example that is fast, efficient, and not too hard to remember:
| perl -pe 's/^\s*(\S+\s+){2}//'
Perl's -p operates like sed's. That is, it gobbles input one line at a time, like -n, and after dong work, prints the line again. The -e starts the command-line-based script. The script is simply a one-line substitute s/// expression; substitute matching regular expressions on the left hand side with the string on the right-hand side. In this case, the right-hand side is empty, so we're just cutting out the expression found on the left-hand side.
The regular expression, particular to Perl (and all PLRE derivatives, like those in Python and Ruby and Javascript), uses \s to match whitespace, and \S to match non-whitespace. So the combination of \S+\s+ matches a word followed by its whitespace. We group that sub-expression together with (...) and then tell sed to match exactly 2 of those in a row with the {m,n} expression, where n is optional and m is 2. The leading \s* means trim leading whitespace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27490379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: php recursive include function in 2 file with different path Hi all I've a problem with include function in php:
I have 4 file:
dir1/file1.php
dir4/dir2/file2.php
dir3/file3.php
dir3/file4.php
In file1.php I have:
include_once('../dir3/file3.php');
In file3.php I have:
required('../dir3/file4.php');
In file2.php I want write:
include_once('../../dir3/file3.php');
but the required function in file3 doesn't work because the path of file4 must be
../../dir3/file4.php
and not
../dir3/file4.php
How can I fix it?
A: You can use only dot (.) before your filename which will find that file from root of dir..for eg ./dir3/file4.php but it increase the overhead..Another way is to use
$base = __DIR__ . '/../';
require_once $base.'_include/file1.php';
A: If you are calling file3 from file2 you will have to go back 2 directories. The best way is using the full path like :
home/mysite/public_html/dir3/file3.php
It maybe (is) troublesome but good uptill some level.
Edit: DIR and rest is also handy, depending on your need
A: I FIX it with:
In file1.php I have:
$path = '..';
include_once($path.'/dir3/file3.php');
In file3.php I have:
required($path.'/dir3/file4.php');
In file2.php I want write:
$path = '../..'
include_once($path.'/dir3/file3.php');
This work for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28478191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to insert date value from jdatechooser to database table private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
String G_ID=gIDText.getText();
String G_Title=(String) titleCombo.getSelectedItem();
String FName=fNameText.getText();
String SName=sureNameText.getText();
String Sex=(String) genderCombo.getSelectedItem();
String dob=(JTextField)dobDte.getDateEditor().getUiComponent().getText();//error
int age=Integer.parseInt(ageText.getText());
String country=contactText.getText();
String nationality=nationText.getText();
String ZipCode=zipCodeText.getText();
String email=mailText.getText();
String PassportNo=passportText.getText();
String IssuedDate=(JTextField)issDte.getDateEditor().getUiComponent().getText();//Error
String ExpiryDate=(JTextField).getDateEditor().getUiComponent().getText();//error
String PIDNo=pidText.getText();
int ContactNo=Integer.parseInt(contactText.getText());
Guest guest=new Guest(G_ID,G_Title,FName,SName,Sex,dob,age,country,nationality,ZipCode,email,PassportNo,IssuedDate,ExpiryDate,PIDNo,ContactNo);
try {
boolean isAdded=GuestController.addGuest(guest);
if (isAdded) {
JOptionPane.showMessageDialog(NewGuest.this,"Registered Success !");
}else{
JOptionPane.showMessageDialog(NewGuest.this,"Unable to Register ! !");
}
}catch(SQLException | ClassNotFoundException ex){
JOptionPane.showMessageDialog(NewGuest.this,ex.getMessage());
}
}
(mvc)I have tried to insert date from jdatechooser to mysql database,but its shows error,please help me to fix this and if can please retype the correct code for me
A: 1 - here to set the date from jDateChooser to string
String dob=""+jDateChooser1.getDate();
2 - to insert the date to database you should set the format first
SimpleDateFormat Date_Format = new SimpleDateFormat("yyyy-MM-dd");
Date_Format.format(jDateChooser1.getDate())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36895567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Design a RESTful API in Laravel 5.2, using a resource that conceptually can contain other resources First of all I am really not very familiar with the REST practice, and I am not very confident about the title of my question.
So I am trying to built a RESTful API using Laravel for a phonebook application. The phonebook may contain telephones of either employees (i.e real persons) or offices. For that reason I have three models
*
*a Directorate with id and name fields,
*an Employee with id and name fields and
*a Telephone with id, tel, employee_id, directorate_id, description and type fields.
Telephones corresponding to a directorate's office have only the id, tel, directorate_id and description fields set, while the telephones corresponding to a person (i.e an employee) have set only the id, tel, employee_id, directorate_id, and type fields. That is how I separate them: a telephone having a description can only be an office's telephone, while a telephone having both the employee_id and the type_id set is an employee's telephone.
The models are related as follows:
*
*an employee may have many telephones
*a directorate, may have many telephones
class Directorate extends Model
{
public function telephones()
{
return $this->hasMany(Telephone::class);
}
public function employees()
{
return $this->hasMany(Employee::class);
}
}
class Employee extends Model
{
public function telephones()
{
return $this->hasMany(Telephone::class);
}
public function directorate()
{
return $this->belongTo(Directorate::class);
}
}
class Telephone extends Model
{
public function employee()
{
return $this->belongsTo(Employee::class);
}
}
My question is what should I a consider as my resource.
So far I am thinking of the following approach:
I shall use the concept of contact as resource. A contact may be the joined information of either an employee and a telephone, or a directorate and a telephone. For instance, a "contact" may contain the name of an employee with his related telephone numbers and telephone types, or it can contain the name of a directorate with the description of the telephone and the telephone number.
The "problem" with this approach is that I have ended up with (let's put it this way) two different types of resource: the employee's contacts and the directorate office's contacts, which contain slightly different information and thus, I need also to have different create and edit forms to interact with these two "types" of resources.
In order to implement the REST API, I am thinking of two different scenarios:
*
*Use two different RESTful controllers, one EmployeeContacts and another OfficesContacts for separating conceptually the resource to an employee's and an office's resource, and accessing them through different URIs like:
example.com/phonebook/employees/{id}/edit
example.com/phonebook/offices/{id}/edit
example.com/phonebook/employees/create
etc...
*Use a single RESTful controller, e.g. PhonebookContacts to access the resources through the same URIs as one resource (i.e. both employee's and office's contact resources now are considered to be just a "contact" resource)
//this refers to a contact resource that can be either an office's or a n employee's contact
example.com/phonebook/contact/{id}/edit
//this should list all resources (both employees and offices contacts)
example.com/phonebook/contact/
and then use conditional statements in the controller's create/store/edit/update methods to deal with them separately (e.g if an http POST request contains a description_id then it is an office contact and do this, or else if has an employee_id then it is an employee's contact so do that...)
I would like to hear your views, what of these two different scenarios do you consider to be better in the context of REST for my phonebook app? Would be better to think of a single "contact" resource and handle it using conditional statements with different return in the controller, or shall I separate the concept of "contact" to "employee's contact" and "office's contact" and use separate controllers and URI's to handle them?
Is there another approach that I could follow instead?
A: The way I would do it is with 2 different controllers for the simple reason of speed and responsiveness. Loading all contacts and filtering isn't as quick as loading the one part only.
However, you can always set in your controller the same return with different data. Such as EmployeeController@index returns view('contacts.index', compact('employeeContacts')), and OfficesController@index returns view('contacts.index', compact('officesContacts'))
EDIT:
Sorry, I have misread it...I thought you wanted to do the filtering in the view. Anyway, my practice is to do it separately, simply because the code is cleaner. If you want to make the whole REST more readable, you can put both resources in a group like so: Route::group(['prefix' => 'contact'], function(){ //routes here// });
So now you will have routes like:
example.com/contact/employees/
example.com/contact/offices/
A: I am not familiar at all with Laravel but since this question is about REST concepts (I have a small background on these) I should give it a try.
Since you are building a RESTful application, you must not consider others as human beings but only as machines. IMO the urls should determine the action that will be performed. Thus, by using different urls for different actions (perform a CRUD on a contact - either an Employee or a Directorate or SomethingElseInTheFuture) sounds good to me and fits the REST nice.
Hope this clarify the things for you!
[EDIT]
I believe jannis is right. It should be the verbs (GET, POST, PUT, PATCH etc) that make the action instead of the URLs. The urls are just respresenting the resources. My mistake. So both of your points of view are correct. It's just how convenient each approach is for your project (for now and for the near future of your project). IMO, I see #1 (two different restful controllers) more approchable.
Cheers and sorry for any misconception!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36616606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Datasnap response doesn't convert to json I am returning a string response in my DataSnap server.
function TServerMethods1.GetImagem(PhotoPath: string): string;
var
...
begin
...
Result := StrEnv.DataString;
end;
This successfully returns a response with my base64 string
{"result":["Qk02...."]}
I need to get the content of the result, this is my base64 string 'Qk02...'. I was trying to get the response as a TJSONObject and then use TJSONObject.Get('result').Value to get my base64 string.
I tried about three ways and couldn't convert this to TJSONObject, in all the attempts it returns me a blank string.
ShowMessage(RESTResponse1.Content); // This shows the result
lJOImagem := RESTResponse1.JSONValue as TJSONObject;
ShowMessage(lJOImagem.ToString); // This shows a blank message
try
ShowMessage(lJOImagem.GetValue('result').Value)); // This shows a blank message
finally
lJOImagem.Free;
end;
How to get the content of the result?
A: The JSONObject was successfully being created. The problem was in the way I was accessing the value.
The image was built by me.
The whole response is a TJSONObject, JSONObject.GetValue('result') is a TJSONArray. If I loop through the array It will loop only once and retrieve a TJSONValue which its value is the string I wanted Qk02...
The code is like that
vJSONObject := RESTResponse1.JSONValue as TJSONObject;
if vJSONObject <> nil then
begin
vJSONArray := vJSONObject.GetValue('result') as TJSONArray;
for vJSONValue in vJSONArray do
begin
memo.Text := vJSONValue.Value; // This is the string I wanted: Qk02..
end;
end;
A: You can parse your string into a JsonObject. To do this, you have to convert your string into bytes and then convert it into a JsonObject as following :
var MyObject : TJSONObject;
MyObject := TJSONObject.ParseJSONValue(
TEncoding.ASCII.GetBytes(RESTResponse1.Content), 0) as TJSONObject;
You don't have to use TEncoding.ASCII. You can also use TEncoding.UTF8/Unicode/Etc depending on your encoding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54894945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to find out which website is requesting my webpage? i have a webpage ... sorto like an api ... basically it prints out some data in form of json .
other website can use this data via php by simply using file_get_contents
or
javascript/jquery ajax request (jsonp)
anyway i want to be able to black list some unwanted websites , so i have to know where this request are coming from
i've tried
$url = $_SERVER['HTTP_REFERER'];
$domain = parse_url($url, PHP_URL_HOST);
but i get
Undefined index: HTTP_REFERER
so unless i'm mistaken and this was an wierd exception , HTTP_REFERER doesn't work here .
so how can i get the referee in case of file_get_contents page request ?
A: Note that Ajax request are usually sent through the client's browser, while usually a server would call file_get_contents() or a similar tool, to fetch your page.
So in the case of a server, you can check the REMOTE_ADDR HTTP header (which contains the caller's IP) against a blacklist.
In the case of an Ajax request, probably from a user agent you can't really say from which website the originated from.
Though I am not sure, but the HTTP_REFERER header might contain exactly that, but again I have not checked it.
UPDATE (Ajax Requests):
After looking up a little bit, I turn out that browsers don't send referrer data with XHR requests, so you can only blacklist the IPs of the servers you don't want to be accessed from.
A: If the server request it directly then you can use $_SERVER 'REMOTE_ADDR' and 'REMOTE_HOST'.
If they use javascript then you will only get the clients ip. You can use strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') to disallow jquery requests.
A: Isn't what you're looking for a $_SERVER['REMOTE_ADDR']? AJAX calls probably won't have a Referer header and that's why you are getting that error.
A: The HTTP Referrer gets sent by a browser, probably not by file_get_contents()!
You can use $_SERVER['REMOTE_ADDR']. This will give you the raw IP address from the TCP stack.
In the case of a server-side API call, you get the server's IP (assuming the client does not use any proxies).
However if the client is an AJAX request, you'll get the IP address of the user viewing that page.
A: HTTP_REFERER is not going to be reliable. You might try $_SERVER['REMOTE_ADDR'] to inspect IP address of remote client.
I would however think that you would have a better time whitelisting approved clients rather then blacklisting, as an attacker could easily proxy a request to get around an IP/host-based blacklist.
There are a number of approaches for whiltelisting:
*
*whitelist known IP's
*HTTP Authentication
*Your own custom API keys
*Third party authentication (i.e. OAuth)
and so forth.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19101841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MonoGame develop3d branch not building on OS X I've successfully built been using the stable branch of MonoGame and the MonoDevelop templates for a while, and now I want to upgrade to the develop3d branch to utilize all its features. But when I build it, it gives me the error:
~/MonoGame/MonoGame.Framework/GamerServices/GamerProfile.cs(67,24): warning CS0628: `Microsoft.Xna.Framework.GamerServices.GamerProfile.Dispose(bool)': new protected member declared in sealed class
~/MonoGame/MonoGame.Framework/Graphics/GraphicsCapabilities.cs(47,7): error CS0246: The type or namespace name `OpenTK' could not be found. Are you missing a using directive or an assembly reference?
I'm totally lost on why this is happening. What OpenTK should I reference? Does it not come with it, so I'd have to download it or something?
EDIT: Building this in Terminal with xbuild and building it in MonoDevelop both yield the same result.
A: Found the solution; replace this in the beginning of Graphics/GraphicsCapabilities.cs:
#if OPENGL
#if GLES
using OpenTK.Graphics.ES20;
//...
with:
#if MONOMAC
using MonoMac.OpenGL;
#elsif OPENGL
#if GLES
using OpenTK.Graphics.ES20;
//...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15238406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Nested List Item not removing from Flask Session I have a simple Route in Flask where I want to add and remove items to a Session dictionary list value. Adding things to it is fine but it doesn't seem to remove the items.
I've tried adding session.modified = True but that doesn't seem to have helped.
What am I doing wrong?
@app.route('/todo/<profile_id>')
def todo(profile_id):
kw = request.args.get('kw', None)
lp = request.args.get('lp', None)
# remove if it exists
try:
session[lp].pop(kw)
session.modified = True
return True
except:
pass
# add if it doesn't exist
if kw and lp:
try:
session[lp].append(kw)
except:
session[lp] = [kw]
return '{}'.format(session[lp])
A: Assuming you want to store generic Objects you will need to use remove() instead of pop().
Your problem after that is returning True, which is not a valid return type for a view. Flask view raises TypeError: 'bool' object is not callable
from flask import session as sesh
@app.route('/todo/<profile_id>')
def todo(profile_id):
kw = request.args.get('kw', None)
lp = request.args.get('lp', None)
# remove if it exists
try:
print(sesh[lp])
sesh[lp].remove(kw)
sesh.modified = True
print("rem", sesh)
return '{}'.format(sesh[lp])
except Exception as e:
print(e)
# add if it doesn't exist
if kw and lp:
try:
sesh[lp].append(kw)
except:
sesh[lp] = [kw]
print("add",sesh)
sesh.modified = True
return '{}'.format(sesh[lp])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51066742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: stuck in lxml and xpath in python 3.x I am parsing an arxml file to extract data from it in python 3.x but I am stuck and can't get myself out the following code. I simply can't understand what I am missing.
With xpath I located the child node from where I want to start extracting data of all its sub-element. I tested the xpath expression (dataExpre3) output in an online tester and it gives me the output as the full xml tree under the node. However, same xpath expression outputs only the list address and not the complete tree under the node in a python code.
Any help on how can I parse child element under node ECUC-CONTAINER-VALUE is really appreciated.
from lxml import etree
arxmlFile = "D:/7_scripts/ArXmlParser/input/EcucValues.arxml"
tree = etree.parse(arxmlFile)
dataExpre3 = "//*[local-name() = 'SUB-CONTAINERS']/*[local-name() = 'ECUC-CONTAINER-VALUE'][1]"
subcontainers = tree.xpath(dataExpre3)
print(subcontainers)
The output in python is:
[<Element {http://autosar.org/schema/r4.0}ECUC-CONTAINER-VALUE at 0x28f8f26a1c0>]
The output in xpath tester is complete xml tree of the first child under node ECUC-CONTAINER-VALUE.
Regards,
A: What you're seeing is the list of Element objects that were selected by xpath().
In this case, it's just one Element with the name {http://autosar.org/schema/r4.0}ECUC-CONTAINER-VALUE. That's the full name with the namespace uri in Clark notation.
If you want to print the serialized tree, try (untested):
print(etree.tostring(subcontainers[0]).decode())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71354956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do i select old date from daterangepicker? I'm using daterangepicker , and I can't select old date from second datepicker section. It shows only from this month.
And There is no arrow clickable on second date picker.
I want that i can select any date , year or month on second datepicker section. There is must js code but i can't figure it out.
Here is my js code
$('.datepicker').daterangepicker({
autoUpdateInput: false,
opens: 'left',
alwaysShowCalendars: true,
showDropdowns: true,
minDate: '01/01/2010',
showOtherMonths: true,
changeMonth: true,
locale: {
cancelLabel: 'Cancel'
}
});
A: Since its a daterange picker you choose a range.
I guess from the moment you choose the starting date, the ending date cannot be older than the starting one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36740353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL How can I return 2 different dates in same query I have a query and what I want to do is return the latest date for 2 columns in the same row. If you look at RowID 1 & 2 I would like to merge both rows. They both have the same Event Type however where they differ is in the isProcessed column one contains 1 and the other 0 value. The LastReceived column should return the latest date where isProcessed is 0 and the LastProcessed column should return the last date where IsProcessed is 1. Right now I have that working but it returns in 2 rows. Row 1 shows the last date of where LastReceived is 0 and Row 2 shows the last date where Lastprocessed is 1. Both LastReceived and LastProcessed come from the column CreatedOn. What I somehow need to do is something like this in the select clause
select MAX(select CreatedOn from mytable where IsProcessed=1) as LastProcessed,
MAX(select CreatedOn from mytable where IsProcessed=0) as LastReceived
This is my query below
with cte as (select distinct EventType,SendingOrganizationID,MAX(CreatedOn) as LastReceived,MAX(CreatedOn) as LastProcessed,case
when SendingOrganizationID = '3yst8' then 'Example 1'
else 'Client Not Found'
END AS ClientName,IsProcessed from mytable
where isprocessed in(0,1)
group by SendingOrganizationID,EventType,IsProcessed
having datediff(hour, MAX(CreatedOn), getdate()) >= 9)
Select ROW_NUMBER() over (ORDER BY SendingOrganizationID) as RowID,* from cte order by SendingOrganizationID,EventType,IsProcessed
Any suggestions would be great
A: You can use case when:
select EventType,SendingOrganizationID,
MAX(case when isProcessed = 0 then CreatedOn end) as LastReceived,
MAX(case when isProcessed = 1 then CreatedOn end) as LastProcessed
from mytable
group by SendingOrganizationID,EventType;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61920261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: swift 4: Setting button's constrains to safe area while inside a view I have a return button that is inside a view on the top left corner, and that view is anchored to the top of the safe area.
What I'm trying to set is the button's top and leading constraint to the top and the leading of the safe area, but since the button is inside a view I guess the safe area is not visible to it?
So what can I do to set the top constraint of the button to the top of the safe area rather than the superview that the button is inside? fix the button issue without taking the button outside of the view and make it overlap with the view and sitting its z-index above it.
superview constraints
button constraints
the arrow-shaped button on the top-left corner, and the view colored with navy blue.
iPhone 8 simulator
iPhone X simulator
A: From your images it seems like that you don't set the top constraint of the top view to top safeAreaLayoutGuide instead you set it to superView here
, also you can't set the top of the button to safeArea , as it's only appears for direct subviews of thw main vc's view not to nested subviews
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53134576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: python matrix multiplication check if number of rows of 1st matrix is equal to number of columns of 2nd matrix I need to perform a matrix multiplication between 2 matrices by taking user input. The below code works fine for the multiplication part but if the no. of rows of 1st matrix are not equal to the no. of columns of the 2nd matrix then it should print NOT POSSIBLE and exit. But it still goes on to add the elements of the matrices. What could possibly be wrong in this code & what could be the solution for the same. Any help would be greatly appreciated
def p_mat(M,row_n,col_n):
for i in range(row_n):
for j in range(col_n):
print(M[i][j],end=" ")
print()
def mat_mul(A_rows,A_cols,A,B_rows,B_cols,B):
if A_cols != B_rows:
print("NOT POSSIBLE")
else:
C = [[0 for i in range(B_cols)] for j in range(A_rows)]
for i in range(A_rows) :
for j in range(B_cols) :
C[i][j] = 0
for k in range(B_rows) :
C[i][j] += A[i][k] * B[k][j]
p_mat(C, A_rows, B_cols)
if __name__== "__main__":
A_rows = int(input("Enter number of rows of 1st matrix: "))
A_cols = int(input("Enter number of columns of 1st matrix: "))
B_rows = int(input("Enter number of rows of 2nd matrix: "))
B_cols = int(input("Enter number of columns of 2nd matrix: "))
##### Initialization of matrix A and B #####
A = [[0 for i in range(B_cols)] for j in range(A_rows)]
B = [[0 for i in range(B_cols)] for j in range(A_rows)]
print("Enter the elements of the 1st matrix: ")
for i in range(A_rows):
for j in range(A_cols):
A[i][j] = int(input("A[" + str(i) + "][" + str(j) + "]: "))
print("Enter the elements of the 2nd matrix: ")
for i in range(B_rows):
for j in range(B_cols):
B[i][j] = int(input("B[" + str(i) + "][" + str(j) + "]:"))
##### Print the 1st & 2nd matrices #####
print("First Matrix : ")
p_mat(A,A_rows,A_cols)
print("Second Matrix : ")
p_mat(B,B_rows,B_cols)
### Function call to multiply the matrices ###
mat_mul(A_rows,A_cols,A,B_rows,B_cols,B)
A: For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix.
If you want to check the no of rows of 1st matrix and the no. of columns of the 2nd matrix then change the if A_cols != B_rows to if A_rows != B_cols
With your current code, it will print NOT POSSIBLE when A_cols != B_rows which is right.
Ex.
Enter number of rows of 1st matrix: 2
Enter number of columns of 1st matrix: 3
Enter number of rows of 2nd matrix: 2
Enter number of columns of 2nd matrix: 3
Enter the elements of the 1st matrix:
A[0][0]: 1
A[0][1]: 2
A[0][2]: 3
A[1][0]: 4
A[1][1]: 5
A[1][2]: 6
Enter the elements of the 2nd matrix:
B[0][0]:1
B[0][1]:2
B[0][2]:3
B[1][0]:4
B[1][1]:5
B[1][2]:6
First Matrix :
1 2 3
4 5 6
Second Matrix :
1 2 3
4 5 6
NOT POSSIBLE
Another mistake in the code is when you are initialize the Matrices.You are doing
A = [[0 for i in range(B_cols)] for j in range(A_rows)]
B = [[0 for i in range(B_cols)] for j in range(A_rows)]
If the B_cols are smaller than the A_cols when you adding elements in A it will raise IndexError
The same if the B_cols are greater than A_cols when you are adding elements to B will raise IndexError.
Change it to
A = [[0 for i in range(A_cols)] for j in range(A_rows)]
B = [[0 for i in range(B_cols)] for j in range(B_rows)]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61943939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Path of assets in CSS files in Symfony 2 Problem
I have a CSS file with some paths in it (for images, fonts, etc.. url(..)).
My path structure is like this:
...
+-src/
| +-MyCompany/
| +-MyBundle/
| +-Resources/
| +-assets/
| +-css/
| +-stylesheets...
+-web/
| +-images/
| +-images...
...
I want to reference my images in the stylesheet.
First Solution
I changed all paths in the CSS file to absolute paths. This is no solution, as the application should (and has to!) be working in a subdirectory, too.
Second Solution
Use Assetic with filter="cssrewrite".
So I changed all my paths in my CSS file to
url("../../../../../../web/images/myimage.png")
to represent the actual path from my resources directory to the /web/images directory. This does not work, since cssrewrite produces the following code:
url("../../Resources/assets/")
which is obviously the wrong path.
After assetic:dump this path is created, which is still wrong:
url("../../../web/images/myimage.png")
The twig code of Assetic:
{% stylesheets
'@MyCompanyMyBundle/Resources/assets/css/*.css'
filter="cssrewrite"
%}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
Current (Third) Solution
Since all CSS files end up in /web/css/stylexyz.css, I changed all paths in the CSS file to be relative:
url("../images/myimage.png")
This (bad) solution works, except in the dev environment:
The CSS path is /app_dev.php/css/stylexyz.css and therefore the image path resulting from this is /app_dev.php/images/myimage.png, which results in a NotFoundHttpException.
Is there a better and working solution?
A: I'll post what worked for me, thanks to @xavi-montero.
Put your CSS in your bundle's Resource/public/css directory, and your images in say Resource/public/img.
Change assetic paths to the form 'bundles/mybundle/css/*.css', in your layout.
In config.yml, add rule css_rewrite to assetic:
assetic:
filters:
cssrewrite:
apply_to: "\.css$"
Now install assets and compile with assetic:
$ rm -r app/cache/* # just in case
$ php app/console assets:install --symlink
$ php app/console assetic:dump --env=prod
This is good enough for the development box, and --symlink is useful, so you don't have to reinstall your assets (for example, you add a new image) when you enter through app_dev.php.
For the production server, I just removed the '--symlink' option (in my deployment script), and added this command at the end:
$ rm -r web/bundles/*/css web/bundles/*/js # all this is already compiled, we don't need the originals
All is done. With this, you can use paths like this in your .css files: ../img/picture.jpeg
A: I had the same problem and I just tried using the following as a workaround. Seems to work so far. You can even create a dummy template that just contains references to all those static assets.
{% stylesheets
output='assets/fonts/glyphicons-halflings-regular.ttf'
'bundles/bootstrap/fonts/glyphicons-halflings-regular.ttf'
%}{% endstylesheets %}
Notice the omission of any output which means nothing shows up on the template. When I run assetic:dump the files are copied over to the desired location and the css includes work as expected.
A: If it can help someone, we have struggled a lot with Assetic, and we are now doing the following in development mode:
*
*Set up like in Dumping Asset Files in the dev Environmen so in config_dev.yml, we have commented:
#assetic:
# use_controller: true
And in routing_dev.yml
#_assetic:
# resource: .
# type: assetic
*Specify the URL as absolute from the web root. For example, background-image: url("/bundles/core/dynatree/skins/skin/vline.gif"); Note: our vhost web root is pointing on web/.
*No usage of cssrewrite filter
A: I have came across the very-very-same problem.
In short:
*
*Willing to have original CSS in an "internal" dir (Resources/assets/css/a.css)
*Willing to have the images in the "public" dir (Resources/public/images/devil.png)
*Willing that twig takes that CSS, recompiles it into web/css/a.css and make it point the image in /web/bundles/mynicebundle/images/devil.png
I have made a test with ALL possible (sane) combinations of the following:
*
*@notation, relative notation
*Parse with cssrewrite, without it
*CSS image background vs direct <img> tag src= to the very same image than CSS
*CSS parsed with assetic and also without parsing with assetic direct output
*And all this multiplied by trying a "public dir" (as Resources/public/css) with the CSS and a "private" directory (as Resources/assets/css).
This gave me a total of 14 combinations on the same twig, and this route was launched from
*
*"/app_dev.php/"
*"/app.php/"
*and "/"
thus giving 14 x 3 = 42 tests.
Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.
The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.
I observed the following:
Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.
These are the results:
*
*Result launched with /app_dev.php/
*Result launched with /app.php/
*Result launched with /
So... ONLY
- The second image
- Div B
- Div C
are the allowed syntaxes.
Here there is the TWIG code:
<html>
<head>
{% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: ABCDEF #}
<link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets 'bundles/commondirty/css_original/d.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: GHIJKL #}
<link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
</head>
<body>
<div class="container">
<p>
<img alt="Devil" src="../bundles/commondirty/images/devil.png">
<img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
</p>
<p>
<div class="a">
A
</div>
<div class="b">
B
</div>
<div class="c">
C
</div>
<div class="d">
D
</div>
<div class="e">
E
</div>
<div class="f">
F
</div>
</p>
<p>
<div class="g">
G
</div>
<div class="h">
H
</div>
<div class="i">
I
</div>
<div class="j">
J
</div>
<div class="k">
K
</div>
<div class="l">
L
</div>
</p>
</div>
</body>
</html>
The container.css:
div.container
{
border: 1px solid red;
padding: 0px;
}
div.container img, div.container div
{
border: 1px solid green;
padding: 5px;
margin: 5px;
width: 64px;
height: 64px;
display: inline-block;
vertical-align: top;
}
And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.
.a
{
background: red url('../images/devil.png');
}
The "directories" structure is:
Directories
All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.
But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:
Compilation process
Note I do this for the --env=prod environment.
Just a few final thoughts:
*
*This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install is executed, then assets:install, then assetic:dump, and then automating the removal of CSS from the public directory after assetic:dump has been executed. This would achive EXACTLY the behaviour desired in the question.
*Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink option when developing.
*Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink usage.
BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.
So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.
The winner is C
A: The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:
*
*Reference the CSS files in the web folder (after: console assets:install --symlink web)
{% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}
*Use the cssembed filter to embed images in the CSS like this.
{% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}
A: I offen manage css/js plugin with composer which install it under vendor.
I symlink those to the web/bundles directory, that's let composer update bundles as needed.
exemple:
1 - symlink once at all (use command fromweb/bundles/
ln -sf vendor/select2/select2/dist/ select2
2 - use asset where needed, in twig template :
{{ asset('bundles/select2/css/fileinput.css) }}
Regards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9500573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "104"
}
|
Q: Core Data Fetch To Many I am trying to fetch all categories, and their sub categories, and display them all in a table. I know how to fetch all categories, but I need to fetch all sub categories, and sort them by category using a fetch results controller. Any ideas of suggestions?
A: You can create a fetched results controller that fetches SubCategory entities and groups them into sections according to the Category:
// Fetch "SubCategory" entities:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SubCategory"];
// First sort descriptor for grouping the cells into sections, sorted by category name:
NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"category.name" ascending:YES];
// Second sort descriptor for sorting the cells within each section:
NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObjects:sort1, sort2, nil];
self.fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:request
managedObjectContext:context
sectionNameKeyPath:@"category.name"
cacheName:nil];
[self.fetchedResultsController setDelegate:self];
NSError *error;
BOOL success = [self.fetchedResultsController performFetch:&error];
Then you can use the usual table view data source methods as described in the NSFetchedResultsController Class Reference.
This gives you a table view with one table view section for each category.
A: so, you have the categories in the fetchedResultsController.fetchedObjects
since each subCategory is essentially contained in the Category you can access each by calling [Category valueForKey:@"subCategory"
this will give you an NSSet that you can then sort out (to an NSArray) and use as data for your tableView.
It won't be contained in a fetchedResultsController though.
A: If you have the option u can do it in other way also if u like.
Take all The Category objects in arrayOfCategories
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection (NSInteger)section:
{
Category *cat = [ arrayOfCategories objectAtIndex:indexPath.row]
if(arrayToHoldObjects.count > 0)
{
[arrayToHoldObjects removeAllObject];
}
for(Subcategory *sub in Category.subcategory)
{
[arrayToHoldObjects addObject:sub];
}
return arrayToHoldObjects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Category *cat = [ arrayOfCategories objectAtIndex:indexPath.row]
if(arrayToHoldObjects.count > 0)
{
[arrayToHoldObjects removeAllObject];
}
for(Subcategory *sub in Category.subcategory)
{
[arrayToHoldObjects addObject:sub];
}
Subcategory *sub = [arrayToHoldObjects objectAtIndexPath.row]
for(int k =0 ; k < arrayToHoldObjects .count; k++)
{
// do what ever u like with sub
return cell;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12993280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Retain submitted data through refreshes I want to retain $orderby and $orderSort (within the query) when I refresh the page or press the links at the bottom of the page to move to next page or previous page.
I have tried attaching orderby and orderSort to sessions but that didn't work due to the query - it always reverts back to Name and ASC from the else statement which seems like an issue with isset($_POST['submit']) but I have tried without it the same problem still occurs.
How do I retain my query (so long as the selections are not changed) as I go to the next page or previous page?
Top PHP portion:
//Next Page
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
} else {
$startrow = (int)$_GET['startrow'];
}
//when options are selected/submitted
if(isset($_POST['submit']))
{
if($_POST['select'] == "EventType")
{
$orderby = $_POST['select'];
if($_POST['otherType'] != "Select an Event") {
$EventType = 'WHERE `' . $orderby . '`="' . $_POST["otherType"] . '"';
}
}
else
{
$orderby = $_POST['select'];
}
$orderSort = $_POST['agree'];
}
else
{
$orderby = "Name";
$orderSort = "ASC";
}
if ($stmt = $local->prepare("SELECT * FROM importdata $EventType ORDER BY `$orderby` $orderSort LIMIT ?,10")) {
$stmt->bind_param('i', $startrow);
$stmt->execute();
$Recordset1 = $stmt->get_result();
$row_Recordset1 = $Recordset1->fetch_assoc();
$stmt->close();
}
Submit Form:
<form id="form1" name="form1" method="post" enctype="multipart/form-data">
<label for="select">Order By:</label>
<select name="select" id="selectType">
<option value="EventType">Event</option>
<option value=" Name"selected="selected">Race Name</option>
</select>
<label><input type="radio" name="agree" value="ASC" checked>Ascend</label>
<label><input type="radio" name="agree" value="DESC">Descend</label>
<input type="submit" name="submit" value="Submit">
</form>
Bottom PHP for next page/previous page
<?php
$prev = $startrow - 10;
if ($prev >= 0)
echo '<a href="'.htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8").'?startrow='.$prev.'">Previous </a>';
echo '<a href="'.htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8").'?startrow='.($startrow+10).'"> Next</a>';
?>
A: You'll have to write the parameters (orderBy and such) into every link, because HTTP is a stateless protocol. This is very tedious, so I suggest to look for a framework that does that for you.
Sessions should work too and for a simple application it might be an easier soultion. How exactly did you store the session variables?
A: I suggest something like this:
// Get our defaults for these variables.
$orderBy = isset($_SESSION['orderBy']) ? $_SESSION['orderBy'] : 'Name';
$orderSort = isset($_SESSION['orderSort']) ? $_SESSION['orderSort'] : 'ASC';
// When options are selected/submitted
if (isset($_POST['submit'])) {
if ($_POST['select'] == "EventType") {
$orderby = $_POST['select'];
if ($_POST['otherType'] != "Select an Event") {
$EventType = 'WHERE `' . $orderby . '`="' . $_POST["otherType"] . '"';
}
} else {
$orderby = $_POST['select'];
}
$orderSort = $_POST['agree'];
// Set our session variables for next time when we set our defaults.
$_SESSION['orderBy'] = $orderBy;
$_SESSION['orderSort'] = $orderSort;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26917593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error: undefined index? I get this array from a function (var_dump()):
...{ [0]=> string(7) "user_id" } [1]=> array(1) { [0]=> string(7) "user_id" } [2]...
When I try to separate the values with:
$var2 = $var['user_id']
I get the error "undefined index 'user_id'", even though, as you can see, the name of the value is "user_id", and I've checked my database a hundred times, and that IS the name of the index.
What other possible sources of error are there?
I appreciate any help!
Thank you in advance!
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT * FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
Can anyone pinpoint where in the above code, I make the mistake leading to this problem?
Thanks.
A: [0] is the index and the data is "user_id"
A: The array key 0 contains a string called 'user_id' but there is no key named 'user_id', hence why you're getting the error.
I suggest you take a look at how you're compiling this data (query results perhaps?).
A: You are mistaken. The structure of the array is like this:
array:
[0] => array:
[0] => "user_id"
[1] => array:
[0] => "user_id"
You need to access it like this: $var[0][0] and you will get user_id. Most likely you did something wrong when setting up the array.
A: the index is [0]. I don't think you have this structured correctly. The index is the left side of the declaration, the value is the right. You have assigned all values to "user_id" with incremental index.
A: user_id is not an array key (that can be accessed by []), it is an value.
But you can use array_search()
$index = array_search('user_id', $your_array);
var_dump( $your_array[$index] );
A: error because the user_id is not an index it's a value having index 0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7850382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: TITokenField- duplicate records are coming, I am using TITokenField and now i don't want to enter duplicate records.
https://www.cocoacontrols.com/controls/titokenfield
User is able to enter duplicate records.
Can anybody tell me how to handle this.
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35333190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ERROR: #1242 - Subquery returns more than 1 row in the query - MYSQL Below is the MySQL code where a subquery is returned. And I want the subquery to return just one row.
SELECT DISTINCT w.cname
FROM works w
WHERE
(SELECT DISTINCT w.cname, AVG(w.salary)
FROM works w
WHERE 1
GROUP BY w.cname
)
<
(SELECT DISTINCT w.cname,AVG(w.salary)
FROM works w
WHERE 1
GROUP BY w.cname
)
MySQL error said:
1242 - Subquery returns more than 1 row
A: First of all, the literal answer: if a subquery you use as an expression returns more than one row, modify it so that it returns at most one row.
I'm going to take a wild guess and say that you want to find workers that earn less than the average salary. The solution would be:
SELECT -- add DISTINCT if needed
w.cname
FROM
works w
WHERE
w.salary < (SELECT AVG(w2.salary) FROM works w2)
Note that the subquery here (SELECT AVG(w2.salary) FROM works w2) will always return a single value, since there is no GROUP BY clause. (Also, since this instance of the works table has nothing to do with the other one, because you're getting something completely unrelated out of it, it's good practice (and required by some DBMS or another) to use a different table alias — hence w2.)
Note that, since you can reference your original table in subqueries, you can use the data in the outer query's FROM clause to filter the subquery. For instance, if you want to return every instance of people earning less than their own average salary:
SELECT DISTINCT
w.cname, w.salary
FROM
works w
WHERE
w.salary < (SELECT AVG(w2.salary) FROM works w2 WHERE w2.cname = w.cname)
Note how the different table aliases (w and w2) matter here. Also, this subquery still returns only one row, because the filter by name is in the WHERE clause — it returns the average of all salary rows matching that particular name, not the average of all salary rows grouped by name. The former is one value (for one particular person), the latter is one value per person (and thus an error).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54965977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ArrayAdapter for FragmentList crashes applications This is my code for an android application:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Attempting to set the Fragment
System.err.println("Starting");
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
System.err.println("Adding the fragment");
FileBrowser fb = new FileBrowser();
ft.add(R.id.flFBrowser,fb);
ft.commit();
System.err.println("Done");
fb.test();
}
Where the file browser only has this:
public void test(){
System.err.println("Entre a test!!!");
String[] MyList = {"Hello","world","of","the","lists"};
System.err.println("File Row ID" + Integer.toString(R.layout.file_row));
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(), R.layout.file_row, MyList);
//setListAdapter(aa);
}
The thing is if I comment the ArrayAdapter constructor the program does not crash If I uncomment it, it crashes with the following error:
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): FATAL EXCEPTION: main
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ccr/com.ccr.Main}: java.lang.NullPointerException
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1748)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.app.ActivityThread.access$1500(ActivityThread.java:122)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.os.Handler.dispatchMessage(Handler.java:99)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.os.Looper.loop(Looper.java:132)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.app.ActivityThread.main(ActivityThread.java:4025)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at java.lang.reflect.Method.invoke(Method.java:491)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at dalvik.system.NativeStart.main(Native Method)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): Caused by: java.lang.NullPointerException
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.widget.ArrayAdapter.init(ArrayAdapter.java:314)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at com.ccr.FileBrowser.test(FileBrowser.java:13)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at com.ccr.Main.onCreate(Main.java:24)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
06-11 10:12:38.150: ERROR/AndroidRuntime(4804): ... 11 more
Does any one have any Idea what I could be doing wrong?
Thanks for any help!
UPDATE:
The problem seems to be specifically that getActivity returns null?
Any Idea why this is?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6316103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Printing array of specific element C programming:
Was assign to derive values from a text file using File i/o and print array of a specific element instead of everything in the array.
For example:
After accessing the file using File i/o, I use printf(“%s”, readings); and was able to print all the reading in the array. But i want to print a specific element in the array like: printf(“%s”, readings[4]); but nothing is printed when i input this line.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65081498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Checking for empty fields on HTML form I am trying to create a form in HTML, and also trying to ensure that any field is not left empty.
Here is the HTML for the form
<form role="form" id="companyDetails" name="companyDetails" method="post" action="saveCompanyDetails.jsp" onsubmit="return false;">
<div class="col-lg-6">
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control" id="cmpname" name="cmpname">
<p id="cmpnameError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" rows="3" id="desc" name="desc"></textarea>
<p id="descError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Url</label>
<input type="text" class="form-control" name="url" id="url">
<p id="urlError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Email Id</label>
<input type="text" class="form-control" name="emailid" id="emailid">
<p id="emailidError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" rows="3" id="address" name="address"></textarea>
<p id="addressError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<h1>All Links <i class="fa fa-link"></i></h1>
<div class="form-group">
<label>Facebook Link</label>
<input type="text" class="form-control" name="fblink" id="fblink">
<p id="fblinkError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Twitter Link</label>
<input type="text" class="form-control" name="twlink" id="twlink">
<p id="twlinkError" style="display: none; color: red; font-weight: bold;"></p>
</div>
</div>
<!-- /.col-lg-6 (nested) -->
<div class="col-lg-6">
<div class="form-group">
<label>Linkedin Link</label>
<input type="text" class="form-control" name="linkinlink" id="linkinlink">
<p id="linkinlinkError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Download Link</label>
<input type="text" class="form-control" name="downlink" id="downlink">
<p id="downlinkError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Live Help Link</label>
<input type="text" class="form-control" name="livehelplink" id="livehelplink">
<p id="livehelpError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Terms & Condition Link</label>
<input type="text" class="form-control" name="tclink" id="tclink">
<p id="tclinkError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Promotion Link</label>
<input type="text" class="form-control" name="prolink" id="prolink">
<p id="prolinkError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Sign Up Link</label>
<input type="text" class="form-control" name="signuplink" id="signuplink">
<p id="signuplinkError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Affiliate Link</label>
<input type="text" class="form-control" name="affiliatelink" id="affiliatelink">
<p id="affiliatelinkError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<div class="form-group">
<label>Game Link</label>
<input type="text" class="form-control" name="gamelink" id="gamelink">
<p id="gamelinkError" style="display: none; color: red; font-weight: bold;"></p>
</div>
<button type="submit" class="btn btn-default" onclick="submitData()"><i class="fa fa-check"></i>Submit</button>
<button type="reset" class="btn btn-default"><i class="fa fa-refresh"></i>Reset</button>
</div>
</form>
Notice that I have a <p> tag just below every input field, whose ID value is constructed from the ID of its corresponding input field. For eg. the <p> tag below text field cmpname is given ID cmpnameError
Now the JavaScript code for displaying the error message below the text field is given below
function submitData() {
var elements = document.querySelectorAll('#companyDetails input, #companyDetails textarea');
for (var i = 0; i < elements.length; i++) {
if (elements[i].value == "") {
var errorElementId = "#" + elements[i].id + "Error";
// alert("Generated ID is " + errorElementId);
document.getElementById(errorElementId).style.display = '';
document.getElementById(errorElementId).innerHTML = "Please enter a value for this field";
return false;
}
}
document.forms['companyDetails'].submit();
return true;
}
My problem is that the proper error message is not getting displayed on the form when I click submit.
Can anybody please help me regarding this? Thank you very much in advance.
Here is the JSFiddle link- https://jsfiddle.net/v8ooy2e1/
A: The pound sign is used to select elements with ids using querySelectorAll, but it shouldn't be used with getElementById.
Remove the pound sign here:
var errorElementId = "#" + elements[i].id + "Error";
Should be:
var errorElementId = elements[i].id + "Error";
Working Fiddle
A: You know, assuming IE 10+, you could skip all this javascript fanciness and just use the "required" attribute:
<input type="text" class="form-control" id="cmpname" name="cmpname" required>
That'll invoke the browser supported form validation.
A: Why do you have:
var errorElementId = "#" + elements[i].id + "Error";
Leave out the "#" sign.
A: If you can use jQuery
var isValid = true;
$("#companyDetails").submit(function(event) {
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
}
})
if (!isValid) {
alert("nopes");
}
});
FIDDLE
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29145190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Multiple websockets from the same page with java as the server side In my web-app I have 2 websocket connecting to server on the same port. One websocket is used for chat messenger and the other
websocket on the same page displays the total number of people currently viewing that event.
Chat Websocket:
var chat = new WebSocket("ws://localhost:8080/chat");
I have a send button on my chat window and when user clicks on the send button function send_message is called which send the message
to the server through websocket chat.
function send_message() {
chat.send("Hey There!");
}
And when the message is recived from the server I am calling onMessage function to get the data.
chat.onmessage = function(evt) { onMessage(evt) };
function onMessage(evt) {
alert('Message Recived from server: "+evt.data);
}
The chat websocket gets opened as soon as the page loads while the attendeeCount websocket gets open when any user clicks on the join event
button. I want to show the other users count of attendees increasing or decreasing as a live update if someone joins or leaves the event. So,
Lets say if a user is attending an event and current attendee count he is seeing right now is 10 and another user joins the event then
the count should get updated to 11.
When a user clicks on the Join Event button an ajax call is made to the server and an entry is made in the attendee table. So once the ajax
call is success in the success callback of my ajax call I am opening the 2nd websocket connection and sending the data to the server to
show updated attendee count to the other users. It is exactly like Facebook likes which gets updated in front of your eyes without
refreshing the page.
$.ajax({
type: 'POST',
url: '/mixtri/rest/event/updateAttendeeCount',
contentType: "application/x-www-form-urlencoded",
data: {data},
success: function(result){
var attendeeCount = new WebSocket("ws://localhost:8080/attendeeCount");
attendeeCount.onopen = function(evt) { onOpen(attendeeCount,result.countOfAttendees) };
attendeeCount.onmessage = function(evt) { onAttendeeJoin(evt) };
}
});
/*Function called in ajax success call back to send data to the server via websocket attendeeCount */
function onOpen(attendeeCount,countOfAttendees) {
console.log('Connected live Data Update: ');
attendeeCount.send(countOfAttendees);
}
Now when the message is recived from the server I am updating the attendee count on the UI in the method onAttendeeJoin all users.
/*Function called when message recieved from the server*/
function onAttendeeJoin(evt) {
var attendeeCount = evt.data;
$('#attendeeCount').html(' '+attendeeCount);
}
Now I have couple of question:
*
*Can we open more than 2 websockets from the same page? Because i need more as well to show some more live updates on my page.
*Another problem is my attendeeCount is getting updated correctly on the UI for other users, but my chat websocket is clashing with
my attendeeCount websocket. With clashing I mean, as soon as user types something in the chat window and clicks on send button the onMessage
function for the chat websocket get called perfectly fine but the onAttendeeJoin function which is attached to attendeeCount websocket also
gets called and my chat message gets displayed in $('#attendeeCount').html(' '+attendeeCount) div as well. I am not able to figure out
why this is happening? Although both onAttendeeJoin and onMessage function are bound to same type of event i.e onmessage but they are
from different webockets.
*If I get answer to my first two questions my last question is, right now when a user uses a chat functionality the message goes to
all the users on that page irrespective of the event they are attending. So a user attending an event1 send a message and user in the
event2 gets that message as well which is incorrect. Ideally users from event1 can only seen messages from users attending event1.
I other words, people in the same chat room should only be able to chat with each other and their messages should not go outside the chat
room. How can I bind my event id in the websocket with the people attending that event so that the messages within the same event chat
room remains within.
A: I'll put my comments into an answer:
Can we open more than 2 websockets from the same page? Because i need
more as well to show some more live updates on my page.
Yes, you can, but you shouldn't need to. Why open more than one webSocket? It's just a communications channel. You can send different messages related to different topics over that one channel. You really shouldn't need multiple webSockets between the same page/server.
The general idea is that you don't just send data, but you send a message name and some data. Then, all receiving code can decide what to do based on the message name. You might be interested in socket.io which creates this format for you on top of webSocket, or you can do it yourself with webSocket as shown here.
If I get answer to my first two questions my last question is, right
now when a user uses a chat functionality the message goes to all the
users on that page irrespective of the event they are attending. So a
user attending an event1 send a message and user in the event2 gets
that message as well which is incorrect. Ideally users from event1 can
only seen messages from users attending event1. I other words, people
in the same chat room should only be able to chat with each other and
their messages should not go outside the chat room. How can I bind my
event id in the websocket with the people attending that event so that
the messages within the same event chat room remains within.
webSockets themselves don't have the "attending the event" capability you are asking for. With plain webSockets, you would have to keep track of which socket was in which event and when you want to send to an event, you send to only the connected webSockets associated with that event. It would be all your own code that would do that. Again, the socket.io library I mentioned above has this capability built-in. It sounds like what you really want. There is Java server support for socket.io too. socket.io has built-in chat rooms and the ability to broadcast to those in a given chat room.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32493212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TypeAhead Feature TextBox Control Windows C# I am using typeahead feature of TextBox .. all I want is that the Typeahead should show all the Items available in AutoCompleteStringCollection.
Currently its suggesting me those string whcih starts with the characters that I type.
What I need is the characters that I type can exist anywhere in the string not only at beginning.
On TextChange Event
What I am doing to get this is making a temp AutoCompleteStringCollection and associating it with the textBox.
Now all I need to do is just display that every time.
any Ideas?
A: The Winform controls with AutoComplete support are using IE's AutoComplete APIs, which does not support ACO_NOPREFIXFILTERING until Windows Vista. Since WinForm needs to support earlier systems, ACO_NOPREFIXFILTERING is not supported in .Net.
If you want to use this feature when it is available, you can skip Windows Form's AutoComplete support and call the API directly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1504646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to change this code so that its loops are removed and replace with tensorflow? I used the following code as part of my deep learning algorithm.
But due to the existence of loops, its execution time is very long.
Can you implement it only with tensorflow's methods?
def build_reward(self):
self.permutations = tf.stack([tf.tile(tf.expand_dims(tf.range(self.batch_size,dtype=tf.int32),1),[1,self.max_length+1]),self.tour],2)
output_list = []
if self.is_training==True:
self.ordered_input_ = tf.gather_nd(self.input_,self.permutations)
self.ordr = tf.gather_nd(self.order_,self.permutations)
else:
self.ordered_input_ = tf.gather_nd(tf.tile(self.input_,[self.batch_size,1,1]),self.permutations)
self.ordr = tf.gather_nd(tf.tile(self.order_,[self.batch_size,1]),self.permutations)
def Tca(indx, l, bth):
t = 0.0
n = 0
f = 0
p = 0
result = 0.0
for i in range(self.max_length):
t = tf.math.floor(self.ordered_input_[bth,i,indx])
p = tf.cond(tf.logical_and((tf.logical_or(tf.logical_or(tf.logical_or(tf.math.equal(t,1.0),
tf.math.equal(t,5.0)),
tf.math.equal(t,6.0)),
tf.math.equal(t,8.0))),tf.math.not_equal(i,l)),
lambda:i, lambda:-1)
n += tf.cond(tf.math.not_equal(p,-1), lambda:1, lambda:0)
f += tf.cond(
tf.logical_and(
tf.math.not_equal(p,-1),
tf.math.greater(
tf.math.count_nonzero(
tf.math.equal(
self.ordr[bth,:l],
self.ordr[bth,p]
)
), 0
)
), lambda: 1, lambda:0
)
result = tf.cond(tf.math.equal(n,f), lambda:0.0, lambda:1.0)
return result
for b in range(0,self.batch_size):
fuse = 0
rsize = tf.math.floor(self.ordered_input_[b,0,self.ordr[b,0]])
rgstr = tf.math.ceil(
tf.math.multiply(
tf.math.subtract(
self.ordered_input_[b,0,self.ordr[b,1]],
tf.math.floor(self.ordered_input_[b,0,self.ordr[b,1]])
), 10
)
)
r = 0
rwrd = 0.0
dt = 0.0
for i in range(self.max_length-1):
fuse = 0
dt = tf.math.floor(self.ordered_input_[b,i,self.ordr[b,i+1]])
r = tf.math.ceil(
tf.math.multiply(
tf.math.subtract(
self.ordered_input_[b,(i+1),self.ordr[b,(i+2)]],
tf.math.floor(self.ordered_input_[b,(i+1),self.ordr[b,(i+2)]])
), 10
)
)
rwrd += tf.truediv(dt,10.0)
pnlty = tf.cond(
tf.math.not_equal(dt,10.0),
lambda:Tca(self.ordr[b,i+1],(i+1), b), lambda:1.0
)
fuse = tf.cond(
tf.logical_and(
tf.math.equal(pnlty,0.0),
tf.logical_or(
tf.math.equal(dt,1.0),
tf.math.equal(dt,3.0)
)
),
lambda:1, lambda:0
)
rgstr = tf.cond(
tf.math.not_equal(fuse,1),
lambda:r,
lambda:rgstr
)
rgstr += tf.cond(tf.math.equal(fuse,1), lambda:r, lambda:0.0)
pnlty += tf.cond(tf.math.not_equal(fuse,1), lambda:1.0, lambda:0.0)
pnlty += tf.cond(
tf.logical_and(
tf.math.greater(rgstr,self.register),
tf.math.equal(fuse,1)
),
lambda:1.0, lambda:0.0
)
rgstr = tf.cond(tf.math.greater(rgstr,self.register),
lambda:r, lambda:rgstr)
rwrd += pnlty
output_list.append(rwrd)
As you can see, the code consists of three nested loops.
This will greatly increase the codes performance.
I'm looking for a way to reduce its run time.
One of my options could be to remove the loops.
But I do not think it is possible for the logic behind this code.
I will be grateful if anyone can guide me in this regard.
Also, if someone can remove some of these loops, it will help me a lot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65449395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error creating jar file in eclipse export When I run the project IDE it compiles fine and runs through IDE but when I export it as a jar file. I get -fat java export: could not find class path entry for my project folder location. I couldn't figure whats causing this issue. Suggestions and solutions are welcome.
Exported with compile warnings:
Jar export finished with problems. See details for additional information.
Fat Jar Export: Could not find class-path entry for 'C:Users/sivap/OneDrive/Desktop/eclipse workspace/Eclipse Workspace PITCON - To Edit - Copy/Questron'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58217538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: IOS: Load a View Controller When App is Launched from Browser using url schemes? I am new to iPhone developing , My app is based on video conferencing, I have a task where an app should launch from browser using URL schemes. I have done it but problem is when app launched from browser it should load particular view controller. I am using Storyboard. Here is the code which I tried.
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
if (!url) { return NO;
}
NSString *URLString = [url absoluteString];
[[NSUserDefaults standardUserDefaults] setObject:URLString forKey:@"url"];
[[NSUserDefaults standardUserDefaults] synchronize];
URLParser *parser = [[URLParser alloc] initWithURLString:URLString];
username = [parser valueForVariable:@"USERNAME"];
NSLog(@"%@", username); //b
sessid = [parser valueForVariable:@"SESSION_ID"];
NSLog(@"%@", sessid); //(null)
tokenid = [parser valueForVariable:@"token"];
NSLog(@"%@", tokenid); //yes
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
ViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"VideoController"];
return YES;
}
A: This is how I do it..
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//get parameters
[self goResetPassword:dict];
}
return YES;
}
- (void) goResetPassword:(NSDictionary*) dict{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UINavigationController *root = [[UINavigationController alloc]initWithRootViewController:[storyboard instantiateViewControllerWithIdentifier:@"resetPasswordView"]];
self.window.rootViewController= root;
ResetPasswordViewController *vc = (ResetPasswordViewController*)[[root viewControllers] objectAtIndex:0];
[vc loadData:dict];
}
hope it helps... GL HF
A: According to your comment your initial ViewController is NavigationController. This is how you can push the required ViewController.
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
// same code
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
// Get instance of initial Viewcontroller from storyboard
UINavigationController *navController = [storyboard instantiateInitialViewController
];
// Get instance of desired viewcontroller
ViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"VideoController"];
// Push ViewController on to NavigationController
[navController pushViewController:viewController animated:NO];
return YES;
}
A: Check It
UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UINavigationController *nav = [[UINavigationController alloc] init];
[nav setNavigationBarHidden:NO];
IntroVC *initailView = [board instantiateViewControllerWithIdentifier:@"Intro"];
[nav pushViewController:initailView animated:YES];
self.window.rootViewController = nav;
[self.window makeKeyAndVisible];
UIApplication *sharedApplication = [UIApplication sharedApplication];
[sharedApplication unregisterForRemoteNotifications];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21325372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: nested virtualization with KVM: -enable-kvm in qemu in nested virtualization In my already virtualized host, trying to pass the option the option -enable-kvm -m 1024, will fail:
qemu-system-x86_64 -vga std -enable-kvm -m 1024 -monitor telnet:localhost:9313,server,nowait -drive file=my_img.img,cache=none
# Could not access KVM kernel module: No such file or directory
# failed to initialize KVM: No such file or directory
If I remove that option -enable-kvm -m 1024, qemu will load (but it will take forever, because it is using software emulation):
qemu-system-x86_64 -vga std -monitor telnet:localhost:9313,server,nowait -drive file=my_img.img,cache=none
# qemu running, OK, but image taking forever to load.
Surely, this virtualized host of mine has capabilities of nesting its own virtualization. Everywhere I find information about it [like here: https://docs.openstack.org/developer/devstack/guides/devstack-with-nested-kvm.html ] tells me that I must check the file /sys/module/kvm_intel/parameters/nested which is simply not available, because kvm-intel isn't and can't be loaded from inside an image:
sudo modprobe kvm-intel
# modprobe: ERROR: could not insert 'kvm_intel': Operation not supported
Probably that method of debugging nested virtualization only works in the bare metal. So, how do I enable (forward the support of) kvm from inside a kvm?
Additional info:
lscpu # from inside the virtualized host
# Architecture: x86_64
# ...
# Vendor ID: GenuineIntel
# CPU family: 6
# Model: 13
# Model name: QEMU Virtual CPU version (cpu64-rhel6)
# Stepping: 3
# ...
# Hypervisor vendor: KVM
ltrace of qemu:
# open64("/dev/kvm", 524290, 00) = -1
# __errno_location() = 0x7f958673c730
# __fprintf_chk(0x7f957fd81060, 1, 0x7f9586474ce0, 0Could not access KVM kernel module: No such file or directory
A: To test if the kvm support is enabled in the current host (ie, it works in the virtual machine) do:
grep -E "(vmx|svm)" /proc/cpuinfo
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 popcnt aes xsave avx f16c lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt lwp fma4 tce tbm topoext perfctr_core perfctr_nb arat cpb hw_pstate npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold vmmcall bmi1
In the question:
grep -E "(vmx|svm)" /proc/cpuinfo | wc -l
0
It means that the support is disabled, and enable-kvm won't work. Action in the bare metal machine is required.
A: By default, Linux KVM has nested virtualization support disabled.
You have to enable it in the host of the outermost VM (in your question you tried to do that inside the outermost VM, instead). For example, for an Intel CPU:
# rmmod kvm_intel
# modprobe kvm_intel nested=1
Verification (on the host of the outermost VM):
$ cat /sys/module/kvm_intel/parameters/nested
Y
(The KVM module for AMD is unsurprisingly called kvm_amd.)
Nesting can be enabled persistently via dropping a config file into /etc/modprobe.d.
This is a necessary condition for nested virtualization. In addition to that, you need to tell QEMU to enable virtualization support in the outermost VM by supplying the right CPU argument, e.g.:
-cpu host
or something more specific like:
-cpu Haswell-noTSX-IBRS,vmx=on
Inside the outermost VM, you can verify virtualization support via:
$ grep -o 'vmx\|svm' /proc/cpuinfo
$ kvm-ok
INFO: /dev/kvm exists
KVM acceleration can be used
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43942033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Twitter bootstrap grid guide I am hoping someone can help me with this I am slightly confused with this I have always worked with 960 grid system. Making a Responsive design with Twitter Bootstrap, see the problem I am having is that the Desktop view on the twitter site states
Label Layout width Column width Gutter width
Large display 1200px and up 70px 30px
Default 980px and up 60px 20px
Portrait tablets 768px and above 42px 20px
Phones to tablets 767px and below Fluid columns, no fixed widths
Phones 480px and below Fluid columns, no fixed widths
Surely it should be Default 960px and up? with 60*12 + 20* = 960px?
Is is there something I am missing or is it simply will need to use the customizer?
Basically should the size of my PSD be 940px still (as it would normally?) or should it be 960px?
A:
Surely it should be Default 960px and up? with 60*12 + 20* = 960px?
If you allow for 20px padding before the first column, 20px between each each column and 20px after the last column the total is 12*(60+20) + 20 = 980px
should the size of my PSD be 940px still (as it would normally?) or
should it be 960px?
Yes, design for 940px wide. As long as the device window is 980px or more it will display full width.
If you are coming from 960.gs, the design width is the same. The difference is that bootstap has an extra 10px margin at the start and end of every row so it needs a 980px wide window to display full width.
If you are looking for bootstap layout templates for the different widths, here is one good source https://benstewart.net/2012/06/bootstrap-responsive-photoshop-templates/
A: From bootstrap, this is correct...
*
*Large display 1200px and up
*Default 980px and up
*Portrait tablets 768px and above
*Phones to tablets 767px and below
*Phones 480px and below
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14386975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVVM Binding Selected RadOutlookBarItem Imagine:
[RadOutlookBarItem1]
[RadOutlookBarItem2]
[RadOutlookBar] [CONTENCONTROL]
What i want to achieve is:
User selects one of the RadOutlookBarItem's. Item's tag is bound like:
Tag="{Binding SelectedControl, Mode=TwoWay}"
MVVM Property
public string SelectedControl
{
get { return _showControl; }
set
{
_showControl = value;
OnNotifyPropertyChanged("ShowControl");
}
}
ContentControl has multiple CustomControls and Visibility of those is bound like:
<UserControl.Resources>
<Converters:BoolVisibilityConverter x:Key="BoolViz"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Views:ViewDocumentSearchControl Visibility="{Binding SelectedControl, Converter={StaticResource BoolViz}, ConverterParameter='viewDocumentSearchControl'}"/>
<Views:ViewStartControl Visibility="{Binding SelectedControl, Converter={StaticResource BoolViz}, ConverterParameter='viewStartControl'}"/>
</Grid>
Converter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// here comes the logic part... should return Visibility.Collapsed : Visibility.Visible based on 'object value' value
System.Diagnostics.Debugger.Break();
return Visibility.Collapsed;
}
now, logically the object value is always set to null. So here's it comes to my question: How can i put a value into the SelectedControl Variable for the RadOutlookBarItem's Tag. I mean something like
Tag="{Binding SelectedControl, Mode=TwoWay, VALUE='i.e.ControlName'"}
So that i can decide, using the Convert Method, whether a specific Control's visibility is either set to collapsed or visible?
help's appreciated
Christian
--- Solution from Laurent ---
Yes, that's what i want,unfortunately VS.NET 2010 / Blend 4RC crashes after implementing it like this:
<Views:ViewDocumentSearchControl Visibility="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource BoolViz}}"/> <Views:ViewStartControl Visibility="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource BoolViz}}"/>
whenever i open the XAML in Blend / VS.NET i get a XYZ has stopped working. Changed the ValueConverter's return to Visibility.Visible, still the same. No idea. Thanks anyway! Christian
--- my (temporary) solution/workaround---
Okay, i ended up with this solution:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && parameter != null)
{
var val = (string) value;
var ctrl = (string) parameter;
if (val.Equals(ctrl))
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
return Visibility.Collapsed;
}
and set the .Tag of the RadOutlookBarItem in the Codebehind...
A: It sounds like you want to pass the current item to the converter and return a Visibility. It is possible that I didn't completely understood what you mean, but if that is the case, this should work for you:
Visibility={Binding RelativeSource={RelativeSource Self}, Converter={StaticResource BoolViz}}
The "value" parameter will be set to the ViewDocumentSearchControl in the first case, and to the ViewStartControl in the second case.
Is that what you were looking for?
Cheers,
Laurent
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2673342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error while installing react-native-queue library I'm installing the react native queue library like so:
npm install --save react-native-queue. But I'm getting the following error:
TOUCH Release/obj.target/OpenSSL.stamp
ACTION binding_gyp_vendored_realm_target_download_realm /Users/prikshetsharma/Desktop/Humboi/node_modules/realm/vendor/realm-mac-x64
Resolved requirements: {
SYNC_SERVER_FOLDER: 'sync',
SYNC_ARCHIVE: 'realm-sync-node-cocoa-4.7.3.tar.gz',
SYNC_ARCHIVE_ROOT: 'realm-sync-node-cocoa-4.7.3'
}
No lockfile found at the target, proceeding.
Download url: https://static.realm.io/downloads/sync/realm-sync-node-cocoa-4.7.3.tar.gz
Downloading realm-sync-node-cocoa-4.7.3.tar.gz [====================] (1886k)
Extracting realm-sync-node-cocoa-4.7.3.tar.gz => /Users/prikshetsharma/Desktop/Humboi/node_modules/realm/vendor/realm-mac-x64
Success
TOUCH Release/obj.target/vendored-realm.stamp
TOUCH Release/obj.target/realm-core.stamp
TOUCH Release/obj.target/realm-sync.stamp
CXX(target) Release/obj.target/object-store/src/object-store/src/binding_callback_thread_observer.o
CXX(target) Release/obj.target/object-store/src/object-store/src/collection_notifications.o
CXX(target) Release/obj.target/object-store/src/object-store/src/index_set.o
CXX(target) Release/obj.target/object-store/src/object-store/src/list.o
CXX(target) Release/obj.target/object-store/src/object-store/src/object.o
CXX(target) Release/obj.target/object-store/src/object-store/src/object_schema.o
CXX(target) Release/obj.target/object-store/src/object-store/src/object_store.o
CXX(target) Release/obj.target/object-store/src/object-store/src/placeholder.o
CXX(target) Release/obj.target/object-store/src/object-store/src/results.o
CXX(target) Release/obj.target/object-store/src/object-store/src/schema.o
CXX(target) Release/obj.target/object-store/src/object-store/src/shared_realm.o
CXX(target) Release/obj.target/object-store/src/object-store/src/thread_safe_reference.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/collection_change_builder.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/collection_notifier.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/list_notifier.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/object_notifier.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/primitive_list_notifier.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/realm_coordinator.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/results_notifier.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/transact_log_handler.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/weak_realm_notifier.o
CXX(target) Release/obj.target/object-store/src/object-store/src/util/uuid.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/apple/external_commit_helper.o
CXX(target) Release/obj.target/object-store/src/object-store/src/impl/apple/keychain_helper.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/impl/apple/network_reachability_observer.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/impl/apple/system_configuration.o
CXX(target) Release/obj.target/object-store/src/object-store/src/util/fifo.o
CXX(target) Release/obj.target/object-store/src/object-store/src/server/adapter.o
CXX(target) Release/obj.target/object-store/src/object-store/src/server/admin_realm.o
CXX(target) Release/obj.target/object-store/src/object-store/src/server/global_notifier.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/impl/sync_file.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/impl/sync_metadata.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/impl/work_queue.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/partial_sync.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/async_open_task.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/sync_config.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/sync_manager.o
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/sync_session.o
../src/object-store/src/sync/sync_session.cpp:567:17: warning: enumeration value
'http_tunnel_failed' not handled in switch [-Wswitch]
switch (static_cast<ClientError>(error_code.value())) {
^
../src/object-store/src/sync/sync_session.cpp:567:17: note: add missing switch
cases
switch (static_cast<ClientError>(error_code.value())) {
^
1 warning generated.
CXX(target) Release/obj.target/object-store/src/object-store/src/sync/sync_user.o
LIBTOOL-STATIC Release/object-store.a
CXX(target) Release/obj.target/realm/src/js_realm.o
CXX(target) Release/obj.target/realm/src/node/node_init.o
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:21:
In file included from ../src/node/node_string.hpp:21:
../src/node/node_types.hpp:52:42: error: no type named
'NamedPropertyGetterCallback' in namespace 'v8'; did you mean
'IndexPropertyGetterCallback'?
using StringPropertyGetterCallback = v8::NamedPropertyGetterCallback;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
IndexPropertyGetterCallback
../src/node/node_types.hpp:50:11: note: 'IndexPropertyGetterCallback' declared
here
using IndexPropertyGetterCallback = Nan::IndexGetterCallback;
^
../src/node/node_types.hpp:53:42: error: no type named
'NamedPropertySetterCallback' in namespace 'v8'; did you mean
'IndexPropertySetterCallback'?
using StringPropertySetterCallback = v8::NamedPropertySetterCallback;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
IndexPropertySetterCallback
../src/node/node_types.hpp:51:11: note: 'IndexPropertySetterCallback' declared
here
using IndexPropertySetterCallback = Nan::IndexSetterCallback;
^
../src/node/node_types.hpp:54:50: error: no type named
'NamedPropertyEnumeratorCallback' in namespace 'v8'; did you mean
'IndexedPropertyEnumeratorCallback'?
using StringPropertyEnumeratorCallback = v8::NamedPropertyEnumeratorCallback;
~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
IndexedPropertyEnumeratorCallback
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:6317:16: note:
'IndexedPropertyEnumeratorCallback' declared here
typedef void (*IndexedPropertyEnumeratorCallback)(
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:21:
../src/node/node_string.hpp:51:32: error: too few arguments to function call,
single argument 'isolate' was not specified
m_str.resize(s->Utf8Length());
~~~~~~~~~~~~~ ^
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:2977:3: note:
'Utf8Length' declared here
int Utf8Length(Isolate* isolate) const;
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:21:
../src/node/node_string.hpp:53:18: error: cannot initialize a parameter of type
'v8::Isolate *' with an rvalue of type 'std::__1::basic_string<char,
std::__1::char_traits<char>, std::__1::allocator<char> >::value_type *'
(aka 'char *')
s->WriteUtf8(&m_str[0], m_str.size(), 0, flags);
^~~~~~~~~
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:3037:26: note:
passing argument to parameter 'isolate' here
int WriteUtf8(Isolate* isolate, char* buffer, int length = -1,
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:24:
../src/node/node_object.hpp:33:57: error: no type named
'ExternalOneByteStringResourceImpl' in namespace 'v8'; did you mean
'Nan::ExternalOneByteStringResource'?
...new v8::ExternalOneByteStringResourceImpl(key.data(), key.size()));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Nan::ExternalOneByteStringResource
../../nan/nan.h:193:5: note: 'Nan::ExternalOneByteStringResource' declared here
ExternalOneByteStringResource;
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:24:
../src/node/node_object.hpp:33:61: error: allocating an object of abstract class
type 'Nan::ExternalOneByteStringResource' (aka
'v8::String::ExternalOneByteStringResource')
node_key = v8::String::NewExternal(isolate, new v8::ExternalOneByt...
^
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:3153:25: note:
unimplemented pure virtual method 'data' in 'ExternalOneByteStringResource'
virtual const char* data() const = 0;
^
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:3155:20: note:
unimplemented pure virtual method 'length' in
'ExternalOneByteStringResource'
virtual size_t length() const = 0;
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:24:
../src/node/node_object.hpp:33:32: error: no member named 'NewExternal' in
'v8::String'
node_key = v8::String::NewExternal(isolate, new v8::ExternalOneByt...
~~~~~~~~~~~~^
../src/node/node_object.hpp:36:77: error: no member named 'kNormalString' in
'v8::String'
node_key = v8::String::NewFromUtf8(isolate, key.data(), v8::String::kNorma...
~~~~~~~~~~~~^
../src/node/node_object.hpp:108:32: error: no matching member function for call to
'Get'
names.push_back(array->Get(i)->ToString());
~~~~~~~^~~
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:3717:43: note:
candidate function not viable: requires 2 arguments, but 1 was provided
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
^
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:3720:43: note:
candidate function not viable: requires 2 arguments, but 1 was provided
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:25:
../src/node/node_function.hpp:41:19: error: no member named 'GetCallingContext' in
'v8::Isolate'; did you mean 'GetCurrentContext'?
if (!isolate->GetCallingContext().IsEmpty()) {
^~~~~~~~~~~~~~~~~
GetCurrentContext
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:8825:18: note:
'GetCurrentContext' declared here
Local<Context> GetCurrentContext();
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:26:
../src/node/node_value.hpp:152:28: error: too few arguments to function call,
single argument 'context' was not specified
return value->ToString();
~~~~~~~~~~~~~~~ ^
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:2810:3: note:
'ToString' declared here
V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
^
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8config.h:431:31: note:
expanded from macro 'V8_WARN_UNUSED_RESULT'
#define V8_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:29:
../src/node/node_class.hpp:191:23: error: no member named
'SetNamedPropertyHandler' in 'v8::ObjectTemplate'; did you mean
'SetIndexedPropertyHandler'?
instance_tpl->SetNamedPropertyHandler(string_accessor.getter ? str...
^~~~~~~~~~~~~~~~~~~~~~~
SetIndexedPropertyHandler
/Users/prikshetsharma/Library/Caches/node-gyp/14.15.5/include/node/v8.h:6840:8: note:
'SetIndexedPropertyHandler' declared here
void SetIndexedPropertyHandler(
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:29:
In file included from ../src/node/node_class.hpp:23:
../src/js_class.hpp:92:17: error: no type named 'StringPropertyGetterCallback' in
'realm::node::Types'
typename T::StringPropertyGetterCallback getter;
~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
../src/node/node_class.hpp:368:16: note: in instantiation of template class
'realm::js::StringPropertyType<realm::node::Types>' requested here
template<node::StringPropertyType::GetterType F>
^
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:29:
In file included from ../src/node/node_class.hpp:23:
../src/js_class.hpp:93:17: error: no type named 'StringPropertySetterCallback' in
'realm::node::Types'
typename T::StringPropertySetterCallback setter;
~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from ../src/node/node_init.cpp:19:
In file included from ../src/node/node_init.hpp:29:
../src/node/node_class.hpp:373:10: error: called object type 'int' is not a
function or function pointer
F(isolate, info.This(), property, return_value);
~^
16 errors generated.
make: *** [Release/obj.target/realm/src/node/node_init.o] Error 1
For some reason during the installation I'm getting these 16 errors.
For some reason during the installation I'm getting these 16 errors.
For some reason during the installation I'm getting these 16 errors.
For some reason during the installation I'm getting these 16 errors.
How to fix this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66713040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: The dataframe with only 1 row can't display 3D bar whereas dataframe with more than one rows can display 3D bars I am trying to produce 3d barchart with highcharter with z-axis label and x-axis label showing.
But when my dataframe has only one row the chart doesnot display the bars. If the dataframe consist of more than one row it displays properly.
I want to be able to display 1 row from the dataframe also in the chart.
Below is a reproducible example:
library(shiny)
library(highcharter)
shinyApp(
ui <- fluidPage(
fluidRow(
highchartOutput('chart')
)
),
server <- function(input, output, session) {
df <- data.frame(
Z1 = c(1, 2, 1, 4),
Z2 = c(2, 3, 2, 7),
Z3 = c(6, 3, 7, 4),
Z4 = c(3, 4, 1, 5)
)
df <- df[-(1:3),] #reduced dataframe to 1 row
dta <- lapply(seq(ncol(df)), function(x) {
list(
name = colnames(df)[x],
data = df[, x]
)
})
output$chart <- renderHighchart({
highchart() %>%
hc_chart(
type = "column",
options3d = list(
enabled = TRUE,
beta = 20,
alpha = 30,
depth = 400,
viewDistance = 10
)
) %>%
hc_xAxis(categories = row.names(df[1:nrow(df)-1,])) %>%
hc_zAxis(
min = 0,
max = 3,
categories = colnames(df)
) %>%
hc_plotOptions(
series = list(
depth = 100,
grouping = FALSE,
groupZpadding = 10
)
) %>%
hc_add_series_list(dta)
})
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65574402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to whitelist good bots in fail2ban We have a server running nginx and wordpress. Access logs have been disabled to reduce disk I/O and increase performance. I have enabled custom logs for multiple specific uri which logs host date/time method and uri into a specific files. For some uri like /phpmyadmin or /xmlrpc.php I am directly banning the IP the moment server receives a request. Now I want to white-list known search engines like AOL.com Baidu Bingbot/MSN DuckDuckGo Googlebot Teoma Yahoo! and Yandex. I know how to white-list an IP, but have no idea how to while-list a whole lot of spiders.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37250086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: $this->Session->setFlash displays in wrong timings I am using $this->Session->setFlash to flash the error messages to the browser and its working fine.
But, unfortunately, it is displaying the messages when it shouldn't display also. It is seems like, its getting the information's from cache and displaying.
A: The flash messages are stored in the user's session. If a user opens up two browser windows. And performs some action on one window that causes a flash, but the user reloads a page in the second browser before the first one redirects the second one will show the flash.
With that said does that sound like your issue? Does it show the flash twice? Please elaborate and be more specific as to when 'it displays when it shouldn't'.
A: Maybe the layout of the page where you want the flash message to show doesn't print flash messages and then it shows up in the layout where you print the flash message
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2739910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: want to create a call now button for my website I a not a super coder, but willing to learn as well.
What I am trying to do is create the same function as : http://callnowbutton.com/ (this is a wordpress plugin) and we do NOT use wordpress.
So how would I go about creating this ? The main items are: of course only needs to show on a mobile device, and you want the button to stay at bottom of device screen, even if page is scrolled.
(so a persons thumb or finger can always access it)
Any assistance would be greatly appreciated.
A: You should be able to simply put your number to call in the href attribute of your a element and precede it with 'tel:as a protocol indicator. If you want to make it stick to the bottom of your page, use thefixed` position CSS style. For example:
<style>
a.phoneMe {
position: fixed;
right: 0px;
bottom: 0px;
left: 0px;
height: 30px;
background: green;
color: white;
}
</style>
<a href="tel:1234567890" class="phoneMe">Call Now!</a>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34551701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: What is the difference between preview size and picture size of android camera In an app which uses the camera, where I need to show the preview of the camera, I can set the preview size by getting all supported preview sizes and find the best one. Should I also set best picture size for the camera? If so what is the difference between preview size and picture size?
And currently I use the below to find the best preview size
int minDiff = Integer.MAX_VALUE;
for (SizePair sizePair : validPreviewSizes) {
Size size = sizePair.previewSize();
int diff =
Math.abs(size.getWidth() - desiredWidth) + Math.abs(size.getHeight() - desiredHeight);
if (diff < minDiff) {
selectedPair = sizePair;
minDiff = diff;
}
}
Using this method gives wrong preview sizes in some phones. Can someone suggest a better logic to get best preivew size?
A: Lalit explained the difference between picture size and preview size on camera. You can try this method to get the most optimal size related to the screen size of the device.
private Camera.Size getOptimalSize(Camera.Parameters params, int w, int h) {
final double ASPECT_TH = .2; // Threshold between camera supported ratio and screen ratio.
double minDiff = Double.MAX_VALUE; // Threshold of difference between screen height and camera supported height.
double targetRatio = 0;
int targetHeight = h;
double ratio;
Camera.Size optimalSize = null;
// check if the orientation is portrait or landscape to change aspect ratio.
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
targetRatio = (double) h / (double) w;
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
targetRatio = (double) w / (double) h;
}
// loop through all supported preview sizes to set best display ratio.
for (Camera.Size s : params.getSupportedPreviewSizes()) {
ratio = (double) s.width / (double) s.height;
if (Math.abs(ratio - targetRatio) <= ASPECT_TH) {
if (Math.abs(targetHeight - s.height) < minDiff) {
optimalSize = s;
minDiff = Math.abs(targetHeight - s.height);
}
}
}
return optimalSize;
}
A: Picture size This is the size of the image produced when you tell the camera to take a photo. If it is the same aspect ratio as the native resolution then it will be directly scaled from that. If the aspect ratio is different then it will be cropped from the native size. In my experience, the largest size returned by getSupportedPictureSizes is the native resolution of the camera.
Preview size This is the size of the image preview that is shown on-screen. It may be a different aspect ratio than either the native size or the picture size, causing further cropping
To get the closest match between what you see on screen and the image that is produced when you take a photo try to select a preview size with an aspect ratio as close as possible to the aspect ratio of the picture size that you've selected. I generally try to get both as close as possible to the native size.
please also check this link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42105087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: VBA Error handling, identifying the point of failure I have a couple of functions in VBA that run a series of queries in Access to download data from various sharepoints, manipulate it and then delete some data from SP, move data between SPs and finally upload new data. (it compiles data from various SP, and then because we have a 5k row limit on our SPs, moves historical versions of the result to archive SP, result is 1500 rows so archive has 3 old versions, and uploads new version). When it is run it quite often fails and my error handling reports that file is read only, I presume NW issues with SP connection and stops, but I cannot tell which step has failed. I need to restart but only from the step that failed so as to not lose a historical data set from the archive. In my shortest Fn I just inc a variable after each query and report this with the error so I can see. But my longest Fn has 100's of queries, and I really don't want to have to go through line by line and add a variable count. Is there a way of getting the error messge to include the query name that failed. My short function with variable included is below.
Function Export_to_sp()
On Error GoTo Export_to_sp_Err
Dim progress As Integer
DoCmd.SetWarnings False
DoCmd.OpenQuery "6-delete_C", acViewNormal, acEdit
Let Progress = 1
DoCmd.OpenQuery "6-rename_B_to_C", acViewNormal, acEdit
Let Progress = 2
DoCmd.OpenQuery "6-rename_A_to_B", acViewNormal, acEdit
Let Progress = 3
DoCmd.OpenQuery "6-rename_Active_to_A", acViewNormal, acEdit
Let Progress = 4
DoCmd.OpenQuery "6- export_to_Sp", acViewNormal, acEdit
Let Progress = 5
DoCmd.OpenQuery "6- move_A_to_backup", acViewNormal, acEdit
Let Progress = 6
DoCmd.OpenQuery "6-delete_A", acViewNormal, acEdit
Let Progress = 7
DoCmd.OpenQuery "upload_size_tracker_to_SP_new", acViewNormal, acEdit
Let Progress = 8
DoCmd.OpenQuery "Clear_old_for_current_SP"
Let Progress = 9
DoCmd.OpenQuery "3_open_op", acViewNormal, acEdit
Let Progress = 10
DoCmd.OpenQuery "export change log to new sp", acViewNormal, acEdit
Let Progress = 11
DoCmd.OpenQuery "clear_sp_table_size", acViewNormal, acEdit
Let Progress = 12
DoCmd.OpenQuery "count_local_std_res", acViewNormal, acEdit
Let Progress = 13
DoCmd.OpenQuery "count_local_res", acViewNormal, acEdit
Let Progress = 14
DoCmd.OpenQuery "count_sp_std_res", acViewNormal, acEdit
Let Progress = 15
DoCmd.OpenQuery "count_sp_ol_res", acViewNormal, acEdit
Let Progress = 16
DoCmd.OpenQuery "count_sp_backup_ol_result", acViewNormal, acEdit
Let Progress = 17
DoCmd.OpenQuery "count_audit_log", acViewNormal, acEdit
Let Progress = 18
DoCmd.OpenQuery "count_row_tracker", acViewNormal, acEdit
Let Progress = 19
DoCmd.OpenQuery "SP_export_sumary", acViewNormal, acEdit
Let Progress = 10
DoCmd.SetWarnings True
Export_to_sp_Exit:
Exit Function
Export_to_sp_Err:
MsgBox Error$
MsgBox Progress
Resume Export_to_sp_Exit
End Function
A: Just going with your constraints taken at face value, have you considered something like the following... I woudln't recommend this approach, but if nothing else about your situation can be changed, this might work for you... Considering the following requirements
*
*Single-line operations
*Detect failed line
*Be able to restart on-or-around failed line (+/- 1, etc).
Public Sub RunCode(Optional ByVal StartLine As Integer = 0)
On Error GoTo Handle
If StartLine > 0 Then
If StartLine = 10 Then GoTo 10
If StartLine = 20 Then GoTo 20
If StartLine = 30 Then GoTo 30
If StartLine = 40 Then GoTo 40
End If
10: Debug.Print "10"
20: Debug.Print "20"
30: Err.Raise -1, "Jones"
40: Debug.Print "40"
Exit Sub
Handle:
Debug.Print "Handle [" & Erl & "]: " & Error
End Sub
The trick used is the Erl statement from VBA... It's generally not used, because it requires the explicit line numbers, seen above... But, since you ALREADY effectively numbered you lines, it would seem like a better option than what you're currently doing.
Second, if you NEED to restart AT or around the line that failed, you need a goto label anyway... That is, you would have to have a third line on each clause the way you're doing it, so you can do a GoTo to it. That is the only way to restart in the middle of your control structure, as you have it. By combining the line numbering as the labels, you effectively reduce this, hopefully making your life easier in the mid-term (not the long term, since numbering your lines is inherently problematic).
The Erl will give you the line that failed, which can be stored somewhere like either a return value or a Global (or wherever you can store and retrieve it). What you have left is the requirement to restart at the given line. Unfortunately, to the best of my knowledge, you can't simply do GoTo StartLine, as would be the easiest, so, as you see, each line is enumerated twice (but, you already had that, right?).. The function, via Optional parameter, can be effectively re-entered at any given point.
This, then, is the most straight-forward way to accomplish your three goals. With that said, you could consider some other options... For example, you could wrap your call to DoCmd.OpenQuery "...", acViewNormal, acEdit in some function, and attempt to apply some retry-logic on the same... That is,
Public Function RetryMyQuery(ByVal Query As String) As Boolean
Const MaxRetries As Long = 5
DoRetry:
On Error Goto QueryFailed
Dim FailureCount as Long
DoCmd.OpenQuery Query, acViewNormal, acEdit
RetryMyQuery = True
Exit Function
QueryFailed:
FailureCount = FailureCount + 1
If FailureCount >= MaxRetries Then Exit Function
If MsgBox("Query Failed [" & Query & "]: " & Err.Description, vbRetryCancel, "Query Failed") = vbRetry Then Resume DoRetry
End Function
Each line in the main function would simply call this function with the query name:
If Not RetryMyQuery("SP_export_sumary") Then MyErrorLine = 19
What this is doing is attempting to retry each operation up to 5 times (configurable), with a message box between each retry to force the user to interact. They can double-check the connection, re-open anything as needed, and try again, or, simply cancel the operation.
The stub function encapsulates the retries and returns True on success, so in the main loop, you can still detect the error, and even record the line that failed, if desired. However, again, if you NEED to re-enter the control logic at any given point, you likely need something like solution #1. Other alternatives to this would be to put the list of operations in some kind of String Array and loop through them, and then you're not re-entering hard-coded logic lines, you just start at an arbitrary point in the list. It depends on your needs.
Hopefully something in this would be of assistance. It is not always possible to change a lot of the control structures on existing code, and while I wouldn't ever set out and design something like the first example, if you merely need to modify what's there, a down-and-dirty way is sometimes the best. Just remember, maintaining line numbers is terrible. BASIC (Before VB or VBA, or even QuickBasic) had line numbers and always had this problem. They aren't used any more for a reason. It should be considered a last resort, but, if it gets things up and going, I've done worse.
NOTE: It may also be helpful to point out that GoTo Labels are only scoped to the current function. Pre-pending the name of the function (Export_to_sp_Err:) only results in more characters being typed, and never being able to remember what the handler is named by the time you get to the end of a long function. Just a tip!
A: The classic way of doing this is to avoid the very limited old scool way of dealing with errors and instead implement a Tryxxx function. The Role of the TryXXX function is to return True of False to indicate the success or fail of an action. One of the parameters (usually the last) is declared as ByRef so that the result of the action can be passed back via the parameter.
I'd also restructure how you provide the strings for the queries so that you separate them from the code that does the querying
XXXQuery is the name of the query for which you have the sequence of query statments.
SOmething along these lines
Public Sub DoXXXQuery(ByRef ipQuerySeq As Collection)
Dim myItem As Variant
For Each myItem In ipQuerySeq
Dim myResult as Variant 'as an example
If Not TryDoQuery(myItem, acviewnormal, acedit, myresult) Then
MsgBox "Query execution stopped unexpectedly at '" & myItem & "'"
'put code here for action after failure
End If
Next
End Sub
' ipViewNormal, ipEdit, and opResult are variants as the OP
' doesn't provide enough information to define more appropriately
Public Function TryDoQuery(ByVal ipCommand As String, ByVal ipViewNormal, ByVal ipEdit, ByVal opResult As Variant) As Boolean
TryDoQuery = False
On Error Resume Next
DoCmd.OpenQuery ipCommand, ipViewNormal, ipEdit
If Err.Number <> 0 Then
Err.Clear
Exit Function
End If
err.clear
opResult = ????? ' its not clear what the result of the query is
TryDoQuery = True
End Function
Public Function GetXXXQuerySeq() As Collection
Dim myC As Collection
Set myC = New Collection
With myC
.Add "6-delete_C", acviewnormal, acedit
.Add "6-rename_B_to_C"
.Add "6-rename_A_to_B"
.Add "6-rename_Active_to_A"
.Add "6- export_to_Sp"
.Add "6- move_A_to_backup"
.Add "6-delete_A"
.Add "upload_size_tracker_to_SP_new"
.Add "Clear_old_for_current_SP"
.Add "3_open_op"
.Add "export change log to new sp"
.Add "clear_sp_table_size"
.Add "count_local_std_res"
.Add "count_local_res"
.Add "count_sp_std_res"
.Add "count_sp_ol_res"
.Add "count_sp_backup_ol_result"
.Add "count_audit_log"
.Add "count_row_tracker"
.Add "SP_export_sumary"
End With
Set GetXXXQuerySeq = myC
End Function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71308840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# setting derived property from base I can't seem to call the setter of an overridden property in a derived class from the base class. This seems like something that one should be able to do, but I am clearly missing something. In the DisplayQuestion method of the SearchSurveyBase class below, this line does not appear to do any setting:
VisibleQuestions.Add(sqc.SurveyQuestion.ID);
VisibleQuestions is an abstract List that is being overridden in a derived class. The getters seem to work fine from the base; I can see them being hit on the derived class when debugging. However, the setter does not appear to be working at all. The getter is called fine, but the setter never sets. What am I missing here? Is there a better way to do this?
Base Class:
public abstract class SearchSurveyBase : System.Web.UI.UserControl
{
public abstract List<int> VisibleQuestions { get; set; }
public abstract void SetupControls();
protected void AddQuestion(Accordion accSection, Question question)
{
SearchQuestionControl searchQuestionControl = GetQuestionControl(question.ControlType);
if (searchQuestionControl != null)
{
//QuestionVisible is a method that checks to see if the object's id is in the VisibleQuestions list
searchQuestionControl.Visible = QuestionVisible(question);
if (!searchQuestionControl.Visible)
{
string btnID = "lb_" + accSection.ID.ToString() + "_" + accSection.Panes.Count;
LinkButton btn = new LinkButton();
btn.ID = btnID;
btn.Text = question.Text;
btn.CommandArgument = questionPane.ID;
btn.Command += new CommandEventHandler(DisplayQuestion);
questionPane.HeaderContainer.Controls.Add(btn);
}
questionPane.ContentContainer.Controls.Add(searchQuestionControl);
searchQuestionControlList.Add(searchQuestionControl);
}
accSection.Panes.Add(questionPane);
}
private void DisplayQuestion(object sender, CommandEventArgs e)
{
SearchQuestionControl sqc = null;
AccordionPane pane = (AccordionPane)UIUtilities.FindControlRecursive(RootControl, e.CommandArgument.ToString());
if (pane != null && pane.ContentContainer.HasControls() && pane.ContentContainer.Controls[0] is SearchQuestionControl)
{
sqc = (SearchQuestionControl)pane.ContentContainer.Controls[0];
}
if (sqc != null)
{
if (!sqc.Visible)
{
//Removed a bunch of lines that aren't relevant to the question per request.
VisibleQuestions.Add(sqc.SurveyQuestion.ID);
}
}
}
}
Derived Class:
public partial class SearchSurveyAccordion : SearchSurveyBase
{
override public List<int> VisibleQuestions
{
get
{
// hfVisibleQuestions is a HiddenField control on the .ascx page that inherits this class.
if (!string.IsNullOrWhiteSpace(hfVisibleQuestions.Value))
{
string[] vals = hfVisibleQuestions.Value.Split(',');
List<int> vqs = new List<int>(Array.ConvertAll<string, int>(vals, (x => Convert.ToInt32(x))));
return vqs;
}
else
{
return new List<int>();
}
}
set
{
hfVisibleQuestions.Value = string.Join(",", value.Select(n => n.ToString()).ToArray());
}
}
// This method is called during the Page_Init of the page that is consuming this user control.
override public void SetupControls()
{
if (base.survey != null && base.survey.QuestionList != null && base.survey.QuestionList.Count > 0)
{
BuildAccordion(base.survey.QuestionList);
}
}
private void BuildAccordion(List<Question> questionList)
{
Accordion accSection = null;
foreach (Question question in questionList)
{
accSection = base.AddSection(accSurvey, defaultSectionHeader);
AddQuestion(accSection, question);
}
}
}
TL;DR? Here's the short version of the problem.
I have a base class and a derived class. I want a method in the base class to be able to set the value of an abstract property that is overridden in the derived class but it isn't working for me.
A: If you are expecting the following statment to call the setter for VisibleQuestions, then you are mistaken:
VisibleQuestions.Add(sqc.SurveyQuestion.ID);
This statement calls the Add method on the List<int> instance returned by the VisibleQuestions getter.
Utilizing the setter would happen if you assigned a value to VisibleQuestions, like so:
VisibleQuestions = new List<int>();
A: You are not calling the setter on that line. You are calling the getter that returns a list to which you add an element. However next time you access the same getter you create a new list (without the added element) which you return anew
A: From MSDN - Using Properties (C# Programming Guide) - The set Accessor:
When you assign a value to the property, the set accessor is invoked
by using an argument that provides the new value.
The setter is only called if you actually set your property's value. In your case, you are calling your getter, which returns a new list, based on the value of the underlying field. If you want to then update that underlying field after you update the list, you will need to then set the value of the property to your updated list, like so:
// Calls the getter and returns a new list
List<string> questions = VisibleQuestions;
// Updates the list, but does not trigger the setter
questions.Add(sqc.SurveyQuestion.ID);
// Calls the setter
VisibleQuestions = questions;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11020632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Editing Multiple Records - Granting Access to All Logged-In Users As far as I can tell, this is a views and controller problem.
I need to allow users to edit multiple records in one of my database tables. Railscast 165 deals with a similar situation, but it's not quite on point for me: http://railscasts.com/episodes/165-edit-multiple
I have a fixed set of products, and I need to let users add associated varieties to those products. I've considered the easier solution of requiring the user to go to a product page, and edit one individual product at a time, but that won't work for my app. Instead, I need to provide more of an admin style functionality for this one task.
The model relationship here is simple. A product has_many varieties, and variety belongs_to product. In my user interface, I simply let the user select a product from a dropdown menu containing all of the available products on the site, and then the user can type the name of a variety in a text input. For example, if we're talking about apples, then the user can select apples from the product dropdown, and he might type in "fuji" and a variety. I simply need to save the product_id and the variety[name] to the varieties table. However, I need to do this for multiple records at one time.
Currently, I've got the form rendering with the dropdown displaying the right product choices. The problem seems to be that the variety input is rendering in html like this:
<label for="nil_class_variety">Variety</label>
<input id="nil_class_name" name="nil_class[name]" size="30" type="text" />
To render parts of the form, I'm following the Advanced Rails Recipes multi-model form technique (i.e. the Ryan Bates way). I spent about 10 hours trying to do this and it seems that I'm now very close, but I don't know what the problem is at this point.
Here's my setup:
Products Controller
def edit_multiple
@products = Product.find(:all)
end
def update_multiple
params[:product][:existing_variety_attributes] ||= {}
@products = Product.find(:all)
if @products.each do |product|
product.update_attributes!(params[:product].reject { |k,v| v.blank? })
end
flash[:notice] = "Updated products!"
redirect_to edit_user_path(self.current_user)
else
render :action => 'edit'
flash[:error] = "Something went wrong. Please try again."
end
end
Routes.rb # To make the custom controller actions work
map.resources :products, :collection => { :edit_multiple => :get, :update_multiple => :put}
views/products/edit_multiple.html.erb
<%= error_messages_for :product %>
<% form_for :product, :url => update_multiple_products_path, :html => { :method => :put } do |f| %>
<div id="varieties">
<%= render :partial => 'variety' %>
</div>
<p><%= add_variety_link "+ Add another variety" %></p>
<%= f.submit 'Submit Varieties' %>
<%end%>
views/products/_variety.html.erb
Note: For now, I'm not letting the users edit the varieties they submit. So I removed the following line from the Ryan Bates technique because it was throwing an error and I don't think I need it, but I could be wrong: <%# new_or_existing = variety.new_record? ? 'new' : 'existing' %>
Here's what I have in this _variety partial:
<% prefix = "product[new_variety_attributes][]" %>
<% fields_for @variety do |variety_form| -%>
<%= collection_select(:product, :product_id, Product.all, :id, :name, {:prompt => true}) %>
<%= variety_form.label :variety %>
<%= variety_form.text_field :name %>
<%= link_to_function "- Remove Variety", "$(this).up('.variety').remove()" %>
<%end -%>
NOTE: Currently the javascript stuff you see is working. On the edit_multiple view page, I can dynamically add and remove the products/varieties inputs. As I mentioned, the dropdown is also populating properly. So it seems that I just need to get the variety input to render properly and get the controller to properly process it. Thanks for your help!
Update
When I select one product from the dropdown and type a name in the variety input, the submit throws the following error and trace:
ActiveRecord::UnknownAttributeError in ProductsController#update_multiple
unknown attribute: product_id
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.3/lib/active_record/base.rb:2740:in `attributes='
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.3/lib/active_record/base.rb:2736:in `each'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.3/lib/active_record/base.rb:2736:in `attributes='
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.3/lib/active_record/base.rb:2628:in `update_attributes!'
/Users/michael/dev/fresh/app/controllers/products_controller.rb:74:in `update_multiple'
/Users/michael/dev/fresh/app/controllers/products_controller.rb:73:in each'
/Users/michael/dev/fresh/app/controllers/products_controller.rb:73:inupdate_multiple'
The log shows the correct product_id and the correct name I entered, but you can see it's calling a nil class:
Processing ProductsController#update_multiple (for 127.0.0.1 at 2009-10-08 07:31:05) [PUT]
Parameters: {"commit"=>"Submit Varieties", "authenticity_token"=>"zzkveSe7qzv2NY8WPrR2cYS376u6DBiz8Vc9iNFLQy8=", "product"=>{"product_id"=>"5"}, "nil_class"=>{"name"=>"yellow"}}
When I try to enter more than one product/variety record, the log isn't recognizing anything except the first one. I get the same result as when I type in just one product/variety record.
A: The short answer to your problem, is that @variety is undefined in the fields_for @variety. The correct version of that line in /app/views/products/_variety.html.erb is
<% fields_for :variety do |variety_form| -%>
Also there's a minor nitpick in your label line.
<%= variety_form.label :variety %>
should be
<%= variety_form.label :name, "Variety" %>
I can't tell if your goal is to update multiple products and varieties at once or just update a single product's varieties. Assuming the latter, you should be using accepts_nested_attributes_for (scroll down to the Nested Attributes Example), seems like it might be an easier way to do it. Also see the github Complex-Forms-Example repository for a working demonstration.
But this doesn't seem to be the case. It looks to me that your javascript functions are adding form/removing values for product and varieties.
This will work in the controller for adding varieties, but needs a little more work for removing existing varieties. But the railscasts you linked to provides all the information you need to put that together.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1537291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring Boot Too Many Redirects I'm developing a simple login Form using a Thymeleaf & Spring Boot. When i try hitting the following URL in Chrome: "http://localhost:8080/login" i get an error saying "ERR_TOO_MANY_REDIRECTS". I've tried clearing my cache & cookies in the browser and still get the same error.
I tried disabling the default security login screen by putting the following property into my application.properties: security.basic.enabled=false
and added the following configuration to my SecurityConfig so any URL except "/login" and "/resources" would get authenticated:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserRepository userRepository;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
My LoginController is strightforward:
@Controller
public class LoginController {
@RequestMapping(value="/login", method=RequestMethod.GET)
public String loadForm(Model model) {
model.addAttribute("user", new User());
return "redirect:/login";
}
Anyone have any idea's why this happens?
A: Your Controller catches and redirects to the same url:
@RequestMapping(value="/login", method=RequestMethod.GET)
public String loadForm(Model model) {
model.addAttribute("user", new User());
return "redirect:/login";
}
Also, your SecurityConfig defines this:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
...
.loginPage("/login")
}
.loginPage()'s javadoc says this:
login page to redirect to if authentication is required
So, any secured request made or direct access to /login will:
*
*redirect to /login because of .loginPage("/login") in your SecurityConfig
*which you then catch with @RequestMapping(value="/login"
*then redirect to /login with "redirect:/login"
*then re-catch and redirect at will.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39310634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Is there a possibility to get a notification when a file on FTP server has been modified? I'd like to build a service where a file from a FTP Server is downloaded as soon as it has been modified. It's always the same file name. I think of checking for the timestamp every few minutes but maybe there is a more elegant way to solve that?
A: Checking timestamp (or something very similar) is the only way you can do it with a generic the FTP protocol API.
Your particular FTP server may have better API for that, but we do not know anything about your FTP server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60309852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Does MOXy have an analog of Jackson's @JsonIgnore tag? In a JAX-RS (Jersey) application, I have a Java class whose instances can be both stored in a SQL database (using OpenJPA) and sent over the wire as JSON text (in a RESTful application). This class has a a field that has a setter and getter (for use with OpenJPA), but which I don't want to be converted to JSON. I know that if I were using Jackson for the Java-object-to-JSON conversion in Jersey, I could use the the @JsonIgnore tag to achieve this purpose, viz.
// This is the main class sent in REST responses; inside a Parent description, a number of
// Child instances are described
@XmlRootElement(name = "parent")
@Entity
public class Parent {
...
@OneToMany(
mappedBy="parent", cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.EAGER)
private Vector<Child> children = new Vector<>();
...
}
@Entity
public class Child implements Serializable {
...
// Don't want to serialize Parent, to avoid an infinite loop!
@JsonIgnore
@ManyToOne(fetch = FetchType.EAGER)
private Parent parent;
public Parent getParent() { return parent; }
public void setParent(Parent _parent) { parent = _parent; }
...
}
However, my Jersey setup uses the "default" JSON conversion tool, which is MOXy rather than Jackson (as per https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/index.html , sec. 9.1). So this setup does not have the @JsonIgnore tag. Is there an analogous tag in the Jersey + MOXy framework? I thought @XmlTransient may do the trick, but it does not.
As a practical solution, I simply renamed getParent() to xgetParent(); apparently OpenJPA is not affected, but MOXy does not try to convert this field anymore. But that's a ridiculously kludgy solution of course, and is bound to break something eventually.
A: @XmlTransient works, but with getter. I tested it with EclipseLink/MOXy 2.7.7.
So try
@XmlTransient
public Parent getParent() { return parent; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62749866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unity Visual Studio 2017 Freeze and Crash I work with Unity, and recently I came across some sort of bug with Visual Studio. For some reason one day the Script Editor stopped working.
When I first open it up through Unity, it would open as usual and seem fine, but after 5 seconds of interaction, Visual Studio would then freeze and crash without an error report. Following tries with the editor would just crash almost right away.
I did some research and found out that it was some sort of problem with Unity's MEF Cache, the Microsoft Documentation would ask me to do the following: Delete the following file: "%localappdata%\Microsoft\VisualStudio<version>\ComponentModelCache" and if the problem continues, I should run this line of code on VS' CMD as a administrator "devenv /setup".
I tried both methods with Visual Studio, but neither seemed to work, only to return to being fine for 5 seconds before freezing and crashing.
I have updated Visual Studio 2017 to the newer version and performed the same method, but the problem persists.
I would like to know if anyone have any solutions to my situation, if I should try reinstalling Visual Studio, try to reinstall Unity or just use another Script Editor.
edit: Just to inform, the version of Unity I was using was 2021.2.8f1. But I don't know if it matters since the bug didn't seem to depend on the Unity version.
A: I managed to fix the issue by installing Visual Studio 2022
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70715245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Iterate through elements in html tree using BeautifulSoup, and produce an output that maintains the relative position of each element? in Python I have this code that does what I need it to do using Jsoup in Java
Elements htmlTree = doc.body().select("*");
Elements menuElements = new Elements();
for(Element element : htmlTree) {
if(element.hasClass("header"))
menuElements.add(element);
if(element.hasClass("name"))
menuElements.add(element);
if(element.hasClass("quantity"))
menuElements.add(element);
}
I want to do the same thing but in Python using BeautifulSoup. An example tree of the HTML I'm trying to scrape follows:
<div class="header"> content </div>
<div class="name"> content </div>
<div class="quantity"> content </div>
<div class="name"> content </div>
<div class="quantity"> content </div>
<div class="header"> content2 </div>
<div class="name"> content2 </div>
<div class="quantity"> content2 </div>
<div class="name"> content2 </div>
<div class="quantity"> content2 </div>
etc.
Basically I want the output to preserve the relative positions of each element. How would I got about doing that using Python and BeautifulSoup?
EDIT:
This is the python code I have (it's very naive) but maybe it can help?
output = []
for e in soup :
if e["class"] == "pickmenucolmenucat" :
output.append(e)
if e["class"] == "pickmenucoldispname" :
output.append(e)
if e["class"] == "pickmenucolportions" :
output.append(e)
A: To find all <div> elements that have class attribute from a given list:
#!/usr/bin/env python
from bs4 import BeautifulSoup # $ pip install beautifulsoup4
with open('input.xml', 'rb') as file:
soup = BeautifulSoup(file)
elements = soup.find_all("div", class_="header name quantity".split())
print("\n".join("{} {}".format(el['class'], el.get_text()) for el in elements))
Output
['header'] content
['name'] content
['quantity'] content
['name'] content
['quantity'] content
['header'] content2
['name'] content2
['quantity'] content2
['name'] content2
['quantity'] content2
There are also other methods that allows you to search, traverse html elements.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13736554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Apache POI SAX Parsing - How to get actual value of the cell I had a requirement to parser very large excel files using apache poi with limit memory. After googling, I came to know that poi provides SAX parser to parser large file effectively without consuming lot of memory.
Apache POI SAX Parser example
private class SheetToCSV implements SheetContentsHandler {
private boolean firstCellOfRow = false;
private int currentRow = -1;
private int currentCol = -1;
private void outputMissingRows(int number) {
for (int i=0; i<number; i++) {
for (int j=0; j<minColumns; j++) {
output.append(',');
}
output.append('\n');
}
}
@Override
public void startRow(int rowNum) {
// If there were gaps, output the missing rows
outputMissingRows(rowNum-currentRow-1);
// Prepare for this row
firstCellOfRow = true;
currentRow = rowNum;
currentCol = -1;
}
@Override
public void endRow(int rowNum) {
// Ensure the minimum number of columns
for (int i=currentCol; i<minColumns; i++) {
output.append(',');
}
output.append('\n');
}
@Override
public void cell(String cellReference, String formattedValue,
XSSFComment comment) {
if (firstCellOfRow) {
firstCellOfRow = false;
} else {
output.append(',');
}
// gracefully handle missing CellRef here in a similar way as XSSFCell does
if(cellReference == null) {
cellReference = new CellAddress(currentRow, currentCol).formatAsString();
}
// Did we miss any cells?
int thisCol = (new CellReference(cellReference)).getCol();
int missedCols = thisCol - currentCol - 1;
for (int i=0; i<missedCols; i++) {
output.append(',');
}
currentCol = thisCol;
// Number or string?
try {
Double.parseDouble(formattedValue);
output.append(formattedValue);
} catch (NumberFormatException e) {
output.append('"');
output.append(formattedValue);
output.append('"');
}
}
@Override
public void headerFooter(String text, boolean isHeader, String tagName) {
// Skip, no headers or footers in CSV
}
}
In the example provided in the above link, the method 'cell' has access only to formatted value however I need to access the actual value of the cell.
A: The current implementation of the streaming interface does not provide this. So in order to achieve this you will need to copy the code of the underlying XSSFSheetXMLHandler and adjust it so that the cell-content is not formatted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40886142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Remove backslashes "\" from title from csv file in php mysql I am working on a script that export data from mysql in csv file. Its work perfectly.
When I enter title of the song with apostrophes from admin panel like test'123' the data save in database like this test\'123\'.
Now when I export the data into csv file, the title save as it is with backslashes '\' like this:
Now I want that when I export the data from database into csv file the back slashes will remove only from csv file, not from the database.
Here is my code to exprot data:
$query = "SELECT plist.playlist_id, plist.playlist_name, plist.playlist_shortcode, psong.song_id, psong.list_order,
psong.song_playlist, psong.mp3, psong.ogg, psong.title, psong.buy, psong.buyy, psong.buyyy, psong.price, psong.cover,
psong.artist
FROM " . $pre . "hmp_songs As psong
LEFT JOIN " . $pre . "hmp_playlists As plist
On plist.playlist_name = psong.song_playlist
Where plist.playlist_id IS NOT NULL
And plist.playlist_name IS NOT NULL
And plist.playlist_shortcode IS NOT NULL
And psong.song_id IS NOT NULL
And psong.list_order IS NOT NULL
And psong.song_playlist IS NOT NULL
And psong.mp3 IS NOT NULL
And psong.ogg IS NOT NULL
And psong.title IS NOT NULL
And psong.buy IS NOT NULL
And psong.buyy IS NOT NULL
And psong.buyyy IS NOT NULL
And psong.price IS NOT NULL
And psong.cover IS NOT NULL
And psong.artist IS NOT NULL";
$result = mysqli_query($link,$query) or die("Error executing query: ".mysqli_error());
$row = mysqli_fetch_assoc($result);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
$out = $line;
mysqli_data_seek($result, 0);
while($row = mysqli_fetch_assoc($result)){
$line = "";
$comma = "";
foreach($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
$out .= $line;
}
$csv_file_name = 'HMP_'.date('Ymd_His').'.csv'; # CSV FILE NAME WILL BE table_name_yyyymmdd_hhmmss.csv
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=".$csv_file_name);
header("Content-Description:File Transfer");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Type: application/octet-stream');
echo __($out,"hmp");
exit;
How can I do this because I have no idea. Thanks
A: PHP function stripslashes will work for you.
Example:
<?php
$str = "Is your name O\'reilly?";
echo stripslashes($str);
?>
Output
Is your name O'reilly?
Usage in your code:
foreach($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', stripslashes($value)) . '"';
$comma = ",";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33751317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Outlook custom script to flag messages with a value less than 40 in the subject field I get thousands of e-mail alerts in my inbox daily, but many of them are actually trivial. I want to check whether the text of these alerts contains numbers below a certain threshold; if the numbers are lower than that threshold, alert me to the message and display a message box.
I'm using Outlook 2010 and have found several tutorials on writing Outlook macros in VB, including one about programmatically creating a rule to move messages to different folders.
But I don't want to check for keywords, I want to check if a number in the message (subject field) text is = to or less than a threshold value. For example, if the text of a message contains the following, id be alerted to it and a message box is displayed:-
The bit I need help with is there any way of writing a code that will only call the message box if the value in the e-mail subject field is below 45kohm?
I can do this in the rule but I’d have to include all values below i.e. 39.99, 39.98, 39.97 and that’s far too long!
A: You could use a VBA macro similar to the following:
Sub SubjectCheckerMessageRule(newMail As Outlook.mailItem)
' "script" routine to be called for incoming mail messages
' This subroutine has to be linked to this mail type using Outlook's rule assistant
Dim EntryID As String
Dim StoreID As Variant
Dim mi As Outlook.mailItem
Dim s As String
Dim x As Double
Const Prefix = "Resistance,"
Const Threshold = 40.0 ' or is it 45.0
' http://www.vboffice.net/en/developers/security-model-part-1/
' In 2003, not 2007 or later
' we have to access the new mail via an application reference
' to avoid security warnings
'
EntryID = newMail.EntryID
StoreID = newMail.Parent.StoreID
Set mi = Application.Session.GetItemFromID(EntryID, StoreID)
If InStr(mi.Subject, Prefix) = 1 Then
s = Mid(mi.Subject, Len(Prefix) + 1)
If IsNumeric(s) Then
x = CDbl(s)
If x <= Threshold Then
MsgBox x & " <= " & Threshold, vbInformation, "Attention!"
End If
End If
End If
End Sub
Use Outlook's Rule Assistant to define this macro as Script for the incoming mails of interest. Define keywords for the subject like "Resistance," to make sure that the macro is only called for the relevant mails. Add some error checking.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35003387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python: Pass a list of IP addresses to geoip2 for location lookup I am looking for a way of analysing a massive list of IP addresses with location data. This list is about 10000000 entries.
For the moment I am using geoip2 module from maxmind. The original code can look for a single IP address entry and print results with a country code as shown below:
import geoip2.database
reader = geoip2.database.Reader('./GeoLite2-Country_20210330/GeoLite2-Country.mmdb')
response = reader.country('80.80.80.80')
print('response.country.iso_code: {}'.format(response.country.iso_code))
reader.close()
I trying to figure out a way of expanding this script to search for more entries at once by iterating through csv file. I wrote a code that does not work as I want to. It seems like Python does not like the way I am passing a list.
import geoip2.database
from csv import reader
import csv
read_db = geoip2.database.Reader('./GeoLite2-Country_20210330/GeoLite2-Country.mmdb')
with open('SrcIP.csv', 'r') as file1:
csv_read = csv.reader(file1, delimiter=' ', quotechar='|')
for row in csv_read:
response = read_db.country(', '.join(row))
print(response) #note 1
print('response.country: {}'.format(read_db.country)) #note 2
Note 1: If I print the response variable directly it searches the database for IP address range and prints all information available for each IP address. As a result, the output becomes too much for each line.
Note 2: This line will limit the output to only country code. However, it returns with error for each row as shown below:
response.country: <bound method Reader.country of <geoip2.database.Reader object at 0x7fe26a752c40>>
A: I think I have managed to resolve my own problem.
I changed the code to:
import geoip2.database
import csv
read_db = geoip2.database.Reader('./GeoLite2-Country_20210330/GeoLite2-Country.mmdb') #read database
with open('SrcIP.csv', 'r') as file1:
csv_read = csv.reader(file1, delimiter=' ', quotechar='|')
for row in csv_read:
response = read_db.country(', '.join(row))
filtered_res = response.country.iso_code
print(filtered_res)
Let me know what do you think. I cross-checked the results with the given IP addresses and the country code seems to be right.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66965638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Input url of photo in textbox and show it at picturebox I would like to ask is there any possible way to input url in textbox and after pressing " submit " button and it will show at picturebox or something else , I've seen it doable in visual studio but not in c# does anyone have any ideas regarding this?
A: You can simply do draw the text using the pictureBox1_Paint event
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
using (Font yourFont = new Font("Arial", 12))
{
if (textBox1.Text != null)
{
string yourtext = textBox1.Text;
e.Graphics.DrawString(yourtext, yourFont, Brushes.Red, new Point(5, 5));
this.Refresh(); //add this in your button click event if you want to perform it on a click event instead.
}
}
}
or, if you want to do this using a button click, then add this line this.Refresh(); on your button_Click event rather than applying directly in your pictureBox1_Paint event.
private void button2_Click(object sender, EventArgs e)
{
this.Refresh();
}
As per your new query...
If you just want to display your image URL in the picturebox by just entering the URL in the textbox on a button click, then try:
private void button1_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
pictureBox1.ImageLocation = str;
}
Alternatively, for displaying the image in the picturebox, use:
private void button1_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
Image img = Image.FromFile(str);
pictureBox1.Image = img;
}
A: On the click event of the submit button add the following code
pictureBox.ImageLocation = textBox.Text;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39199290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: disable past dates on datepicker "without using JQuery UI" How to disable past dates from the current date on a datepicker, without using JQuery UI? I tried few posts for similar question but was unable to achieve it, Below is what I tried
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen"
href="http://tarruda.github.com/bootstrap-datetimepicker/assets/css/bootstrap-datetimepicker.min.css">
<script type="text/javascript"
src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript"
src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/js/bootstrap.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.pt-BR.js">
</script>
<script type="text/javascript">
$(function() {
$('#datetimepicker2').datetimepicker({
language: 'en',
pick12HourFormat: true
});
});
</script>
<div id="datetimepicker2" class="input-append">
<input data-format="MM/dd/yyyy" type="text"/>
<span class="add-on">
<i data-date-icon="icon-calendar">
</i>
</span>
I also tried
$("datetimepicker2").datepicker({ changeYear: true, dateFormat: 'dd/mm/yy', showOn: 'none', showButtonPanel: true, minDate:'0d' });
and
$("#datetimepicker2").datepicker({ minDate: 0 });
A: Problem fixed :)
Below is the working code
$(function(){
$('#datepicker').datepicker({
startDate: '-0m'
//endDate: '+2d'
}).on('changeDate', function(ev){
$('#sDate1').text($('#datepicker').data('date'));
$('#datepicker').datepicker('hide');
});
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15802572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Specific Crosstab I'm facing a problem with some data, so i need to use a crosstab to generate a specific report, could you help me?
Basicaly i have one query select like this:
select route_id,id,tipo,local,valor_cobrado from itinerario
and inside this table i have this data below:
As you can see we have sometimes Coleta and Entrega with the same route_id, so i need to have someting like that:
route_id | id | tipo Coleta | local Coleta | tipo Entrega | local Entrega | sum(valor_cobrado)
Is it possible?
thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72958146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Draw Canvas with video loop I loop over a part of a HTML video and simultaneously draw a Canvas with the current frame of the video.
When the Videos starts over, there is always 1 gray frame at the canvas.
If the loop region is long, its not a big problem, but for my needs these regions are maybe 0.5 seconds and then the canvas starts to flicker if you loop over and over again.
When drawing the canvas, I also tried different video properties (ended, loop, networkState, readyState) - doesnt help
I provided a jsfiddle to show you my problem. (just press play at the video)
https://jsfiddle.net/Lz17fnf3/2/
$('#v').on('timeupdate', function () {
if ($('#v')[0].currentTime > 2) {//Loop for one second
$('#v')[0].currentTime = 1;
}
var $this = $('#v')[0]; //cache
(function loop() {
if (!$this.paused && !$this.ended) {
drawCanvas();
setTimeout(loop, 1000 / 25); // drawing at 25fps
}
})();
});
function drawCanvas() {
var elem = document.getElementById('c');
var c = elem.getContext('2d');
var v = $('#v')[0];
$('#c').attr('width', v.videoWidth);
$('#c').attr('height', v.videoHeight);
if (v.readyState == 4) {
c.drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, v.videoWidth, v.videoHeight);
}
}
A: The reason it flickers is because when you assign the width or height to a canvas element, this action resets the entire context of the canvas, most likely that is causing the blank frame. Try moving all the canvas/context definitions outside the drawCanvas.
Something like:
var elem = document.getElementById('c');
var c = elem.getContext('2d');
var v = $('#v')[0];
// In order to set the canvas width & height, we need to wait for the video to load.
function init() {
if (v.readyState == 4) {
$('#c').attr('width', v.videoWidth);
$('#c').attr('height', v.videoHeight);
} else {
requestAnimationFrame(init);
}
}
init();
$('#v').on('timeupdate', function () {
if ($('#v')[0].currentTime > 2) { //Loop for one second
$('#v')[0].currentTime = 1;
}
var $this = $('#v')[0]; //cache
(function loop() {
if (!$this.paused && !$this.ended) {
drawCanvas();
setTimeout(loop, 1000 / 25); // drawing at 25fps
}
})();
});
function drawCanvas() {
c.drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, v.videoWidth, v.videoHeight);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33914294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PowerShell exit code 1 when selecting text from nuget help output I was trying to make use of the suggestion from this question Get NuGet.exe version from command-line to use the PowerShell command
nuget help | select -First 1
This works and outputs just the line with the version on, which is exactly what I want. But when I try to use it in automation it's a problem because I get an error code from the command even thought it succeeds.
PS C:\> $PSVERSIONTABLE
Name Value
---- -----
PSVersion 5.1.16299.637
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.16299.637
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
PS C:\> nuget help | select -First 1
NuGet Version: 4.8.1.5435
PS C:\> $?
False
PS C:\> $LASTEXITCODE
-1
I can't find a reason for the error code in the PowerShell documentation for the select-object command.
Interestingly, the problem is not present in PowerShell Core 6.1
Can anybody shed some light on why I'd be seeing this error code or an alternative for getting the nuget version in PowerShell?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52869877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Angular 4 Data Binding over ng-repeat I've recently switched to Angular 4 from Angular 1 and lots of things seem to be new to me now. One of them seems to relate to data-binding. In the old version, I would declare an array as $scope.arrname in the JS controller and I could navigate over it in the HTML view using ng-repeat.
Now, when I am trying to achieve the same outcome, it only works partially. What am I doing wrong?
Example: In a component, I declared a test array testarr : any[] = [1,2,3];
{{testarr}}
> Prints 1,2,3 on the scrreen
<ol>
<li ng-repeat="item in testarr">{{item}}ITEM Found!</li>
</ol>
>only iterates 1 time (ignoring the 2,3) in the array.
Why does my code not iterate over the array as it was the case previously
? What am I missing here?
A: You should use ngFor instead of ng-repeat
<ol>
<li *ngFor="let item of testarr">{{item}}ITEM Found!</li>
</ol>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44319853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Exporting Pandas to CSV results in #NAME error in CSV I have a DF that looks like this:
Words
+Beverly +Hills
+Andrea +Johnson
+Football
Exporting this df to a CSV using:
df.to_csv('df.csv', index=False)
However, because each word has a '+' before it, excel is reading these cells as an equation resulting in an #NAME error. I know I can force an ' before the string to have excel read it as plaintext but that results in a leading ' which I do not want.
Suggestions to fix this error on exporting?
A: The DataFrame can be written to an xlsx file with no issues using to_excel and the xlsxwriter engine. Maybe that's good enough. However the same issue as you have experienced occurs after converting the xlsx file to cvs format using Excel.
Here is an example of creating the xlsx file:
import pandas as pd
from pandas import DataFrame
data = {'Words': ['+Beverly +Hills', '+Andrea +Johnson', '+Football']}
df = DataFrame(data)
df
Out[2]:
Words
0 +Beverly +Hills
1 +Andrea +Johnson
2 +Football
writer = pd.ExcelWriter('df.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
# contents of df.xlsx are now
# Words
# 0 +Beverly +Hills
# 1 +Andrea +Johnson
# 2 +Football
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32575345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Project import of old firebase to new firebase console The Google docs say that I should be able to see all my old firebase projects in the new console and then import them.
The problem is that 2 of the projects on the old firebase simply do not show up in the new console and therefore I cannot import them!
The two projects are in fact already using Google Cloud (for authentication) and I see can the projects listed when I click the "Import Google Project" button in the dropwdown. However, in that same dialogue window it says "add firebase to a Google Project", but there is already firebase included in the code for these projects (Android), so I am afraid this will screw things up?
I have a lot of live users on this Android app and trial/error by pressing this is not an option if it screws things up.
Any help?
A: I found the solution myself.
I seems I had the limit of 10 Google Cloud projects (the standard limit I think), and since Firebase actually uses Google Cloud as well, then I had to delete some old Google Cloud projects I did not use anymore.
Then my old firebase projects showed up in the new Firebase console and I could import them into the new console.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38874586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the definition behind `%0 | %0`? Please help me to find the definition behind this code:
%0 | %0
If we save this code in a .bat file and run it our CPU & MEMORY usage will go to 100%.
A: %n is the n-th argument when calling a program or batch file. %0 will be the first parameter or the file name of the executatble/script. Hence %0 will run it's own file, and the copy will again run it's own. This continues forever and cannot exit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23926021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google Chart : Single quote in title The title of my column-chart contain a single quote. It's displayed like this: ' .
I have other specific characters, such as 'é', but they work perfectly.
I tried to URL-encode the text, without result.
Is there something I need to know about Google Visualization and single quotes?
A: Turns out I was wrong about the problem. I'm working in a Rails app, and I'm rendering my charts via Erb templates, with the title as a parameter.
Solution was to pass that parameter like this raw(title_string), so the single quote character is escaped. Issue was about Erb, not Google Chart.
WhiteHat comment helped me realise that, thanks :)
A: Appreciate this is an old question, but as I too have had this issue, with title and column values I pop in my solution.
If your title is
title: 'my title's great'
then you need to escape the ' in the title with a backslash \ . It becomes
title: 'my title\'s great'
If your title is
title: "my title's "great""
then you need to escape the " in the title with a backslash \ . It becomes
title: "my title's \"great\"".
What I have started to do is put \ before all specials. Some systems may need to you to use double backslash in your code for the single backslash to make it to the google chart.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36553946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Limit not working when testing Dynamic SOQL I am running a Dynamic SOQL query in my apex test code, and the LIMIT clause is not working. It does however seem to work when using it in the production code.
The Query is similar to below. I dynamically build up the where clause using some terms from a form.
string query = 'SELECT name, billingstreet, billingpostalcode, phone ';
query += 'FROM Account WHERE ';
query += '(name LIKE \'%limited%\' OR name LIKE \'%LIMITED%\') ';
query += 'LIMIT 500';
List<Account> results = Database.query(query);
System.assert(results.size() <= 500);
This can fail as the query seems to return well over 500 records in the test. The query does work however when using this in a visual force page.
Any thoughts?
A: I tested dynamic SOQL in the test method with a limit clause and it worked fine without any issues.
I suggest you to put some system.debug prior to assertion to check the size of the accounts list returned.
Hope this way you will come to know whats happening.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3998037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What exactly does "import *" import? In Python, what exactly does import * import? Does it import __init__.py found in the containing folder?
For example, is it necessary to declare from project.model import __init__, or is from project.model import * sufficient?
A: The "advantage" of from xyz import * as opposed to other forms of import is that it imports everything (well, almost... [see (a) below] everything) from the designated module under the current module. This allows using the various objects (variables, classes, methods...) from the imported module without prefixing them with the module's name. For example
>>> from math import *
>>>pi
3.141592653589793
>>>sin(pi/2)
>>>1.0
This practice (of importing * into the current namespace) is however discouraged because it
*
*provides the opportunity for namespace collisions (say if you had a variable name pi prior to the import)
*may be inefficient, if the number of objects imported is big
*doesn't explicitly document the origin of the variable/method/class (it is nice to have this "self documentation" of the program for future visit into the code)
Typically we therefore limit this import * practice to ad-hoc tests and the like. As pointed out by @Denilson-Sá-Maia, some libraries such as (e.g. pygame) have a sub-module where all the most commonly used constants and functions are defined and such sub-modules are effectively designed to be imported with import *. Other than with these special sub-modules, it is otherwise preferable to ...:
explicitly import a few objects only
>>>from math import pi
>>>pi
>>>3.141592653589793
>>> sin(pi/2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined
or import the module under its own namespace (or an alias thereof, in particular if this is a long name, and the program references its objects many times)
>>>import math
>>>math.pi
>>>3.141592653589793
etc..
>>>import math as m #bad example math being so short and standard...
>>>m.pi
>>>3.141592653589793
etc..
See the Python documentation on this topic
(a) Specifically, what gets imported with from xyz import * ?
if xyz module defines an __all__ variable, it will import all the names defined in this sequence, otherwise it will import all names, except these which start with an underscore.
Note Many libraries have sub-modules. For example the standard library urllib includes sub-modules like urllib.request, urllib.errors, urllib.response etc. A common point of confusion is that
from urllib import *
would import all these sub-modules. That is NOT the case: one needs to explicitly imports these separately with, say, from urllib.request import * etc. This incidentally is not specific to import *, plain import will not import sub-modules either (but of course, the * which is often a shorthand for "everything" may mislead people in thinking that all sub-modules and everything else would be imported).
A: Yes, it does. It imports everything (that is not a private variable, i.e.: variables whose names start with _ or __), and you should try not to use it according to "Properly importing modules in Python" to avoid polluting the local namespace.
It is enough, but generally you should either do import project.model, which already imports __init__.py, per "Understanding python imports", but can get too wordy if you use it too much, or import project.model as pm or import project.model as model to save a few keystrokes later on when you use it.
Follow Alex's advice in "What exactly does "import *" import?"
A: If project.model is a package, the module referred to by import project.model is from .../project/model/__init__.py. from project.model import * dumps everything from __init__.py's namespace into yours. It does not automatically do anything with the other modules in model. The preferred style is for __init__.py not to contain anything.
Never ever ever ever ever use import *. It makes your code unreadable and unmaintainable.
A: Here is a nice way to see what star / asterisk ( * ) has imported from a module:
before = dir()
from math import *
after = dir()
print(set(after) - set(before))
returns:
{'modf', 'pow', 'erfc', 'copysign', 'sqrt', 'atan2', 'e', 'tanh', 'pi', 'factorial', 'cosh', 'expm1', 'cos', 'fmod', 'frexp', 'log', 'acosh', 'sinh', 'floor', 'isclose', 'lgamma', 'ceil', 'gcd', 'ldexp', 'hypot', 'radians', 'atan', 'isnan', 'atanh', 'before', 'isinf', 'fabs', 'isfinite', 'log10', 'nan', 'tau', 'acos', 'gamma', 'asin', 'log2', 'tan', 'degrees', 'asinh', 'erf', 'fsum', 'inf', 'exp', 'sin', 'trunc', 'log1p'}
I was working with my own module, importing everything explicitly but the list of stuff to import was getting too long. So, had to use this method to get a list of what * had imported.
A: If the module in question (project.model in your case) has defined a list of stings named __all__, then every named variable in that list is imported. If there is no such variable, it imports everything.
A: It import (into the current namespace) whatever names the module (or package) lists in its __all__ attribute -- missing such an attribute, all names that don't start with _.
It's mostly intended as a handy shortcut for use only in interactive interpreter sessions: as other answers suggest, don't use it in a program.
My recommendation, per Google's Python style guide, is to only ever import modules, not classes or functions (or other names) from within modules. Strictly following this makes for clarity and precision, and avoids subtle traps that may come when you import "stuff from within a module".
Importing a package (or anything from inside it) intrinsically loads and executes the package's __init__.py -- that file defines the body of the package. However, it does not bind the name __init__ in your current namespace (so in this sense it doesn't import that name).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2360724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "67"
}
|
Q: Removing a portion of text using regex? Here is what I have up to this point:
The function .*? takes everything until the first "this character". For example $html = preg_replace('/alt=".*?"/', '', $html); replaces everything between alt=" and other quotation mark with nothing. My problem is now I have to deal with multiple characters. Here is the portion of text I want to replace :
<a href="http://feeds.feedburner.com/~ff/TheWindowsClub?a=tjWEu-9hLFk:Jv9oVdSsx2A:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/TheWindowsClub?a=tjWEu-9hLFk:Jv9oVdSsx2A:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/TheWindowsClub?a=tjWEu-9hLFk:Jv9oVdSsx2A:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?i=tjWEu-9hLFk:Jv9oVdSsx2A:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/TheWindowsClub?a=tjWEu-9hLFk:Jv9oVdSsx2A:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/TheWindowsClub?a=tjWEu-9hLFk:Jv9oVdSsx2A:cGdyc7Q-1BI"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?d=cGdyc7Q-1BI" border="0"></img></a></div><img src="http://feeds.feedburner.com/~r/TheWindowsClub/~4/tjWEu-9hLFk" height="1" width="1" alt=""/>
Unlike last time I can't use quotation marks or other such character. I have to delete the whole line. One thing I thought about was to do something like this:
$html = preg_replace('/<a href=".*?(alt=""/>)/', '', $html);
I thought that using the above code would find the last portion in this segment and replace everything inside but it replaces nothing. Please suggest what should I do?
After running above line of code the output should be nothing. It should remove all this code block.
A: <a\s+href.*(alt="[^"]*")?>
or without quotation mark :
<a\s+href.*(alt="[^"]*"){0,1}>
We match everything that starts by <a, is followed by at least one space, then by any character until the character >, before which you may have zero or one iteration of the string alt="" containing anything but a ".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30794248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a button in unity from Input.GetMouseButtonDown How can I create a touch event or UI button that can execute the code below. I got that code from an asset that meant for PC i want to re-create that project for android mobile
using UnityEngine;
using System.Collections;
public class PlayerIO : MonoBehaviour {
RaycastHit hit;
int maxBuildDist = 10;
public Transform RetAdd;
public Transform RetDelete;
public Transform Player;
public GameObject Player_Camera;
Color Block_Color = Color.blue;
bool Block_Menu = false;
void Start(){
RetAdd = GameObject.Find("RetAdd").transform;
RetDelete = GameObject.Find("RetDel").transform;
Player = GameObject.FindGameObjectWithTag("Player").transform;
Player_Camera = GameObject.Find("Main Camera");
}
void Update(){
if(Input.GetKeyDown(KeyCode.E))
Block_Menu = !Block_Menu;
if(Block_Menu){
Time.timeScale = 0;
Player.GetComponent<MouseLook>().enabled = false;
Player_Camera.GetComponent<MouseLook>().enabled = false;
//((MonoBehaviour)Player.GetComponent<FPSInputController>()).enabled = false;
}
if(!Block_Menu){
Time.timeScale = 1;
Player.GetComponent<MouseLook>().enabled = true;
Player_Camera.GetComponent<MouseLook>().enabled = true;
//((MonoBehaviour)Player.GetComponent<FPSInputController>()).enabled = true;
}
if(!Block_Menu){
if(Physics.Raycast(Camera.main.ScreenPointToRay(new Vector3((Screen.width / 2), (Screen.height / 2), 0)), out hit, maxBuildDist)){
RetAdd.GetComponent<Renderer>().enabled = true;
if(hit.transform.tag == "Block"){
RetAdd.transform.position = hit.transform.position + hit.normal;
RetDelete.transform.position = hit.transform.position;
RetDelete.GetComponent<Renderer>().enabled = true;
}
if(hit.transform.tag != "Block"){
RetDelete.GetComponent<Renderer>().enabled = false;
RetAdd.transform.position = new Vector3(hit.point.x, hit.point.y + 0.5f, hit.point.z);
}
if(Input.GetMouseButtonDown(0)){
GameObject block = (GameObject)Instantiate(Resources.Load("Block01"), RetAdd.transform.position, Quaternion.identity);
block.GetComponent<Renderer>().material.color = Block_Color;
}
else if(Input.GetMouseButtonDown(1) && hit.transform.tag != "Floor"){
Destroy(hit.transform.gameObject);
}
}
else{
RetAdd.GetComponent<Renderer>().enabled = false;
RetDelete.GetComponent<Renderer>().enabled = false;
}
}
}
void OnGUI(){
if(Block_Menu)
Block_Menu_GUI();
}
void Block_Menu_GUI(){
GUILayout.BeginVertical();
if(GUILayout.Button("Green"))
Block_Color = Color.green;
if(GUILayout.Button("Red"))
Block_Color = Color.red;
if(GUILayout.Button("Blue"))
Block_Color = Color.blue;
GUILayout.EndVertical();
}
}
this is the whole code of the script that I want to change. I already had a joystick control but the problem is since I'm using that OnMouseDown whenever I click my joystick the object is spawning
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46379918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I use Provider to provide a bloc to a PageView() without the child resubscribing everytime I switch page? I am using Provider to provide my bloc to a widget called TheGroupPage via a static create method
static Widget create(BuildContext context, GroupModel group) {
final database = Provider.of<DatabaseService>(context);
return Provider(
create: (_) => GroupMembersBloc(database, group),
child: TheGroupPage(group),
dispose: (BuildContext context, GroupMembersBloc bloc) => bloc.dispose(),
);
}
That widget has a PageView() with 3 pages
PageView(children: [
TheGroupNotificationsView(),
TheGroupMembersView(group),
TheGroupSettingsView(group),
])
The group members view looks for the GroupMembersBloc
GroupMembersBloc bloc = Provider.of<GroupMembersBloc>(context);
I also tried to put listen to false but this did not work. And I want the widget to listen for any changes. The page uses that bloc's stream to draw a list of group members
class GroupMembersBloc{
StreamController<List<UserModel>> _controller = StreamController<List<UserModel>>();
Stream<List<UserModel>> get stream => _controller.stream;
GroupMembersBloc(DatabaseService database, GroupModel group)
{
_controller.addStream(database.groupMembersStream(group));
}
void dispose(){
_controller.close();
}
}
The problem is when I switch page inside the PageView() I get an error on the page after the first time it has been shown. The error says Bad state: Stream has already been listened to. how can I solve this?
A: That's because stream controllers allow only 1 Subscription (or 1 listener) , you could use the [StreamController<List<UserModel>>.broadcast()][1] constructor instead of StreamController>().
A: I ended up moving the StreamBuilder to the parent widget above the PageView() which fixed the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61471472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting Errors When Downloading Files From SQL Database I am running a website, and part of the site is allowing users to upload files to a SQL database, and then download them. The download itself works, but the file is getting corrupted. Image files cannot be opened, doc files are showing up as blank. I will attach below my uploading script and my downloading script.
$classid = $_POST['uploadclass'];
$userid = $_SESSION['id'];
$view = $_POST['view'];
$filename = $_FILES['uploadfile']['name'];
$tmpname = $_FILES['uploadfile']['tmpname'];
$filesize = $_FILES['uploadfile']['size'];
$filetype = $_FILES['uploadfile']['type'];
$fp = fopen($tmpname, 'r');
$content = fread($fp, filesize($tmpname));
$content = addslashes($content);
fclose($fp);
if (!get_magic_quotes_gpc()){
$filename = addslashes($filename);
}
$query = "INSERT INTO uploads VALUES('','$filename', '$filetype', '$filesize', '$content', '$userid', '$classid', '$view', 'no')";
$run = mysqli_query($connect, $query);
mysqli_close($connect);
header('location: files.php');
Below is the code for my download page.
$query = "SELECT * FROM uploads WHERE id=$id";
$run = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($run)){
$name = $row['name'];
$type = $row['type'];
$size = $row['size'];
$content = $row['content'];
}
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
?>
A: You are incorrectly handling the files and everything else when inserting them into the database. All files that are already there are damaged and probably destroyed.
addslashes() is no escaping function for a database. Always use the escaping function that comes with the DB extension you are using. If you are using mysqli, then the correct function must be mysqli_real_escape_string().
You should however have a look at prepared statements. These will use an different way of transferring the data that does not need escaping. Do pay attention however to the setting of magic quotes. The preferred setting is OFF, and the recent PHP versions starting with 5.4 have this feature removed already. So you have to deal with escaping the data you insert into the database anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20035165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where in a "block" I am doing a program that have very similar code blocks, and I was trying to make a where in a "block".
Just an example
function "sum" x = x + a
function "product" x = x * a
where
a = 2
I want the 'a' to be replaced in both lines, but I didn't find out if this is possible using where
Thanks in advance
A: If you really need this, you need to merge the two function clauses. One way to do this:
func what x = case what of
"add" -> x+a
"mul" -> x*a
where
a = 2
A: You can also introduce a second function:
function fName x = function' fName x
where
a = 2
function' "sum" x = x + a
function' "product" x = x * a
A: (Forgive me because I'm a newbie.) I don't think this is possible. The scope of the where "block" is the function it's defined in. What you can do is this, though:
Prelude> let a = 2
Prelude> let sum x = x + a
Prelude> let product x = x * a
Prelude> sum 3
5
This is done in GHCi. You may be concerned that everyone can see a, but if this were in a .hs file, you could make it a module and just not export a, and then only these functions could see it.
A: I think you can define a new function geta
geta=2
And then you can use the geta function in any other functions.
I don't think mix every functions is a good way,
maybe you will have 20 functions need the same value
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14762407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Referring to a previously existing DataSet I'm working on a very basic VB.net frontend for an Access database and have stumbled upon a problem.
Dim ds As DataSet
MaxRows = ds.Tables("Course_assignmentsDataSet.tblCourse").Rows.Count
i = 0
Private Sub Navigate()
txtCourseReference.Text = ds.Tables("Course_assignmentsDataSet.tblCourse").Rows(i).Item(1)
txtCourseName.Text = ds.Tables("Course_assignmentsDataSet.tblCourse").Rows(i).Item(2)
End Sub
I get the error that Object Reference is not set to an instance of an Object. I think this is because I haven't defined the DataSet as "Course_assignmentsDataSet"- the one I want to use- but I'm not sure how to do this.
Can anyone help?
A: Your dataset needs to be instantiated using the "New" keyword. The object reference in this case is ds, and it's just set to type dataset. New creates an "instance" of the DataSet.
Dim ds as New Course_assignmentsDataSet
Then you'll want to do:
txtCourseReference.Text = ds.Tables("tblCourse").Rows(i).Item(1)
txtCourseName.Text = ds.Tables("tblCourse").Rows(i).Item(2)
Edit: As Jay said below, you'll want to fill the dataset first
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6783568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Resolve remote host names into ip addresses in codename one I'm interested in the ip address of remote hosts. Is there an easy way to resolve a host name into its ip address?
After searching in the codename one source code and reading through the documentation, the only way to achieve this seems by implement android/ios native features (e.g. using the InetAddress class).
A: Yes you would need to implement this using native code or thru the Socket API by implementing the DNS protocol calls.
The InetAddress class can be used in the Android/Desktop ports but other platforms (e.g. iOS) would need the Objective-C/C equivalent of that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37040185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R loop through name specific columns to check the value I want to achieve the following:
*
*loop through all CHECK columns, sometimes there are more (up to 20). The same goes for data (will definitely more than 3 observations). feel free to use my variables CHECKnum, CHECKstart or CHECKend
*check whether A001 is in it, if yes, return the column name, else return CHECK0
sample data
mydf <- data.frame(case = c(1, 2, 3),
id = c(10, 11, 12),
CHECK1 = c("A001", "B001", "C001"),
CHECK2 = c("Z001", "B001", "C001"),
CHECK3 = c("Z001", "B001", "C001"),
CHECK4 = c("Z001", "B001", "A001"),
CHECK5 = c("Z001", "B001", "C001"))
Trial:
CHECKnum = ifpol %>%
colnames(.) %>%
str_which("^CHECK") %>%
length(.)
CHECKstart = which(colnames(ifpol) == "CHECK1")
CHECKend = CHECKstart + CHECKnum
for (i in 1:CHECKnum) {
# giving out position and column name
mydf = mydf %>% mutate(CHECK_Pos = case_when(mydf[paste0("CHECK", i)] == "A001" ~ i * 1,
TRUE ~ 0),
CHECK_Name = case_when(mydf[paste0("CHECK", i)] == "A001" ~ paste0("CHECK", i),
TRUE ~ "CHECK0"))
}
I want it to show something like
enter image description here
A: Here's a base R option using max.col :
#Select the columns to check
cols <- grep('CHECK', names(mydf), value = TRUE)
#Compare the value
mat <- mydf[cols] == 'A001'
#Find the column name where the value exist in each row
mydf$result <- cols[max.col(mat)]
#If the value does not exist in the row turn to `NA`.
mydf$result[rowSums(mat) == 0] <- NA
mydf
# case id CHECK1 CHECK2 CHECK3 CHECK4 CHECK5 result
#1 1 10 A001 Z001 Z001 Z001 Z001 CHECK1
#2 2 11 B001 B001 B001 B001 B001 <NA>
#3 3 12 C001 C001 C001 A001 C001 CHECK4
A: As a supplement:
I think the long format is a nice option for this case.
Becase it's very clear to show the position "A001" and easy to filter even for more CHECK number.
I will use data.table as a demonstration.
library(data.table)
setDT(mydf)
dt <- melt(mydf, id = 1:2, measure.vars = patterns("CHECK*"))
dt
Long format
case id variable value
1: 1 10 CHECK1 A001
2: 2 11 CHECK1 B001
3: 3 12 CHECK1 C001
4: 1 10 CHECK2 Z001
5: 2 11 CHECK2 B001
6: 3 12 CHECK2 C001
7: 1 10 CHECK3 Z001
8: 2 11 CHECK3 B001
9: 3 12 CHECK3 C001
10: 1 10 CHECK4 Z001
11: 2 11 CHECK4 B001
12: 3 12 CHECK4 A001
13: 1 10 CHECK5 Z001
14: 2 11 CHECK5 B001
15: 3 12 CHECK5 C001
Filter A001
dt[value == "A001"]
case id variable value
1: 1 10 CHECK1 A001
2: 3 12 CHECK4 A001
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66759259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NFC Permission Error I am working on an application that uses NFC and I keep getting this error,
`12-28 14:19:41.962: E/AndroidRuntime(27523): java.lang.RuntimeException: Unable to resume activity {com.example.clinkguitest/com.example.clinkguitest.MainActivity}: java.lang.SecurityException: NFC permission required: Neither user 10168 nor current process has android.permission.NFC.`
I have android:permission="android.permission.NFC" in my manifest so what is wrong? Thanks.
A: In my manifest permissions look like this:
<uses-permission android:name="android.permission.NFC" />
Maybe that's the problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14074671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Powershell remotely register COM dll by using regsvr32 I found on Internet, this ps script may work. But the result I get is: no error pops up, but also DLL not found in registry after running the script.
Invoke-Command -ComputerName $servername -ScriptBlock {regsvr32.exe "\\uncpath\some.dll" }
I tried in both "run as administrator" and normal PS console window, and windows remote management service is on on remote server.
Any idea?
A: You need to use the silent option of regsrv32 (/s):
Syntax
REGSVR32 [/U] [/S] [/N] /I:[CommandLine] DLL_Name
Key /u Unregister Server.
/s Silent, do not display dialogue boxes.
/i Call DllInstall to register the DLL.
(when used with /u, it calls dll uninstall.)
/n Do not call DllRegisterServer, you must use this option
with /i.
CommandLine An optional command line for DllInstall
/c Console output (old versions only).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20461721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why when passing parameters from one component to another it arrives undefined and then arrives again with the data? As will be shown below when passing properties from a parent component to a child component my code is executed first before the properties arrive and when trying to do a .map of an Array it returns the error "Cannot read properties of undefined (reading 'map')". Why does this happen?
As you can see in the image, first you get undefined values which generates the error in the .map and then you get the properties
Parent component:
import React, {useEffect, useState} from "react";
import ItemDetail from "./itemDetail";
import '../../App.css';
import { useParams } from "react-router-dom";
//Component Class
const ItemDetailContainer = () => {
const [producto, productos] = useState([]);
const { productId } = useParams();
useEffect(() => {
fetch('http://localhost:3000/productos/' + productId)
.then(res=>res.json())
.then(data=>productos(data))
}, [productId]);
console.log(producto);
return (
<div className="container">
<ItemDetail
nombre={producto.nombre}
id={producto.id}
precio={producto.precio}
category={producto.category}
imagenes={producto.imagenes}
ancho={producto.ancho}
alto={producto.alto} />
</div>
)
}
export default ItemDetailContainer;
Child component:
import React from 'react';
import { Card } from 'react-bootstrap';
import ItemCount from '../itemCount';
const ItemDetail = ({ nombre, id, precio, category, imagenes, ancho, alto }) => {
console.log(imagenes);
return (
<div className="row" key={id} id={id}>
<div className="col-md-6" id="productImage">
<div className="carousel-item">
{imagenes.map((p) => (
<img src={p} className="d-block w-100" alt={nombre} />
))}
</div>
</div>
<div className="col-md-6 producto">
<div className="card">
<Card.Body>
<Card.Title>{nombre}</Card.Title>
<Card.Text>{category}</Card.Text>
<Card.Text>${precio}</Card.Text>
<ItemCount />
</Card.Body>
</div>
</div>
</div>
);
};
export default ItemDetail;
A: Change your code to only execute if imagenes is an array. Personally I would rethink how you are structuring your initial state. Instead of it being an empty array, perhaps make it an object with all of those properties having default values.
<div className="carousel-item">
{ Array.isArray(imagenes) && imagenes.map((p) => (
<img src={p} className="d-block w-100" alt={nombre} />
))}
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69274810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I add a foreach inside another foreach in this context? When a user registers on my platform, there's some code that removes invisible characters.
I wanted to go further and add ucwords into it. However, I need to have some exceptions, as some words in Portuguese names aren't supposed to be capitalized.
The code has one if statement and an else one. I don't know how to change the else statement to correspond to the same thing as my if statement, because it's already a foreach loop.
$exceptions = array('DAS' => 'das', 'DA' => 'da', 'DE' => 'de', 'DOS' => 'dos', 'DO' => 'do');
if ( !\is_array( $return ) )
{
$return = preg_replace( '/\p{C}+/u', '', $return );
$return = ucwords( $return );
foreach ( $exceptions as $exception => $fix )
{
$return = str_replace( $exception, $fix, $return );
}
}
else
{
foreach( $return as $k => $v )
{
$return[ $k ] = preg_replace( '/\p{C}+/u', '', $v );
$return[ $k ] = ucwords( $v );
//What do I add below? How do I type another foreach instead this one?
}
}
EDIT:
Would this make sense? If so, why?
else
{
foreach( $return as $k => $v )
{
$return[ $k ] = preg_replace( '/\p{C}+/u', '', $v );
$return[ $k ] = ucwords( $v );
//Does this make sense?
foreach ( $exceptions as $k => $v )
{
$return = str_replace( $k, $v, $return );
}
}
}
A: The code between array and non-array are the same, so you can write a single foreach
$return = (array)$return;
foreach ($return as $k => $v) {
$return[ $k ] = preg_replace( '/\p{C}+/u', '', $v );
$return[ $k ] = ucwords( $v );
foreach ( $exceptions as $exception => $fix ) {
$return[$k] = str_replace( $exception, $fix, $return[$k] );
}
}
Alternatively, this is what you'd use a function for
function fix_things($s) {
$exceptions = array('DAS' => 'das', 'DA' => 'da', 'DE' => 'de', 'DOS' => 'dos', 'DO' => 'do');
$s = preg_replace( '/\p{C}+/u', '', $s );
$s = ucwords( $s );
foreach ( $exceptions as $exception => $fix )
{
$s = str_replace( $exception, $fix, $s );
}
return $s;
}
Then call that function from your main code
if (!\is_array($return)) {
$return = fix_things($return);
else {
foreach ($return as $k => $v) {
$return[$k] = fix_things($v);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71289364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Shopify customers/account.liquid Create for loop sort of order I'm trying to sort orders in customers/account.liquid by shipping_address.name
{% assign orders = customer.orders | sort: 'shipping_address.name' %}
{% for order in orders %}
<tr class="{% cycle 'odd', 'even' %} {% if order.cancelled %}cancelled_order{% endif %}">
<td>{{ order.name | link_to: order.customer_url }}</td>
<td><span class="ship_name">{{ order.shipping_address.name }}</span></td>
<td><span class="note">{{ order.created_at | date: format: 'month_date_year' }}</span></td>
<td><span class="status_{{ order.financial_status }}">{{ order.financial_status }}</span></td>
<td><span class="status_{{ order.fulfillment_status }}">{{ order.fulfillment_status }}</span></td>
<td><span class="total money">{{ order.total_price | money }}</span></td>
</tr>
{% endfor %}
see screen shot
A: You forgot to use the sorted array! I made it easier to follow by renaming the variables a bit.
{% assign sortedOrders = customer.orders | sort: 'order.shipping_address.name' %}
{% for order in sortedOrders %}
...
{% endfor %}
Hope you're getting enough sleep!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31460691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Nokogiri 1.6.8 is installed but gives error for previous Nokogiri when running "bundle install" We had a server shutdown and Redmine stopped working, so I had to reinstall Bundler and run bundle install.
While running bundle install I get this error:
c:\APPS\webapps\redmine-3.2.0>bundle install
Fetching gem metadata from https://rubygems.org/.............
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies....
Using rake 12.3.2
Using concurrent-ruby 1.1.5
Using i18n 0.9.5
Using json 1.8.6
Using minitest 5.11.3
Using thread_safe 0.3.6
Using tzinfo 1.2.5
Using activesupport 4.2.5
Using builder 3.2.3
Using erubis 2.7.0
Using mini_portile2 2.4.0
Fetching nokogiri 1.9.1 (x64-mingw32)
Installing nokogiri 1.9.1 (x64-mingw32)
Gem::RuntimeRequirementNotMetError: nokogiri requires Ruby version >= 2.2, <
2.6. The current ruby version is 2.0.0.
An error occurred while installing nokogiri (1.9.1), and Bundler cannot
continue.
Make sure that `gem install nokogiri -v '1.9.1' --source
'https://rubygems.org/'` succeeds before bundling.
In Gemfile:
rails was resolved to 4.2.5, which depends on
actionmailer was resolved to 4.2.5, which depends on
actionpack was resolved to 4.2.5, which depends on
actionview was resolved to 4.2.5, which depends on
rails-dom-testing was resolved to 1.0.9, which depends on
nokogiri
I already installed Nokogiri 1.6.8. I'm not sure why it cannot read the Nokogiri version that I installed and still fetches 1.9.1 because I need Ruby v. 2 for Redmine 2.3.0, however my bundle is still telling me that it is looking for 1.9.1. While doing bundle install I tried changing the Gemfile based on my research to gem "nokogiri", ">= 1.4.2" however 1.9.1 is persisting. How can I successfully upgrade Nokogiri?
I used:
gem "nokogiri", "1.6.8"
In my Gemfile I have:
c:\APPS\webapps\redmine-3.2.0>bundle update nokogiri
Fetching gem metadata from https://rubygems.org/.............
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies....
Bundler could not find compatible versions for gem "nokogiri":
In Gemfile:
nokogiri (= 1.6.8) java
roadie-rails java was resolved to 1.2.0, which depends on
roadie (~> 3.1) java was resolved to 3.5.0, which depends on
nokogiri (~> 1.8) java
If I run what gem install nokogiri -v '1.9.1', I get an error that my Ruby version is lower than expected and I cannot have a higher Ruby version because Redmine is an old version.
Here are all the Nokogiri versions I have:
c:\APPS\webapps\redmine-3.2.0>gem uninstall nokogiri
YAML safe loading is not available. Please upgrade psych to a version that supports safe loading (>= 2.0).
Select gem to uninstall:
1. nokogiri-1.6.8.rc3-x64-mingw32
2. nokogiri-1.6.8-x64-mingw32
3. nokogiri-1.6.8.1-x64-mingw32
4. All versions
A: I could not fix this issue. It was looping through upgrades and downgrades, so after much frustration I tried Ruby 2.6 that Redmine 4.2 claimed to be compatible, which still had issues. I downgraded to Ruby 2.3 and it worked, then I migrated my database according to the redmine.org documentation and almost everything is functional, and I got a feedback that it is much faster.
According to my experience, you will have your Redmine database still working so don't worry that it s the same version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56728540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Suggestions for Writing Map as JSON file in Scala I have a simple single key-valued Map(K,V) myDictionary that is populated by my program and at the end I want to write it as JSON format string in a text file - as I would need parse them later.
I was using this code earlier,
Some(new PrintWriter(outputDir+"/myDictionary.json")).foreach{p => p.write(compact(render(decompose(myDictionary)))); p.close}
I found it to be slower as the input size increased. Later, I used this var out = new
var out = new PrintWriter(outputDir+"/myDictionary.json");
out.println(scala.util.parsing.json.JSONObject(myDictionary.toMap).toString())
This is proving to be bit faster.
I have run this for sample input and found that this is faster than my earlier approach. I assuming my input map size would reach at least a million values( >1GB text file) (K,V) hence I want to make sure that I follow the faster and memory efficient approach for Map serialization process.What are other approaches that you would recommend,that I can look into to optimize this.
A: The JSON support in the standard Scala library is probably not the best choice. Unfortunately the situation with JSON libraries for Scala is a bit confusing, there are many alternatives (Lift JSON, Play JSON, Spray JSON, Twitter JSON, Argonaut, ...), basically one library for each day of the week... I suggest you have a look at these at least to see if any of them is easier to use and more performative.
Here is an example using Play JSON which I have chosen for particular reasons (being able to generate formats with macros):
object JsonTest extends App {
import play.api.libs.json._
type MyDict = Map[String, Int]
implicit object MyDictFormat extends Format[MyDict] {
def reads(json: JsValue): JsResult[MyDict] = json match {
case JsObject(fields) =>
val b = Map.newBuilder[String, Int]
fields.foreach {
case (k, JsNumber(v)) => b += k -> v.toInt
case other => return JsError(s"Not a (string, number) pair: $other")
}
JsSuccess(b.result())
case _ => JsError(s"Not an object: $json")
}
def writes(m: MyDict): JsValue = {
val fields: Seq[(String, JsValue)] = m.map {
case (k, v) => k -> JsNumber(v)
} (collection.breakOut)
JsObject(fields)
}
}
val m = Map("hallo" -> 12, "gallo" -> 34)
val serial = Json.toJson(m)
val text = Json.stringify(serial)
println(text)
val back = Json.fromJson[MyDict](serial)
assert(back == JsSuccess(m), s"Failed: $back")
}
While you can construct and deconstruct JsValues directly, the main idea is to use a Format[A] where A is the type of your data structure. This puts more emphasis on type safety than the standard Scala-Library JSON. It looks more verbose, but in end I think it's the better approach.
There are utility methods Json.toJson and Json.fromJson which look for an implicit format of the type you want.
On the other hand, it does construct everything in-memory and it does duplicate your data structure (because for each entry in your map you will have another tuple (String, JsValue)), so this isn't necessarily the most memory efficient solution, given that you are operating in the GB magnitude...
Jerkson is a Scala wrapper for the Java JSON library Jackson. The latter apparently has the feature to stream data. I found this project which says it adds streaming support. Play JSON in turn is based on Jerkson, so perhaps you can even figure out how to stream your object with that. See also this question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19442723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: d3 v4 Positioning labels without touching polygon boundaries I'm working on a d3 v4 map that needs short labels positioned within each poloygon generated from topojson.
You can see where I've got to here:
http://bl.ocks.org/oroojo/9afff90bdb85deb78359a0d5e87a3f31/7606b296a1a47de3b9370d757182386fa35ac650
You'll see that I have the labels centered using path.centroid(d).
This is not ideal as the center is not always the best place to put the label due to random polygon shapes.
I'm sure there is a way of finding a position that does not touch the boundary, though calculation..
Any thoughts?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46466703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bash execute another command and enter input automatically I have a script when running it with ./script.sh it prints something in the console, then asks for a user input username?. After writing my username it asks a lot of other things which I have to write to the console.
I have one case where I have exactly the same input over and over again.
I want to write a second script that calls the first one and automatically puts in this input into the first script, so I only need to call the second script.
How can I achieve that? I know how I can call the first script from the second script but I have no idea where to put the input.
A: If it's reading from stdin for things like the password too, then you should be able to just put all your answers as lines in a file and redirect the script input from there.
./script.sh < answers.txt
A lot of apps won't accept passwords that way, though...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72477134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: why do i get: IndexError: tuple index out of range? i've been trying to create a tictactoe agent and when i ran the training loop i got an error pointing towards the (.0) in the function that checks whether someone won(check_game_status).
if you need the whole environment let me know.
here is the way the board was created:
board = [0] * 9
which means the 0 means empty spot, 1 for O and 2 for x.
here is after_action_state function:
def after_action_state(state, action):
"""Execute an action and returns resulted state.
Args:
state (tuple): Board status + mark
action (int): Action to run
Returns:
tuple: New state
"""
board, mark = state
nboard = list(board[:])
nboard[action] = tocode(mark)
nboard = tuple(nboard)
return nboard, next_mark(mark)
tocode function basically converts 'X' to 2 and 'O' to 1
this is the function that the error pointed at:
def check_game_status(board):
"""Return game status by current board status.
Args:
board (list): Current board state
Returns:
int:
-1: game in progress
0: draw game,
1 or 2 for finished game(winner mark code).
"""
for t in [1, 2]:
for j in range(0, 9, 3):
if [t] * 3 == [board[i] for i in range(j, j+3)]:
return t
for j in range(0, 3):
if board[j] == t and board[j+3] == t and board[j+6] == t:
return t
if board[0] == t and board[4] == t and board[8] == t:
return t
if board[2] == t and board[4] == t and board[6] == t:
return t
for i in range(9):
if board[i] == 0:
# still playing
return -1
# draw game
return 0
this is the play_one_step function that takes experience and puts it in a replay buffer using greedy epsilon policy.
def play_one_step(self, env ,state, available_actions, agents_model ,epsilon= 0.2):
action = self.greedy_policy(state, available_actions, agents_model ,epsilon= epsilon)
next_state, reward, done, info = env.step(action)
self.replay_buffer.append((state, action,reward, next_state, done))
return next_state, reward, done, info
and this is the epsilon greedy policy :
def greedy_policy(self, state ,available_actions, agents_model ,epsilon = 0.2):
if np.random.rand() < epsilon:
return np.random.choice(available_actions)
else:
for next_action in available_actions: # checking if the next possible action wins the game and if it does then it returns it
next_state = after_action_state(state, next_action)
game_status = check_game_status(next_state)
if game_status > 0 & tomark(game_status)==self.mark:
return next_action
Q_values = agents_model.predict(state[np.newaxis])
return np.argmax(Q_values[0])
this is the training loop:
agent_1 = Agent('X', model_1)
agent_2 = Agent('O', model_2)
agent_1_rewards = []
agent_2_rewards = []
agents = [agent_1, agent_2]
n_episodes = 600
start_mark = 'O'
batch_size = 15
for episode in range(n_episodes):
env = TicTacToeEnv()
env.set_start_mark(start_mark)
state = env.reset()
while not env.done:
_ , mark = state
available_actions = env.available_actions()
epsilon = max( 1 - episode/500 , 0.01)
agent = agent_by_mark(agents, mark)
agents_model = agent.agents_model
next_state, reward, done, _ = agent.play_one_step(env, state, available_actions, agents_model ,epsilon)
state = next_state
if agent is agent_1:
agent_1_rewards.append(reward)
else:
agent_2_rewards.append(reward)
env.render()
if episode > 60:
agent.training_step(15)
this is the error trace:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17792/1466320926.py in <module>
26
27
---> 28 next_state, reward, done, _ = agent.play_one_step(env, state, available_actions, agents_model ,epsilon)
29 state = next_state
30 if agent is agent_1:
~\AppData\Local\Temp/ipykernel_17792/3137506088.py in play_one_step(self, env, state, available_actions, agents_model, epsilon)
60
61 def play_one_step(self, env ,state, available_actions, agents_model ,epsilon= 0.2):
---> 62 action = self.greedy_policy(state, available_actions, agents_model ,epsilon= epsilon)
63 next_state, reward, done, info = env.step(action)
64 self.replay_buffer.append((state, action,reward, next_state, done))
~\AppData\Local\Temp/ipykernel_17792/3137506088.py in greedy_policy(self, state, available_actions, agents_model, epsilon)
35 for next_action in available_actions: # checking if the next possible action wins the game and if it does then it returns it
36 next_state = after_action_state(state, next_action)
---> 37 game_status = check_game_status(next_state)
38 if game_status > 0 & tomark(game_status)==self.mark:
39 return next_action
g:\Code\TicTacToe\gym-tictactoe\gym_tictactoe\env.py in check_game_status(board)
66 for t in [1, 2]:
67 for j in range(0, 9, 3):
---> 68 if [t] * 3 == [board[i] for i in range(j, j+3)]:
69 return t
70 for j in range(0, 3):
g:\Code\TicTacToe\gym-tictactoe\gym_tictactoe\env.py in <listcomp>(.0)
66 for t in [1, 2]:
67 for j in range(0, 9, 3):
---> 68 if [t] * 3 == [board[i] for i in range(j, j+3)]:
69 return t
70 for j in range(0, 3):
IndexError: tuple index out of range
does anyone know what causes this issue? i already tried to rewrite the function only and give it a few cases and it worked absolutely fine with no index problem.
if you need more of the code let me know.
thanks in advance!
A: It is not a fix but explains the cause of bug...
In the below snippet, you are trying to access board[i] with index i > 9 but your board is of size 9. For instance, check for j=9.
for j in range(0, 9, 3):
if [t] * 3 == [board[i] for i in range(j, j+3)]:
return t
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70383789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Serving static files in django 1.8 My 404.html page does not reference my finale.css file.
My directory structure
musicworld/
musicworld/
__pycache__
__int__.py
settings.py
urls.py
wsgi.py
feature/
__pycache__
migrations
static/
feature/
finale.css
templates/
feature/
about.html
detail.html
404.html
500.html
index.html
template.html
__init__.py
admin.py
models.py
tests
This is where in index.html I'm referencing the css
<link rel="stylesheet" type="text/css" href="{% static 'feature/finale.css' %}" />
But 404.html that extends index.htmlis not referencing the css
{% extends "index.html" %}
{% load staticfiles %}
{% block 404page %}
<div class="box">
<p class="box-message" data-dead-message="AAAAAHHHHHH!">Oh No! Something went wrong.Punish the developer by clicking here.</p>
</div>
<div class="robot">
<img src="" alt="Robot" />
</div>
{% endblock %}
static reference in settings.py
STATIC_URL = '/static/'
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
Both the index.htmland template.html are placed in the same folder and are properly referencing the css.Plus all the html pages in feature that are extending index.html are also referencing the css.But both 404.html and 500.htmlare not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30768303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: FMOD: Cleaning up duplicate platform warning FMOD for Unity 2.01.07 (Unity 2019.4.18f1 - running on MacOS Catalina) seems to have broken their FMODStudioSettings class.
I can't save in the editor without getting these errors:
FMOD: Cleaning up duplicate platform: ID = playInEditor, name = 'Play In Editor Settings', type = PlatformPlayInEditor
ArgumentException: An item with the same key has already been added. Key: playInEditor
FMOD: Cleaning up duplicate platform: ID = default, name = 'Default Settings', type = PlatformDefault
ArgumentException: An item with the same key has already been added. Key: default
NullReferenceException: Object reference not set to an instance of an object
FMODUnity.SettingsEditor.DisplayPlugins (System.String title, FMODUnity.Platform platform, FMODUnity.Platform+PropertyAccessor`1[T] property, System.Collections.Generic.Dictionary`2[TKey,TValue] expandState, System.String warning) (at Assets/Plugins/FMOD/src/Editor/SettingsEditor.cs:1028)
I believe this is a regression that basically makes the Unity integration unusable. Something to do with de-duplicating platforms in the Platforms map. At runtime there's a series of NPEs related to platforms so actually I can't run the game properly. Has anyone else run into this?
I'm evaluating FMOD as a middleware option for our game, and have run into at least two serious bugs in the Unity integration. See other bug here.
UPDATE:
I haven't found out why this doesn't happen for everyone, but an easy fix for anyone else running into this issue has been applying this diff:
diff --git a/Assets/Plugins/FMOD/src/Runtime/Settings.cs b/Assets/Plugins/FMOD/src/Runtime/Settings.cs
index 2641e926..c2843145 100644
--- a/Assets/Plugins/FMOD/src/Runtime/Settings.cs
+++ b/Assets/Plugins/FMOD/src/Runtime/Settings.cs
@@ -817,6 +817,10 @@ namespace FMODUnity
private void PopulatePlatformsFromAsset()
{
+ Platforms.Clear();
+ PlatformForBuildTarget.Clear();
+ PlatformForRuntimePlatform.Clear();
+
#if UNITY_EDITOR
string assetPath = AssetDatabase.GetAssetPath(this);
UnityEngine.Object[] assets = AssetDatabase.LoadAllAssetsAtPath(assetPath);
@@ -827,36 +831,8 @@ namespace FMODUnity
foreach (Platform newPlatform in assetPlatforms)
{
- Platform existingPlatform = FindPlatform(newPlatform.Identifier);
-
- if (existingPlatform != null)
- {
- // Duplicate platform; clean one of them up
- Platform platformToDestroy;
-
- if (newPlatform.Active && !existingPlatform.Active)
- {
- Platforms.Remove(existingPlatform.Identifier);
-
- platformToDestroy = existingPlatform;
- existingPlatform = null;
- }
- else
- {
- platformToDestroy = newPlatform;
- }
-
- Debug.LogWarningFormat("FMOD: Cleaning up duplicate platform: ID = {0}, name = '{1}', type = {2}",
- platformToDestroy.Identifier, platformToDestroy.DisplayName, platformToDestroy.GetType().Name);
-
- DestroyImmediate(platformToDestroy, true);
- }
-
- if (existingPlatform == null)
- {
- newPlatform.EnsurePropertiesAreValid();
- Platforms.Add(newPlatform.Identifier, newPlatform);
- }
+ newPlatform.EnsurePropertiesAreValid();
+ Platforms.Add(newPlatform.Identifier, newPlatform);
}
#if UNITY_EDITOR
A: So this was a bug in the integration they fixed in 2.01.10.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65711930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Name lookup in using-declaration via using-directive Is the following program well-formed or ill-formed according to the c++ standard?
namespace N { int i; }
using namespace N;
using ::i;
int main() {}
I get different results with different compilers:
*
*Clang (http://melpon.org/wandbox/permlink/c8vl7XbumyyS6vsw): No errors.
*GCC (http://melpon.org/wandbox/permlink/immhNeWFCMcCA800): Error: 'i' not declared.
Is this program well-formed or ill-formed according to the c++ standard? References to the c++ standard needed.
I'm trying to figure out for which compiler I should file a bug.
A: Well-formed.
The using-directive doesn't introduce the name i in the global namespace, but it is used during lookup. The using-declaration uses qualified lookup to find i; qualified lookup in the presence of using-directives is specified in [3.4.3.2 p1, p2] (quotes from N4527, the current working draft):
If the nested-name-specifier of a qualified-id nominates a namespace
(including the case where the nested-name-specifier is ::, i.e.,
nominating the global namespace), the name specified after the
nested-name-specifier is looked up in the scope of the namespace. [...]
For a namespace X and name m, the namespace-qualified lookup set
S(X,m) is defined as follows: Let S'(X,m) be the set of all
declarations of m in X and the inline namespace set of X (7.3.1). If
S'(X,m) is not empty, S(X,m) is S'(X,m); otherwise, S(X,m) is the
union of S(Ni,m) for all namespaces Ni nominated
by using-directives in X and its inline namespace set.
So, for qualified lookup, the first step is to look for declarations of i made directly in the namespace indicated by the nested-name-specifier (:: in this case). There are no such declarations, so lookup then proceeds to the second step, which is to form the set of all declarations of i found by qualified lookup in all namespaces nominated by using-directives in the global namespace. That set is comprised of N::i, which is the result of name lookup, and is introduced as a name in global namespace by the using declaration.
I find it worth noting (although pretty obvious) that this definition of qualified lookup is recursive: using the notation in the quote, qualified lookup in each namespace Ni will first look for declarations made directly in Ni, then, if none is found, will in turn proceed to look in the namespaces nominated by using-directives in Ni, and so on.
For what it's worth, MSVC accepts the code as well.
A: GCC is wrong. Qualified name lookup does consider N::i; §3.4.3.2/2 & /3:
For a namespace X and name m, the namespace-qualified lookup set
S(X, m) is defined as follows: Let S'(X, m) be the set of all
declarations of m in X and the inline namespace set of X
(7.3.1). If S'(X, m) is not empty, S(X, m) is S'(X, m);
otherwise, S(X, m) is the union of S(Ni, m) for all namespaces Ni nominated by using-directives in X
and its inline namespace set.
Given X::m (where X is a user-declared namespace), or given ::m (where
X is the global namespace), […] if S(X, m) has exactly one member, or if the
context of the reference is a using-declaration (7.3.3), S(X, m) is
the required set of declarations of m.
There is only one namespace nominated by a using-directive in your program: N. It's therefore included in the union and ::i is resolved to N::i.
Note that GCC is inconsistent with its lookup: Using ::i in another context is fine.
namespace N { int i; }
using namespace N;
int main() {
::i = 5;
}
This compiles. The only difference that a using-declaration makes as a context is shown in the above quote and does not affect the established conclusion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31628853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.