text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Apple Watch on react-native I want to get react-native working for the Apple Watch, but I'm not sure where to start
I started reading the code for the iOS implementation to figure out how they did it there.
My question is: are there any resources or guidelines for help to actually implement react-native (do they ever talk about this aspect of it) or do I need to just read through the code and figure it out on my own?
It would be nice if the react-native team made a document on how they got it up and running on iOS (or Android), though they may already have that out there which is what I'm looking for.
Thanks in advance for any advice and/or help
A: I was looking into this, too. I will share my findings.
According to this comment from the React Native team back in 2015, the team doesn't have resources to support it, yet.
Right now, we're focused on normal iOS and Android. We still a very small team and don't have the resources to target a different support right now. However, we open sourced React Native in the hope that we get help from the community to build those :)
Someone tried to build one with a lot of reverse engineering, but there are still unsolved issues causing crashes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36867628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to disable all actions of hyperlink and submit form but can drag these elements I use JavaFx WebView to show a web page but I don't want to have any interaction(location change) on web page and web engine disabled Javascript also. Because of that reason, I tried to disable all actions of hyperlink and submit form by
a[style] {
pointer-events: none !important;
cursor: default;
}
input[style] {
pointer-events: none !important;
cursor: default;
}
So I can not drag them. Have another way for this issue? Solve it by CSS or JavaFx as better.
Thanks for advance.
A: Using Jquery:
$('input[type="submit"]').attr('disabled','disabled');
and
$('a').attr('disabled','disabled');
like this
A: You can attempt to prevent the default action on as many events as you like. Note that browsers usually allow this, but do have the final say (I vaguley remember some issues with this not always working).
var events = ["keypress","click","submit","focus","blur","tab"];
events.forEach(function(eventName){
window.addEventListener(eventName, function(e){
// this is the list of tags we'd like to prevent events on
// you may wish to remove this early return altogether, as even a div or span
// can cause a form to submit with JavaScript
if (["INPUT","A","FORM","BUTTON"].indexOf(e.tagName) === -1) {
return;
}
// prevent the default action
e.preventDefault();
// stop other JavaScript listeners from firing
e.stopPropagation();
e.stopImediatePropagation();
// if an input is somehow focused, unfocus it
var target = e.target;
setTimeout(function(){
if (target.blur) target.blur();
}, 50);
// true as the third parameter signifies 'use capture' where available;
// this means we get the event as it's going down, before it starts to bubble up
// our propagation prevention will thus also prevent most delegated event handlers
}, true);
});
You cannot solve this with CSS. pointer-events doesn't allow you to specify which pointer events are okay. For that, you do need JavaScript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26396417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CAShapeLayer strokeColor get mix with fillColor I have made a hexagonal View with border. The problem I am facing now is I am not able to set the desired color for border which I have made using strokeWidth (not borderWidth) and now my layer's strokeColor get mix with fill color of the layer.
Here is the code:
CAShapeLayer *hexagonMask = [CAShapeLayer layer];
CAShapeLayer *hexagonBorder = [CAShapeLayer layer];
hexagonMask.frame=self.layer.bounds;
hexagonBorder.frame = self.layer.bounds;
UIBezierPath* hexagonPath=[self makeHexagonalMaskPathWithSquareSide:side]; //making hexagon path
hexagonMask.path = hexagonPath.CGPath; //setting the mask path for hexagon
hexagonBorder.path = hexagonPath.CGPath; //setting the maskpath for hexagon border
hexagonBorder.fillColor=[UIColor clearColor].CGColor; //setting by default color
hexagonBorder.lineWidth = self.customBorderWidth; // setting border width
hexagonBorder.strokeColor = self.customBorderColor.CGColor; //setting color for hexagon border
hexagonBorder.fillColor = self.customFillColor.CGColor; //setting fill color for hexagon
Any suggestions to solve this Problem?
A: Finally I found a way out to solve this problem.
I have added a CALayer as sublayer and the fill color is used to create as a UIImage which is used to set as contents for the sublayer.
Here is the code for someone who may face this problem in future
CAShapeLayer *hexagonMask = [CAShapeLayer layer];
CAShapeLayer *hexagonBorder = [CAShapeLayer layer];
hexagonMask.frame=self.layer.bounds;
hexagonBorder.frame = self.layer.bounds;
UIBezierPath* hexagonPath=[self makeHexagonalMaskPathWithSquareSide:side]; //making hexagon path
hexagonMask.path = hexagonPath.CGPath; //setting the mask path for hexagon
hexagonBorder.path = hexagonPath.CGPath; //setting the maskpath for hexagon border
hexagonBorder.fillColor=[UIColor clearColor].CGColor; //setting by default color
hexagonBorder.lineWidth = self.customBorderWidth; // setting border width
hexagonBorder.strokeColor = self.customBorderColor.CGColor; //setting color for hexagon border
CGFloat coverImageSide=side-(_customBorderWidth);
CGFloat backgroundLayerXY=_customBorderWidth/2.0;
UIImage *coverImage=[UIImage ImageWithColor:_customFillColor width:coverImageSide height:coverImageSide];
UIBezierPath* dpath=[self makeHexagonalMaskPathWithSquareSide:coverImageSide];
CALayer *backgroundLayer=[CALayer layer];
backgroundLayer.frame=CGRectMake(backgroundLayerXY, backgroundLayerXY, coverImageSide, coverImageSide);
CAShapeLayer *backgroundMaskLayer=[CAShapeLayer layer];
backgroundMaskLayer.path=dpath.CGPath;
backgroundLayer.mask=backgroundMaskLayer;
[backgroundLayer setContentsScale:[UIScreen mainScreen].scale];
[backgroundLayer setContentsGravity:kCAGravityResizeAspectFill];
[backgroundLayer setContents:(__bridge id)[UIImage maskImage:coverImage toPath:dpath].CGImage];
[self.layer.sublayers[0] addSublayer:backgroundLayer];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25446892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: The following code works in my IDE but fails to work in the online editor provided at hackerrank.com
Input Format
Every line of input will contain a String followed by an integer. Each String will have a maximum of 10 alphabetic characters, and each
integer will be in the inclusive range from 0 to 999.
Output Format
In each line of output there should be two columns: The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits;
if the original input has less than three digits, you must pad your
output's leading digits with zeroes.
Sample Input
java 100
cpp 65
python 50
Sample Output
================================
java 100
cpp 065
python 050
================================
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
StringBuilder sb=new StringBuilder();
int x=0,len=0;
System.out.println("================================");
for(int i=0;i<3;i++)
{
boolean bool = true;
while(bool){
sb=sb.append(sc.next());
len=sb.toString().length();
if(len>10) {
sb.delete(0,len);
System.out.println("Enter zero - ten character string");
}
else
bool = false;
}
bool= true;
while(bool){
x=Integer.parseInt(sc.next());
sc.nextLine();
int l= Integer.toString(x).length();
if(l>3) {
System.out.println("Enter zero - three digit number");
}
else
bool = false;
}
System.out.printf("%1$-16s %2$03d\n",sb,x);
sb=sb.delete(0,len);
}
System.out.println("================================");
}
}
A: You printed two extra space characters between each strings and numbers.
Try Replacing
System.out.printf("%1$-16s %2$03d\n",sb,x);
with
System.out.printf("%1$-15s%2$03d \n",sb,x);
Also you should remove the line sc.nextLine(); to avoid extra reading and causing an exceition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35931665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Java 8 thenApply() and thenAccept() I'm creating a demonstration example for chaining CompleteableFuture operations and I think I'm close but there's something I'm missing. Everything compiles except for the final "Build cakes in parallel" clause in main():
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.*;
import java.time.*;
// Use decorator pattern to build up the cake:
interface Cake_ {
String describe();
}
class Cake implements Cake_ {
private int id;
public Cake(int id) { this.id = id; }
@Override
public String describe() {
return "Cake " + id;
}
}
abstract class Decorator implements Cake_ {
protected Cake_ cake;
public Decorator(Cake_ cake) {
this.cake = cake;
}
@Override
public String describe() {
return cake.describe();
}
@Override
public String toString() {
return describe();
}
}
class Frosted extends Decorator {
public Frosted(Cake_ cake) {
super(cake);
}
@Override
public String describe() {
return cake.describe() + " Frosted";
}
}
class Decorated extends Decorator {
public Decorated(Cake_ cake) {
super(cake);
}
@Override
public String describe() {
return cake.describe() + " Decorated";
}
}
// For the cake-building assembly line:
class CreateCakes implements Supplier<Cake> {
private int id;
public CreateCakes(int id) {
this.id = id;
}
@Override
public Cake get() {
return new Cake(id);
}
}
class FrostCakes implements Function<Cake, Frosted> {
@Override
public Frosted apply(Cake cake) {
return new Frosted(cake);
}
}
class DecorateCakes implements Consumer<Frosted> {
public Decorated result;
@Override
public void accept(Frosted fc) {
result = new Decorated(fc);
}
}
public class Test {
public static int NUM_OF_CAKES = 20;
public static void main(String[] args) {
// Change from the default number of threads:
System.setProperty(
"java.util.concurrent.ForkJoinPool" +
".common.parallelism", "" + NUM_OF_CAKES);
// Test/demonstrate the decorator pattern:
List<Cake_> decorated =
IntStream.range(0, NUM_OF_CAKES)
.mapToObj(Cake::new)
.map(Frosted::new)
.map(Decorated::new)
.collect(Collectors.toList());
decorated.forEach(System.out::println);
// Build cakes in parallel:
List<CompletableFuture<?>> futures =
IntStream.range(0, NUM_OF_CAKES)
.mapToObj(id -> new CreateCakes(id))
.map(CompletableFuture::supplyAsync)
.thenApply(new FrostCakes())
.thenAccept(new DecorateCakes())
.collect(Collectors.toList());
futures.forEach(CompletableFuture::join);
}
}
I realize I'm missing some fundamental understanding in the definition of the futures list, but I've included it to show what I'm trying to accomplish here: a cake factory with portions of the cake-creation process running in parallel.
A: A quick answer to your question will be that the thenApply line doesn't compile because the result from the line above (map(CompletableFuture::supplyAsync)) returns Stream<CompletableFuture<Cake>> and not CompletableFuture<Cake>.
You'll need to do something like map(cakeFuture -> cakeFuture.thenApply(new FrostCakes())).
But I think there's a more important point that needs to be made.
If your examples are meant for educational purposes, I'd recommend investing another day or two in preparation, and more specifically in reading about the fundamentals of stream operations and CompletableFuture.
This way you'll feel much more confident when you get to present your material, but more importantly, you won't be presenting less than perfect code examples that can potentially harm your colleagues/students notion about how can streams and CompletableFutures (and even decorators) be used.
I'll point out some of the things that I think need to be redone in your examples.
*
*Manually setting the parallelism level of the common ForkJoinPool is not always a good idea. By default, it uses the number of processors, as returned by Runtime.availableProcessors() which is a pretty good default. You need to have a pretty good reason to change it to something more than that, because in most cases you'll just be introducing unnecessary overhead from scheduling and maintenance of redundant threads. And to change it to the number of tasks you're planning to fire is almost always a bad idea (explanation omitted).
*Your stream examples perform a couple of stream operations, then terminate with a collection, and then a stream operation is performed on the collected list. They can be rewritten without the collection to list, by directly applying the forEach on the stream returned by the last mapping, and arguably this will be a better demonstration of the fluent programming model using Java 8 streams.
*Your examples also don't perform their operations in parallel. You can fix that easily by adding .parallel() after IntStream.range(), but unless you remove the redundant collection to list from above, you won't be able to see that you've done something in parallel just by printing the list contents with forEach.
*Your classes implementing the java.util.function interfaces are not very idiomatic. I would argue that they should be replaced with the corresponding lambda expressions even though in your case this could result in a mouthful lambda in lambda, unless your second example is slightly rewritten.
*CompletableFuture.thenAccept returns a CompletableFuture<Void>, so in this stage of your stream processing you lose the references to the created, frosted and decorated cakes. This can be OK if you don't care about them, or if you log something about them in the decoration logic, but your example can easily mislead people that the finally collected list of CompletableFutures can be used to reach to the cakes (after all, who doesn't want to have his cake and eat it too).
So your first example can look something like
IntStream.range(0, NUM_OF_CAKES)
.parallel()
.mapToObj(Cake::new)
.map(Frosted::new)
.map(Decorated::new)
.forEach(System.out::println);
Notice how the cake IDs are not ordered because of the parallel execution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36377769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Adding slide effect by anchor tag I want to open another searchpage.html html page with slide effects for which i used anchor tag.
<a id="add" href="searchpage.html" class="show_hide">Click</a>
And js:
$(document).ready(function () {
$('.show_hide').click(function (e) {
e.preventDefault(); //to prevent default action of link tag
$(this).toggle('slide','left',100);
});
});
But its showing error:
TypeError: jQuery.easing[this.easing] is not a function
A: Try this one, this may help You..
HTML :
<a id="add" href="searchpage.html" class="show_hide">Click</a>
JS:
$(document).ready(function () {
$('.show_hide').click(function (e) {
e.preventDefault(); //to prevent default action of link tag
$('#add').slideToggle(1000);
});
});
And Here is Demo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30255637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: React Native - Sending text messages by phone i use fire base service. after wake up the app i need to send text message to users number by use device messaging, i install react-native-S M S but just work when on app and need to push user send button, can help me to send text message in background, thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62152090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to combine JSF togglePanel to trigger visibility of some other div/element/? I was looking through a number of websites, but i couldn't find out how to use a toggle panel to change the visibility of another element. Please see the example..
<rich:togglePanel switchType="client"
stateOrder="panelOneOff, panelOneOn">
<f:facet name="panelOneOff">
<rich:toggleControl>
<h:outputText value="Start"/>
</rich:toggleControl>
</f:facet>
<f:facet name="panelOneOn">
<rich:toggleControl switchToState="panelOneOff">
<h:outputText value="Close"/>
</rich:toggleControl>
</f:facet>
</rich:togglePanel>
<rich:effect name="hideDiv" for="toggleAccordingToTheTogglePanel" type="Fade" />
<rich:effect name="showDiv" for="toggleAccordingToTheTogglePanel" type="Appear" />
<div id="toggleAccordingToTheTogglePanel">
please show me on start and hide me on Close
</div>
What listeners will work to call the hideDiv() or showDiv() javascript functions so the DIV-Element at the end will appear or fade out?
update It be run on jboss 5.1 using richfaces 3.3.2
A: <rich:toggleControl onclick="hideDiv()">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3258162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL delete multiple criteria duplicate records I have a table with duplicate records in all but one field (col4 for ex). I just need to delete the duplicate entries where the t1.col4 field is blank.
ID Col1 Col2 Col3 Col4
1 Joe 1 2 Yes
2 Sue 1 2
3 Joe 2 3
4 Joe 1 2
Goal: Delete only ID 4
I have tried both the inner join (I don't think msaccess allows this) and WHERE EXISTS/IN techniques with errors.
Exists technique deletes all records where t1.col4 is null (not just ones matched in subquery):
DELETE t1.*
FROM t1
WHERE Exists (
SELECT t1.col1, t1.col2, t1.col3
FROM t1
Group by t1.col1, t1.col2, t1.col3
HAVING Count(*) > 1
)
AND t1.col4 Is Null;
I've tried multiple iterations of the Inner Join technique but everything I've read here suggests it is not supported in Access. Happy to post what I've tried if it helps. I've also tried writing the subquery to a temptable and then trying to delete records matched by the inner join.
A: You need a correlated subquery:
DELETE t1
FROM t1
WHERE EXISTS (SELECT t1.col1, t1.col2, t1.col3
FROM t1 as tt1
WHERE t1.col1 = tt1.col1 AND t1.col2 = tt1.col2 AND t1.col3 = tt1.col3 AND t1.id <> tt1.id
) AND
t1.col4 Is Null;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50030938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: updating a notification service from activity I have a notification service that starts when application is started
and there are 2 buttons in main activity, I want to update notification by clicking on each buttons, foreample if I touch start button, the text view in notification service should show: you touched start button and ..
I want to update notification from my activity
how should I do that?
here is my code:
public class MainActivity extends AppCompatActivity {
Button btn_start,btn_end;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
btn_end = (Button) findViewById(R.id.btn_end);
Intent serviceIntent = new Intent(MainActivity.this, NotificationService.class);
serviceIntent.setAction("startforeground");
startService(serviceIntent);
}
public class NotificationService extends Service {
Notification status;
public static int FOREGROUND_SERVICE = 101;
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("startforeground")) {
showNotification();
}
return START_STICKY;
}
private void showNotification() {
RemoteViews views = new RemoteViews(getPackageName(), R.layout.status_bar);
RemoteViews bigViews = new RemoteViews(getPackageName(), R.layout.status_bar_expanded);
status = new Notification.Builder(this).build();
status.contentView = views;
status.bigContentView = bigViews;
status.flags = Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.ic_launcher;
startForeground(FOREGROUND_SERVICE, status);
}
}
A: You have to use same way as you create one and then update it with whatever you need by using this method:
NotificationManagerCompat.notify()
Read the details here:
https://developer.android.com/training/notify-user/build-notification
You need to use the same Notification id for when creating and when updating.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50549376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Writing C# SDKs with dynamic responses and casting to a model For example;
I have a class called "User";
public class User
{
public string Name { get; set; }
public List<Job> Jobs { get; set; }
}
Awesome! Now, lets make a request to our REST API;
GET: api.com/users/123
RESPONSE:
{
name : "Erik",
jobs : [ { id : 1 }, { id: 2 } ]
}
Great! Now, lets do something fun with query strings and expand the jobs list.
GET: api.com/users/123?$expand=Jobs
RESPONSE:
{
name : "Erik",
jobs : [
{
id : 1,
name : "My Job",
address : "1515 My Street Rd. 20144, VA"
},
{
id : 2,
name : "My Job 2",
address : "9595 My Street Rd. 20144, VA"
}
]
}
But uh oh... We can't use the original User class. This is because the Job model looks like this;
public class Job
{
public int Id { get; set; }
}
So naturally, the JSON serializer doesn't know how to cast it's "expanded" response.
What are my options?
Can I override the Jobs property in the User class? Like;
public class UserWithExpandingJobs : User
{
public List<JobExpanded> Jobs { get; set; }
}
So that it is hides the initial inherited value and replaces it with a new Job model like this;
public class JobExpanded : Job
{
public string Name { get; set; }
public string Address { get; set; }
}
All this expanding is making my head hurt! It seems SO verbose.
Can anyone coach me through what I should be thinking or trying to do to minimize the SDK footprint.
Oh, btw... It's not letting me override Jobs because it is a different type. Thoughts?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24124255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Maven build not exporting dependent library's for packaging type jar I need to create a runnable jar file that will be operated in Batch mode.
During development I need to use following api/frameworks apache-poi,hibernate,Spring etc.
So,I prefer to go with maven:
Please find below my maven file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mypackage</groupId>
<artifactId>myartifact</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>fully.qualified.classpath.Main</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
I am running the maven build from eclipse as clean package.
Build completes successfully.But in the generated jar all the dependent jar
is not present [spring/hibernate/poi] etc.
We need to run this jar as java -jar jarname from command prompt/console.
A: Consider using Maven Shade Plugin.
This plugin provides the capability to package the artifact in an uber-jar, including its dependencies
Spring framework can do similar thing for you. Generate sample project and check its pom file.
A: maven-jar-plugin provides the capability to build jars without dependencies.
To create jar with all it's dependencies you can use maven-assembly-plugin or maven-shade-plugin. Below is maven-assembly-plugin configuration in pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>
fully.qualified.classpath.Main
</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
More information: executable-jar-with-maven
A: Try this out inside your pom.xml file:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/classes/lib</outputDirectory>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53407728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: A class rewritten with templates makes a program slower (in run-time) I have a class for a serial-memory 2D array that was initially an array of ints. Now that I need a similar array with another type, I've rewritten the class with templates; the only difference is in the type of stored objects:
template <class T>
class Serial2DArray
{
...
T ** Content;
}
I have a few test functions that deal with Content, for example, a one that nullifies all elements in the array (they're not class members, they're outside functions working with Serial2DArray<int> objects. I've noticed that now it works 1-2% slower - all the other code in the class is untouched, the only difference is that earlier it was just a regular class with int ** Content and now it's a template.
A sort of similar question: Do c++ templates make programs slow? - has opinions that only compilation becomes slower (and I can see why, the compiler generates classes for each that it finds in the code), but here I see the program becoming slower in run-time - is there any rational explanation?
Upd: issue narrowed down a little bit here: https://stackoverflow.com/a/11058672/1200000
Upd2: as mentioned in the comments, here's the function that became slower:
#include <windows.h>
#include <mmsystem.h>
...
int Size = G_Width * G_Height * sizeof(int);
DWORD StartTime = timeGetTime();
for(int i=0; i<100; ++i)
{
FillMemory(TestArray.Content[0], Size, 0);
}
MeasuredTime = timeGetTime() - StartTime;
And here's the actual class template:
#include <malloc.h>
template <class T>
class Serial2DArray
{
public:
Serial2DArray()
{
Content = NULL;
Width = 0;
Height = 0;
}
Serial2DArray(int _Width, int _Height)
{
Initialize(_Width, _Height);
}
~Serial2DArray()
{
Deinitialize();
}
T ** Content;
int GetWidth()
{
return Width;
}
int GetHeight()
{
return Height;
}
int Initialize(int _Width, int _Height)
{
// creating pointers to the beginning of each line
if((Content = (T **)malloc(_Height * sizeof(T *))) != NULL)
{
// allocating a single memory chunk for the whole array
if((Content[0] = (T *)malloc(_Width * _Height * sizeof(T))) != NULL)
{
// setting up line pointers' values
T * LineAddress = Content[0];
for(int i=0; i<_Height; ++i)
{
Content[i] = LineAddress; // faster than Content[i] =
LineAddress += _Width; // Content[0] + i * _Width;
}
// everything went ok, setting Width and Height values now
Width = _Width;
Height = _Height;
// success
return 1;
}
else
{
// insufficient memory available
// need to delete line pointers
free(Content);
return 0;
}
}
else
{
// insufficient memory available
return 0;
}
}
int Resize(int _Width, int _Height)
{
// deallocating previous array
Deinitialize();
// initializing a new one
return Initialize(_Width, _Height);
}
int Deinitialize()
{
// deleting the actual memory chunk of the array
free(Content[0]);
// deleting pointers to each line
free(Content);
// success
return 1;
}
private:
int Width;
int Height;
};
As requested, binaries size comparison.
Code with the following:
Serial2DArray<int> TestArray;
Serial2DArray<int> ZeroArray;
*
*1 016 832 bytes.
Code with the following:
Serial2DArray TestArray; // NOT-template class with ints
Serial2DArray ZeroArray; // methods are in class declaration
*
*1 016 832 bytes
Code with the following:
Serial2DArray<int> TestArray;
Serial2DArray<int> ZeroArray;
Serial2DArray<double> AnotherArray;
Serial2DArray<double> YetAnotherArray;
*
*1 017 344 bytes
A: Yeah- random benchmark variability, not to mention the fact that the whole program is slower might have nothing at all to do with this specific class.
A: Using templates in your container class may lead to the known issue of template code bloat . Roughly it could lead to more page fault in your program decreasing performance.
So why would you ask ? Because a template would generate the classes for each class instance of your template instead of one, leading to more pages in your binary product, more code pages if you prefer. Which could statistically lead to more page fault, depending on your run-time execution.
Have a look to the size of your binary with one class template instance, and with two instances which must be the heaviest. It will give you a grasp of the new code size introduced with the new instance.
Here is the wikipedia article on that topic: Code bloat article. The issue could be the same when forcing the compiler to inline every functions and methods in your program, if only it could be available with your compiler. The standard tries to prevent that with making the inline keyword a "request" that the compiler must not follow everytime. For instance GCC produces your code in an intermediate langage in order to evaluate if the resulting binary won't be lead to code bloat, and may discard the inline request as a result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11058431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why this functions duplicate data when scroll down to bottom page? Why this functions duplicate data when scroll down to bottom page ?
when scroll to bottom page sometime duplicate data.
<script type="text/javascript">
$(document).ready(function(){
$(window).scroll(function(){
var height = $('#demoajax').height();
var scroll_top = $(this).scrollTop();
var isload = $('#demoajax').find('.isload').val();
var page = $('#demoajax').find('.nextpage').val();
document.getElementById('check').value = page++;
if(($(window).scrollTop() + $(window).height() == $(document).height()) && (isload=='true')){
$('#loading').show();
$.ajax({
url: 'aaa.php',
type: 'POST',
data: $('#fid').serialize(),
cache: false,
success: function(response){
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$("#loading").fadeOut("slow");
$('#demoajax').append(response);
}
});
}
return false;
});
});
</script>
A: Did you mean sometimes the Ajax called more than one time, in that case you can busy flag. By default the busy flag set to false. Here is the code to do that
var busy = false;
if(($(window).scrollTop() + $(window).height() == $(document).height()) && (isload=='true'))
{
if(busy)
return;
busy = true;
$('#loading').show();
$.ajax({
url: 'aaa.php',
type: 'POST',
data: $('#fid').serialize(),
cache: false,
success: function(response)
{
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$("#loading").fadeOut("slow");
$('#demoajax').append(response);
},
complete: function()
{
busy = false;
}
});
}
return false;
});
});
I think this should solve the problem.
Thank You.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25830332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SSRS - 404 page not found I have a windows 2008 server running SSRS on SQL 2008. It is also a web server with Plesk installed.
I have been developing reports for this server for some time now on a development server. Everything is working fine on the development server. But I tried to move the reports to the live server and I get the error below:
Server Error
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
I am not sure why this is happening, because when I access the reports URL on its own it works fine. But as soon as I call the report in my web application hosted on the very same server I get this error. My application is written in c# and asp.net. Here is a section of code I use to access the report. Any help would be greatly appreciated:
string ExpId1 = Convert.ToString(Request.QueryString["Id"]).Trim();
string ExpId2 = ExpId1.Replace("@", "+");
Int32 ExpId3 = Convert.ToInt32(qsc.decryptQueryString(ExpId2));
string id=ExpId3.ToString();
ReportViewer1.Width = 1050;
ReportViewer1.Height = 600;
ReportViewer1.Style.Add("Overflow", "Scroll");
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
IReportServerCredentials irsc = new CustomReportCredentials("user", "password", "server");
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
ReportParameter[] para = new ReportParameter[2];
para[0] = new ReportParameter();
para[0].Name = "ExpHearderId";
para[0].Values.Add(id);//any value
para[1] = new ReportParameter();
para[1].Name = "ExpHeadreId";
para[1].Values.Add(id);//any value
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://xxx.xxx.xxx.xxx/reportserver_TGO");
string path=Server.MapPath("~/ReportingofUsers/ExpenseClaimReport");
ReportViewer1.ServerReport.ReportPath = path;
ReportViewer1.ServerReport.SetParameters(para);
ReportViewer1.ShowParameterPrompts = false;
ReportViewer1.ServerReport.Refresh();
ReportViewer1.Visible = true;
A: This should help: http://otkfounder.blogspot.com/2007/11/solving-reportviewer-rendering-issue-on.html
EDIT: One more thing. I'm pretty sure that when you use Reports Server you should not use Server.MapPath. Just specify the path as you see it in Reports Server, in your case: /ReportingofUsers/ExpenseClaimReport. That is assuming that you publish reports to the server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6343534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bypassing Controller in Rails Im using Rails 2.3.5 and I have a model, let's call it Post. I used named scopes to apply different kinds of sorts on Post. For example, in the Post model I have possibility to rank posts by its scores:
named_scope :order_by_acception_rate_desc,
Proc.new { |limit| { :limit => limit, :order => "acception_rate desc" } }
In the Post Controller I have:
def best
@best_posts = Post.order_by_acception_rate_desc(10)
end
In the view I just render this collection @best_posts:
<%= render :partial => "post", :collection => @best_posts
Currently my application is working like that, but actually I do not need to have the method "best" in the Controller, and I could move it to the Model Post doing like:
def self.best
self.order_by_acception_rate_desc(10)
end
and then in the view I would render the collection like:
<%= render :partial => "post", :collection => Post.best
I do not know which approach is better, but using the ranking methods in the Model, I could avoid to create routes for each one of ranking methods. What approach is better, is there any better approach than these?
A: with according to Rails conventions the logic should be separated,
*
*controllers handle permissions, auth/authorization, assign instance/class variables
*helpers handle html logic what to show/hide to user
*views should not provide any logic, permissions check. think about it from designer's point of view
*models handle data collection/manipulation over ORM
I'd like to ask you to try:
#helper
def self.best(limit)
all(:limit => limit, :order => "acception_rate desc")
end
#controller
@best_posts = Post.best
#view
<%= render :partial => "post", :collection => @best_posts %>
A: You should not bypass the controller and include much logic in your view.
You could keep a single route and filter the Post model depending on one of the params.
You don't tell enough here to answer more clearly but you have the big picture.
A: You can leave just the view file and it should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6713719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Server Reporting Services 2008 R2 Express Edition "Report Builder" Button How do I enable the "Report Builder" button on SQL Server Reporting Services (Report Manager Web View).
I am using the 2008 R2 Express Edition.
Is this available in this edition ??
Thanks.
A: I don't believe that it's possible. If you compare Express to Standard, expand the Reporting node, you will see Model Support is unchecked for Express. Report Builder 1.0 only worked on prebuilt models so by extension, I'm assuming that bullet continues to address models and the report builder.
I never install Express so I can't dig around and verify it.
If the Report Builder button is not showing, verify the accessing account has Report Builder role or better. Predefined SSRS Roles in 2008 R2
A: I can confirm that this feature is not available in the express edition - you will also not be able to create a report model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7916243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Using Formula Language to return column values I'm trying to return all values stored in the tNames variable.
Values exists in the field. The show multivalues as separate entries have been selected already but none of the names is returned.
Below is the sample code:
tNames := "";
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
tNames := tNames + ", " + @Implode(@GetField("ChecklistContact_" +
@Text(n));",")
);
@Trim(tNames)
I dont know why its not returning anything, will appreciate your help.
The below returns only the contact with index 0, but I want to return all contacts in each document.
tCount := 0;
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
tCount := tCount + @If(@GetField("ChecklistContact_" + @Text(n)) = ""; 0; 1)
);
@GetField("ChecklistContact_" + @Text(tCount))
Following comments from Richard the below return the required values, but will prefer not to hard code field name.
Is there any way of using for loop to return field names and values?
tNames := "";
tNames:= @GetField("ChecklistContact_1") : @GetField("ChecklistContact_2") : ... @GetField("ChecklistContact_7");
@Trim(tNames)
A: I don't believe that IBM's documentation says this explicitly, but I don't think @GetField works in column value formulas. The doc says that it works in the "current document", and there is no current document when the formula is executing in a view.
Assuming you know what the maximum number for N is, the way to do this is with a simple list:
ChecklistContact_1 : ChecklistContact_2 : ChecklistContact_3 : ... : ChecklistContact_N
If N is large, this will be a lot of typing, but you'll only have to do it once and copying and pasting and editing the numbers will make it go pretty quickly.
A: It might sound inelegant but, if you can, create a new computed field with your column formula in your form and then use that new field in your column. Also, from a performance standpoint you will be better off.
A: Maybe use your loop to create the list of fieldnames as Richard suggested, then display tNames
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47360865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Scala: expression's type is not compatible with formal parameter type trait Ingredient{}
case class Papperoni() extends Ingredient{}
case class Mushroom() extends Ingredient{}
trait ToppingDef[T] {
}
object PepperoniDef extends Serializable with ToppingDef[Papperoni] {
}
object MushroomDef extends Serializable with ToppingDef[Mushroom] {
}
class Oven[T <: Ingredient](val topping:ToppingDef[T]) {
}
class Pizza {
def cook = {
val topping =
if(someCondition()) { PepperoniDef }
else { MushroomDef}
new Oven(topping) // <-- build error here
}
}
I am using Scala 2.11. This example is somewhat contrived but I’ve stripped out everything unrelated to the problem to provide a concise example.
The error I get on the last line is:
Error:(26, 5) no type parameters for constructor Oven: (topping: ToppingDef[T])Oven[T] exist so that it can be applied to arguments (Serializable with ToppingDef[_ >: Papperoni with Mushroom <: Product with Serializable with Ingredient])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : Serializable with ToppingDef[_ >: Papperoni with Mushroom <: Product with Serializable with Ingredient]
required: ToppingDef[?T]
new Oven(topping)
However changing the last line to this for example:
new Oven(PepperoniDef)
builds fine. So the compiler has no problem finding the type when the parameter is passed explicitly like this.
Also, removing the Serializable trait from PepperoniDef and MushroomDef like this:
object PepperoniDef extends ToppingDef[Papperoni] {
}
object MushroomDef extends ToppingDef[Mushroom] {
}
also builds. However in my case I need the Serializable.
I think I can probably restructure the code to work around this if necessary but I would like to understand what's going on, I don't know why the type is ambiguous in the first case, or why the presence of the Serializable trait has any effect. Thanks in advance for any insights.
EDIT: Thank you for the replies, very helpful. I think the most concise fix is to change this:
val topping =
to this:
val topping:ToppingDef[_ <: Ingredient] =
Which cures the build error and does not require a change to the generic classes, which I would like to keep as simple an unannotated as possible so as to have Scala infer as much type information as possible.
This doesn't answer the question of why the presence of Serializable has any effect on this.
A: It seems that helping the compiler out with type annotation makes this compile:
val topping: ToppingDef[
_ >: Papperoni with Mushroom <: Ingredient with Product with Serializable] =
if (true) {
PepperoniDef
} else {
MushroomDef
}
I don't think this has to do with the Serializable class specifically, it seems like a compiler quirk to me since the produced type has a mixed in type including Product with Serializable anyway.
You can also "relax" the type signature by making T covariant, meaning Topping[Ingredient] will be inferred. This happens because the "is subtype of" relation Papperoni <: Ingredient on a covariant ToppingDef[+T] means ToppingDef[Papperoni] <: ToppingDef[Ingredient], thus allowing the common supertype for T:
trait ToppingDef[+T]
val topping: ToppingDef[Ingredient with Product with Serializable] =
if (true) {
PepperoniDef
} else {
MushroomDef
}
And this also compiles without type annotation.
Edit:
Making Ovens type parameter an existential instead of a universally quantified type seems to work as well with the Serializable trait:
class Oven[_ <: Ingredient](val topping: ToppingDef[_])
val topping: Serializable with ToppingDef[_ <: Ingredient] =
if (true) {
PepperoniDef
} else {
MushroomDef
}
new Oven(topping)
A: You need to add some type information to your trait:
trait ToppingDef[+T <: Ingredient] {}
Right now the topping variable is not able to figure out that T is supposed to be an Ingredient so you need to tell it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45462849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Pass string array to PHP script as POST I am trying to pass a string array to a PHP script as POST data in an Android app but i have an issue.
this is my client side code:
ArrayList<NameValuePair> querySend = new ArrayList<NameValuePair>();
for (Stop s : stops) {
querySend.add(new BasicNameValuePair("stop_data[]", s.getNumber()));
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myURL/myPHPScript.php");
httppost.setEntity(new UrlEncodedFormEntity(querySend));
HttpResponse response = httpclient.execute(httppost);
and this is my PHP script code:
foreach($_GET['stop_data'] as $stop) {
// do something
}
If i run my java code i will get this response error from php script:
Warning: Invalid argument supplied for foreach() in /web/htdocs/www.myURL/myPHPScript.php on line 6
null
otherwise if i will put the request on my browser manully in this way:
http://www.myURL/myPHPScript.php?stop_data[]=768&stop_data[]=1283
i will give the correct answer!
if i try the same code, but if i POST not an array but a single string passing and receiving stop_data variables without [] it works!
I can't understand where is the mistake!! It is possible that the [] in BasicNameValuePair String name are doing some codification mistaken? I need to pass an array, how i have to do?
A: you use POST method and in php code you should use $_POST
try this
foreach($_POST['stop_data'] as $stop) {
// do something
}
this way is using GET method
http://www.myURL/myPHPScript.php?stop_data[]=768&stop_data[]=1283
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20031940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create a .htaccess file with the code for clean url I want to create clean url, so I tried many configurations. I also created an .htaccess file but it does not work. Anyone can help me?
My .htaccess code
Options +FollowSymLinks
RewriteEngine on
RewriteRule single-post/id/(.*)/title/(.*)/ single-post.php?id=$1&title=$2
RewriteRule single-post/id/(.*)/title/(.*) single-post.php?id=$1&title=$2
Present url
http://localhost/just2minute/story/single-post/id/2590/title/%E0%A4%95%E0%A5%87%E0%A4%B0%E0%A4%B2%20%E0%A4%AE%E0%A5%87%E0%A4%82%20%E0%A4%AC%E0%A4%BE%E0%A4%B0%E0%A4%BF%E0%A4%B6%20%E0%A4%94%E0%A4%B0%20%E0%A4%B2%E0%A5%88%E0%A4%82%E0%A4%A1%E0%A4%B8%E0%A4%B2%E0%A4%BE%E0%A4%87%E0%A4%A1%20%E0%A4%B8%E0%A5%87%2018%20%E0%A4%B2%E0%A5%8B%E0%A4%97%E0%A5%8B%E0%A4%82%20%E0%A4%95%E0%A5%80%20%E0%A4%AE%E0%A5%8C%E0%A4%A4/
I want to create"
http://localhost/just2minute/story/single-post/id/(Any Value)/title/(Any Value)/
A: You do not need two rules. You can achieve the goal using one rewrite rule, for example,
RewriteRule ^story/single-post/id/([0-9]+)/title/([0-9a-zA-Z-]+)/?$ single-post.php?id=$1&title=$2
After that you can access with the URL like this
https://localhost/just2minute/story/single-post/id/51835322/title/create-a-htaccess-file-with-the-code-for-clean-url
Then you want to do something like explained in this article:
https://www.tinywebhut.com/remove-duplicate-urls-from-your-website-38
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51835322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Modify path name when saving with PIL I am extracting RGB channels from images and saving them as grayscale png files, but I have trouble saving them. Here is my code:
listing = os.listdir(path1)
for f in listing:
im = Image.open(path1 + f)
red, green, blue = im.split()
red = red.convert('LA')
green = green.convert('LA')
blue = blue.convert('LA')
red.save(path2 + f + 'r', 'png')
green.save(path2 + f + 'g', 'png')
blue.save(path2 + f + 'b','png')
Where path1 and path2 are image folder and save destinations respectively. What I want to do is to save the b&w version of color channel of img.png to
imgr.png, imgg.png, imgb.png, but what I get with this code is img.pngr, img.pngg, img.pngb. Any help would be appreciated.
A: You first need to split the filename from the extension.
import os
filename = path2 + f # Consider using os.path.join(path2, f) instead
root, ext = os.path.splitext(filename)
Then you can combine them correctly again doing:
filename = root + "r" + ext
Now filename would be imgr.png instead of img.pngr.
A: You could do this as follows:
import os
listing = os.listdir(path1)
for f in listing:
im = Image.open(os.path.join(path1, f))
red, green, blue = im.split()
red = red.convert('LA')
green = green.convert('LA')
blue = blue.convert('LA')
file_name, file_ext = os.path.splitext(f)
red.save(os.path.join(path2, "{}r.png".format(file_name))
green.save(os.path.join(path2, "{}g.png".format(file_name))
blue.save(os.path.join(path2, "{}b.png".format(file_name))
I would recommend you make use of the os.path.split() and os.path.join() functions when working with paths and filenames.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42646343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Putting $scope in Cytoscape click event I have created a network graph using Cytoscapejs. I am trying to unhide a div, and load more things after the user click on edge of the graph.
I have the following in my controller:
CytoscapeService.getGraph().on('tap', 'edge[id = "123"]', function (event) {
console.log("Hi")
//Above console printout works.
//The below does not work on index.html
$scope.testMessage = "Hello World";
$scope.showMe = function () {
$scope.show = true;
}
$scope.showMe();
});
// This works though.
//$scope.testMessage = "Hi from outside";
And in Index.html:
<div ng-controller="MainCtrl" class="container" ng-show="show">
</div>
<div ng-controller="MainCtrl">
{{testMessage}}
</div>
The console.log does get print out but the $scope.showMe with function inside isn't being called. However, if I move the scope outside of this clause, into the main clause of the Controller, it works.
Any there alternatives on how I can achieve this?
A: This is common with angular when you are using jquery events to update a $scope value. You will have to manually triger a $scope apply:
$scope.$apply(function(){
$scope.show = true;
});
Another solution would be to use Angular's $timeout
$timeout(function () {
$scope.show = true;
});
See the documentation for $scope.apply() and more scope information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38673700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flex how to format a date string when it could be two different formats I have a date field in flex and have the format set to YYYY-MM-DD. As long as the user clicks the calendar pop-up it set's it that way.
However, I need to allow the field to be human enter-able so they can type in a date.
The problem is, most users want to type the format MM/DD/YYYY. I have a tool tip that shows the format, but how can I check the format and change it to the YYYY-MM-DD format, or do something else appropriate (alert?)?
A: Easy enough:
DateFormatter.parseDate(yourString);
As long as your string is somewhat of a standard format, it should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6230123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to use for loop in a JButton public void init(GUI gui){
// the class extends Jframe
gui.setSize(1024, 700);
gui.setPreferredSize(new Dimension(1024, 700));
gui.setResizable(false);
gui.setLocationRelativeTo(null);
gui.setTitle("Student Management System");
gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
Admin_AllStudents_pnl=new JLayeredPane();
Admin_AllStudents_pnl.setSize(1024,700);
Admin_AllStudents_pnl.setLayout(null);
Admin_AllStudents_pnl.setVisible(false);
Admin_AllStudents_pnl.setOpaque(true);
// Admin_AllStudents_pnl.setBackground(Color.white);
String col[]={"ID","Name","Password","Cell","Adress"};
DefaultTableModel tablemodel=new DefaultTableModel(col,0);
All_Students=new JTable(tablemodel);
view_all=new JButton("View_All");
Admin_AllStudents_pnl.add(view_all);
view_all.setBorder(null);
view_all.setBounds(10,10,view_all.getPreferredSize().width,view_all.getPreferredSize().height);
view_all.addActionListener(new ActionListener(){
@Override
// Student and admin are both classes s gets an array list from the admin of all //the students.
//i need to display them in a table format so using for loop.
public void actionPerformed(ActionEvent ae) {
ArrayList<Student> s=new ArrayList<>();
s=admin.AllStudent();
System.out.println("size of s arraylist"+s.size());
for(int i=0;i<s.size();i++)
{
String Ids=s.get(i).getId();
String names=s.get(i).getName();
String passwords=s.get(i).getPass();
String cells=s.get(i).getCell();
String adresss=s.get(i).getAdress();
Object[] data={Ids,names,passwords,cells,adresss};
tablemodel.addRow(data);
}
}
});
Admin_AllStudents_pnl.add(All_Students);
gui.add(Admin_AllStudents_pnl);
only the for loop is not working whole code works fine without for loop every variable is already declared the code is about of 1000 lines so i cant upload all of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43526367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: System.Net.WebException on YoutubeExtractor when downloading a video Environment
*
*Windows 8.1
*Visual Studio 2017 Community
*C#
*WPF application
Issue
*
*YoutubeExtractor throws System.Net.WebException when downloading a video.
I got YoutubeExtractor by Nuget and it doesn't work. The VideoInfo object isn't null. I tried several videos on Youtube and the same exceptions popped up. I googled the issue and it didn't give me much help.
Here's the code.
var videos = DownloadUrlResolver.GetDownloadUrls(@"https://www.youtube.com/watch?v=M1wLtAXDgqg");
VideoInfo video = videos
.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
if (video.RequiresDecryption)
DownloadUrlResolver.DecryptDownloadUrl(video);
var videoDownloader = new VideoDownloader(video, System.IO.Path.Combine("D:", video.Title + video.VideoExtension));
videoDownloader.DownloadProgressChanged += (sender_, args) => Console.WriteLine(args.ProgressPercentage);
videoDownloader.Execute(); // I got the exception here.
How can I solve this issue? Thanks.
EDIT : 2017/10/26 13:42 GMT
Alexey 'Tyrrrz' Golub's answer helped so much! I corrected his original code and here it is.
using YoutubeExplode;
using YoutubeExplode.Models.MediaStreams;
var client = new YoutubeClient();
var video = await client.GetVideoAsync("bHzHlSLhtmM");
// double equal signs after s.VideoQuality instead of one
var streamInfo = video.MuxedStreamInfos.First(s => s.Container == Container.Mp4 && s.VideoQuality == VideoQuality.Medium360);
// "D:\\" instead of "D:"
var pathWithoutExtension = System.IO.Path.Combine("D:\\", video.Title);
// streamInfo.Container.GetFileExtension() instead of video.VideoExtension (video doesn't have the property)
var path = System.IO.Path.ChangeExtension(pathWithoutExtension, streamInfo.Container.GetFileExtension());
// new Progress<double>() instead of new Progress()
await client.DownloadMediaStreamAsync(streamInfo, path, new Progress<double>(d => Console.WriteLine(d.ToString("p2"))));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46502734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: kotlin whereNotEqualTo doesn't work for a field that has null value in firestore
BJ document has a null value of the capital field which should have not taken by whereNotEqualTo
val citiesRef = db.collection("cities").whereNotEqualTo("capital", true)
try {
val documents = citiesRef.get().await()
for (document in documents){
Log.d(TAG,"${document.data}")
}
}catch (e:Throwable){
Log.d(TAG,e.message.toString())
}
This code is not working despite the documentation saying that
Note that null field values do not match != clauses, because x != null evaluates to undefined.
but after I altered the null value with true or false doesn't matter which one is chosen, the code works well. can somebody explain to me what is the problem I encountered?
A: When you are using the following query:
val citiesRef = db.collection("cities").whereNotEqualTo("capital", true)
It means that you are trying to get all documents in the cities collection where the capital field holds the opposite value of the Boolean true, which is false. So you'll only get the documents where the capital field holds the value of false. The above query is the same with:
val citiesRef = db.collection("cities").whereEqualTo("capital", false)
Since null, is not the negation of true, the documents that have the capital field set to null, won't be returned. And it makes sense since null is not a boolean type, not a string type, nor any other supported data types. Null represents "none" or "undefined" and it's a distinct data type and cannot be considered "not equal" to any other data type.
That's the same as the docs states:
Note that null field values do not match != clauses
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71310643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create mobile, tablet, desktop viewable web template I want to create same category two templates. First one for tablet, laptop and desktop viewable to any screen size and second one for mobile viewable to any screen size.
How can I create all device (mobile, tablet, laptop and desktop any screen size) viewable template?
I searched last two week in google to find out the above question answer but I unfortunately I don’t find any useful link. So please, anyone can help me giving above question answer (any useful link or details description). Thanks
A: Those kind of templates are really hard to find unless u pay fo them.
Just have a look on this :
http://mobile.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16457986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Get all changed files in a changest I want to get all the changed file in a changeset but without having the letter that specify the change type.
I know this command
hg status --change changeset
However, this return result like,
A /path/to/file
M /path/to/file
I want the result to be
/path/to/file
without "A" or "M". I tried to do it with regular expression and it used to work but I don't know it didn't work in one scenario.
The regular expression,
/(?<=[MA]\s).+/
This the scenario that did not work
arwa/Documents/Projects/firefox/M db << notice M here.
Any thought?
A: You should add ^ (start of line) to your regex:
/(?<=^[MA]\s).+/
If you don't do that, (?<=[MA]\s) will lookabehind the M part and .+ will catch db.
A: As of Mercurial 3.5, you can use templates (still an experimental feature, you can see it with hg help status -v). Namely:
hg status --change <rev> --template '{path}\n'
A: Why not use log with template?
hg log -r CSET -T "{files % '{file}\n'}"
will produce clean output
lang/UTF-8/serendipity_lang_ru.inc.php
plugins/serendipity_event_bbcode/UTF-8/lang_ru.inc.php
plugins/serendipity_event_emoticate/UTF-8/lang_ru.inc.php
plugins/serendipity_event_karma/UTF-8/lang_ru.inc.php
plugins/serendipity_event_s9ymarkup/UTF-8/lang_ru.inc.php
plugins/serendipity_plugin_shoutbox/UTF-8/lang_ru.inc.php
contrary to templated status
'lang\UTF-8\serendipity_lang_ru.inc.php
''plugins\serendipity_event_bbcode\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_emoticate\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_karma\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_s9ymarkup\UTF-8\lang_ru.inc.php
''plugins\serendipity_plugin_shoutbox\UTF-8\lang_ru.inc.php
'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32148545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: App closes upon using BACKSPACE or SHIFT button in an EditText view When using the BACKSPACE or SHIFT of the onscreen keyboard to edit text in EditText views, my app closes (didn't have this problem before). It is possible to type in text, but as soon as I use BACKSPACE or SHIFT, the app closes.
Logcat gives the following alerts:
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
Line 106 of Handler.java reads as follows;
handleMessage(msg);
Line 214 of Looper.java reads as follows;
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart,
dispatchEnd, "dispatch", msg);
}
What action should I take to remedy this? Here is the full Logcat
2019-09-09 16:46:12.416 13560-13560/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-09-09 16:46:12.417 13560-13560/? E/Zygote: accessInfo : 1
2019-09-09 16:46:23.608 13560-13560/com.commonsense.android.doorway E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.commonsense.android.doorway, PID: 13560
java.lang.NoSuchMethodError: No static method dispatchUnhandledKeyEventPre(Landroid/view/View;Landroid/view/KeyEvent;)Z in class Landroid/support/v4/view/ViewCompat; or its super classes (declaration of 'android.support.v4.view.ViewCompat' appears in /data/app/com.commonsense.android.doorway-4nmhQXtmyOPwFjuoPHsunQ==/base.apk)
at android.support.v7.app.AppCompatDelegateImpl.dispatchKeyEvent(AppCompatDelegateImpl.java:1162)
at android.support.v7.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2529)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:590)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:6094)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5949)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5402)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5455)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5421)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:5580)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5429)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5637)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5402)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5455)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5421)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5429)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5402)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:8467)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:8387)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:8340)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:5039)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7094)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
And this is the build.gradle file. Android Studio says that mixing versions (like 28.0.0) in the dependencies can lead to bugs. Apparently they schould all be the same version. Could this be the problem source?
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.commonsense.android.doorway"
minSdkVersion 25
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.android.support:wear:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:design:28.0.0-alpha3'
compileOnly 'com.google.android.wearable:wearable:2.4.0'
}
When I detach the EditText views from their editText = findViewBy(R.id.editText), the error stops. But then of course the EditText views have become useless.
A: In the build.gradle file, I deleted implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'. Android Studio had warned in uncertain terms (as usual) that putting different versions in the dependencies "might produce some bugs". The said dependency was the first that could be deleted without causing any compile errors. And waddayou know, the backspace/shift bug disappeared immediately...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57856122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Default Value Containing Special Characters in HTML Form I was trying to get a symbol like ® to be a default value for a text field,
I am trying to set the default by a javascript , but all i get is ® or &® in the text box, i am doing this from script as i am using drupal , so i dont have html files , i even trie ddefault value option in hook_form()
A: I'm not clear on what exactly you're trying to do; maybe something like this?
// set the default value of yourTextField
yourTextField.defaultValue = '\u00AE';
// or set the actual value of yourTextField
yourTextField.Value = '\u00AE';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3726130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make a table in ebook file I wanna make a book with parallel translation. It supposed to have table with to columns - one have text on source language, the other on target language.
I found, that I can do it easy with fb2, just write a xml code by python script. But my ebook read it ugly - the first column much wider than the second. (see picture)
Code example:
<section><table>
<tr>
<td> Lang1 </td>
<td> Lang2 </td>
</tr>
<tr>
... the same ...
</tr>
</table></section>
I don't work with web design, and maybe dont understand some simple thing. How can I set size of columns? Or maybe I should use some other format (epub)
It essential, that I need format, which I can read on ebook comfortable. Books in PDF format are bad for this, cause I can't change font and don't want zoom.
Thanks for you answers!
A: FB2 Supports reflow by design which is the reason for poor table support in many ebook readers as two column is contra the basic reflow principle.
Thus HTML can support tables but are not always "expected" nor supported well in many ebook readers.
Daisy epubtest "basic" did not include tables ! But they are tested in Accessibility: Non-visual Reading. Adobe fails the visual display by not adjusting the 4 cell contents to fit device, and fails on navigation.
MuPDF show the table as one column with cells reflowing to fit the page width, Calibre uses varying width columns but can also have issues.
If you need a fixed layout, then PDF was designed to maintain page layout, Thus the answer is probably use PDF with a page column and font size targeted to suit a pocket book such as A6, two column, no margins, 6pt.
If it is for your own use only, then ebook format targeted for your device, may well work if the columns are fixed to half screen width.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69232810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Java Enumeration vs Iterator Enumeration doesn't throw ConcurrentModificationException , why?
See below code .
public static void main(String[] args) {
Vector<String> v=new Vector<String>();
v.add("Amit");
v.add("Raj");
v.add("Pathak");
v.add("Sumit");
v.add("Aron");
v.add("Trek");
Enumeration<String> en=v.elements();
while(en.hasMoreElements())
{
String value=(String) en.nextElement();
System.out.println(value);
v.remove(value);
}
}
It only prints :
Amit
Pathak
Aron
Why is this such behavior . Can we say that Enumerator is thread safe.
Edit: When working with Iterator it throws ConcurrentModificationException in single thread application.
public static void main(String[] args) {
Vector<String> v=new Vector<String>();
v.add("Amit");
v.add("Raj");
v.add("Pathak");
v.add("Sumit");
v.add("Aron");
v.add("Trek");
Iterator<String> it=v.iterator();
while(it.hasNext())
{
String value=(String) it.next();
System.out.println(value);
v.remove(value);
}
}
Please check.
A:
Enumeration doesn't throw ConcurrentModificationException , why?
Because there is no path in the code being invoked which throws this exception. Edit: I am referring to the implementation provided by the Vector class, not about the Enumeration interface in general.
Why is this such behavior . Can we say that Enumerator is thread safe.
It is thread-safe in a sense that the code executed is properly synchronized. However, I don't think the result your loop yields is what you would except.
The reason for your output is that the Enumeration object maintains a counter, which is incremented after every invokation of nextElement(). This counter is not aware of your invokation of remove().
A: the fail-fast behaviour which throws the ConcurrentModificationException is only implemented for the Iterator as you can read in
http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html
A: Concurrent modification here has nothing to do with threads.
Concurrency here simply means that you are modifying the collection while you are iterating over it. (In your example this happens in the same thread.)
Iterators and enumerations of collections can throw ConcurrentModificationException in this case, but don't have to. The ones that do exhibit fail-fast behaviour. Apparently, the enumeration of Vector isn't fail-fast.
Thread-safety obviously involves multiple threads somehow. Vector is thread-safe only in the sense that its operations (like add, get, etc.) are synchronized. This is to avoid non-deterministic behaviour when one thread is adding an element while at the same time another thread is trying to remove one for example.
Now, when one thread is structurally modifying your collection while another thread is iterating over it, you have to deal with both thread-safety and concurrent modification issues. In this case, and probably in general, it is safest not to rely on ConcurrentModificationException being thrown. It is best to choose the appropriate collection implementation (a thread-safe one for example) and avoid/disallow concurrent modification yourself.
Some iterators allow adding/setting/removing elements through the iterator itself. This can be a good alternative if you really need concurrent modification.
A: Note that ConcurrentModificationException has nothing to do with concurrency in the sense of multithreading or thread safety. Some collections allow concurrent modifications, some don't. Normally you can find the answer in the docs. But concurrent doesn't mean concurrently by different threads. It means you can modify the collection while you iterate.
ConcurrentHashMap is a special case, as it is explicitly defined to be thread-safe AND editable while iterated (which I think is true for all thread-safe collections).
Anyway, as long as you're using a single thread to iterate and modify the collection, ConcurrentHashMap is the wrong solution to your problem. You are using the API wrongly. You should use Iterator.remove() to remove items. Alternatively, you can make a copy of the collection before you iterate and modify the original.
EDIT:
I don't know of any Enumeration that throws a ConcurrentModificationException. However, the behavior in case of a concurrent modification might not be what you expect it to be. As you see in you example, the enumeration skips every second element in the list. This is due to it's internal index being incremented regardless of removes. So this is what happens:
*
*en.nextElement() - returns first element from Vector, increments index to 1
*v.remove(value) - removes first element from Vector, shifts all elements left
*en.nextElement() - returns second element from Vector, which now is "Pathak"
The fail-fast behavior of Iterator protects you from this kind of things, which is why it is generally preferable to Enumberation. Instead, you should do the following:
Iterator<String> it=v.iterator();
while(it.hasNext())
{
String value=(String) it.next();
System.out.println(value);
it.remove(); // not v.remove(value); !!
}
Alternatively:
for(String value : new Vector<String>(v)) // make a copy
{
String value=(String) it.next();
System.out.println(value);
v.remove(value);
}
The first one is certainly preferable, as you don't really need the copy as long as you use the API as it is intended.
A: Short answer: It's a bonus feature that was invented after enumeration was already there, so the fact that the enumerator does not throw it does not suggest anything particular.
Long answer:
From wikipedia:
Collection implementations in pre-JDK 1.2 [...] did not contain a
collections framework. The standard methods for grouping Java
objects were via the array, the Vector, and the Hashtable classes,
which unfortunately were not easy to extend, and did not implement a
standard member interface. To address the need for reusable
collection data structures [...] The
collections framework was designed and developed primarily by Joshua
Bloch, and was introduced in JDK 1.2.
When the Bloch team did that, they thought it was a good idea to put in a new mechanism that sends out an alarm (ConcurrentModificationException) when their collections were not synchronized properly in a multi-threaded program. There are two important things to note about this mechanism: 1) it's not guaranteed to catch concurrency bugs -- the exception is only thrown if you are lucky. 2) The exception is also thrown if you misuse the collection using a single thread (as in your example).
So, a collection not throwing an ConcurrentModificationException when accessed by multiple threads does not imply it's thread-safe either.
A: It depends on how you get the Enumeration. See the following example, it does throw ConcurrentModificationException:
import java.util.*;
public class ConcurrencyTest {
public static void main(String[] args) {
Vector<String> v=new Vector<String>();
v.add("Amit");
v.add("Raj");
v.add("Pathak");
v.add("Sumit");
v.add("Aron");
v.add("Trek");
Enumeration<String> en=Collections.enumeration(v);//v.elements();
while(en.hasMoreElements())
{
String value=(String) en.nextElement();
System.out.println(value);
v.remove(value);
}
System.out.println("************************************");
Iterator<String> iter = v.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
iter.remove();
System.out.println(v.size());
}
}
}
Enumeration is just an interface, it's actual behavior is implementation-dependent. The Enumeration from the Collections.enumeration() call wraps the iterator in someway, so it's indeed fail-fast, but the Enumeration obtained from calling the Vector.elements() is not.
The not-fail-fast Enumeration could introduce arbitrary, non-deterministic behavior at an undetermined time in the future. For example: if you write the main method as this, it will throw java.util.NoSuchElementException after the first iteration.
public static void main(String[] args) {
Vector<String> v=new Vector<String>();
v.add("Amit");
v.add("Raj");
v.add("Pathak");
Enumeration<String> en = v.elements(); //Collections.enumeration(v);
while(en.hasMoreElements())
{
v.remove(0);
String value=(String) en.nextElement();
System.out.println(value);
}
}
A: remove the v.remove(value) and everything will work as expected
Edit: sorry, misread the question there
This has nothing to do with threadsafety though. You're not even multithreading so there is no reason Java would throw an exception for this.
If you want exceptions when you are changing the vector make it Unmodifiable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10880137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Access DataGridTemplateColumn content I have a WPF DataGrid templatecolumn that has a DataTemplate for an AutoCompleteBox from the wpf toolkit. During RowEditEnding event and validation procedures, I am not able to see the content in the templatecolumn.
<DataGridTemplateColumn Header="Account Type" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<toolkit:AutoCompleteBox Text="{Binding Path='Account Type'}" Populating="PopulateAccountTypesACB" IsTextCompletionEnabled="True" BorderThickness="0" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if ((value as BindingGroup).Items.Count == 0)
return new ValidationResult(true, null);
DataRowView row = (value as BindingGroup).Items[0] as DataRowView;
if (row != null)
{
if (ValidateAccountName(row.Row.ItemArray[0].ToString()))
{
return new ValidationResult(true, null);
}
else
{
return new ValidationResult(false,
"Account Name must be between 1 and 100 Characters.");
}
}
else
return new ValidationResult(true, null);
}
When I put a break point in my validation function after I create the DataRowView, the template column is empty. How would I get its content?
A: For a start you have a space in the Path of your Binding for the AutoCompleteBox.Text property which I don't think is allowed.
A: After looking into this, it seems like it doesn't have anything to do with the DataGridTemplateColumn, but rather with the AutoCompleteBox from the Wpf Toolkit. The AutoCompleteBox has been nothing but trouble for me ever since I started using it. As a result, I decided to scrap it and use an Editable ComboBox instead. The combobox is much cleaner and more simple to implement. Here is how my code now looks and the datarowview is able to see what the user types in the box:
<DataGridTemplateColumn Header="Account Type">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path='Account Type'}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox IsEditable="True" LostFocus="LostFocusAccountTypes" ItemsSource="{DynamicResource types}" Height="23" IsTextSearchEnabled="True"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
Code Behind (this.Types is an observable collection of strings)
private void PopulateAccountTypes()
{
try
{
string accountQuery = "SELECT AccountType FROM AccountType WHERE UserID = " + MyAccountant.DbProperties.currentUserID + "";
SqlDataReader accountType = null;
SqlCommand query = new SqlCommand(accountQuery, MyAccountant.DbProperties.dbConnection);
accountType = query.ExecuteReader();
while (accountType.Read())
{
this.Types.Add(accountType["AccountType"].ToString());
}
accountType.Close();
Resources["types"] = this.Types;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8483509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wait for nested async calls to finish I have a series of nested async calls that need to finish before my code continues. Function save_part1 calls the sqlite database and returns the rows of interest. For each of those rows, I make an ajax call to a save them remotely.
From what I have read about promises and deferred, I have only seen them being used in the context of ajax calls. And on top of that, it makes my brain hurt.
Question: how do I wait until all the ajax calls have completed before starting save_part2?
function save()
{
save_part1();
//this should only happen after all the ajax calls from save_part1 are complete
save_part2();
}
function save_part1()
{
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM TABLE1", [],
function (transaction, results) {
for (var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
ajaxCall_item1(row);
}
}, errorHandler)
});
}
function save_part2()
{
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM TABLE2", [],
function (transaction, results) {
for (var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
ajaxCall_item2(row);
}
}, errorHandler)
});
}
A: As long as you have ajaxCall_item returning the jQuery deferred object, you can have save_part1 return a deferred object, collect the returned promises into an array, call them with $.when and resolve the "promise" once all of the requests have completed. Then you will be able to write: save_part1().then(save_part2);. Here is an untested example:
function save() {
save_part1().then(save_part2).fail(function(err) {
// ohno
});
}
function ajaxCall_item1(row) {
return $.ajax({ ... });
}
function save_part1()
{
var dfd = jQuery.Deferred();
var promises = [];
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM TABLE1", [],
function (transaction, results) {
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
promises.push(ajaxCall_item1(row));
}
$.when.apply($, promises).then(function() {
dfd.resolve.apply(dfd, arguments);
});
}, function(err) {
dfd.reject(err);
});
});
return dfd;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35368640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to find the list of indices of NaN values of a given column of a dataframe in python Say I have the following dataframe and I want to get the indices of NaN values in Column 'b'.
Input:
df = pd.DataFrame(np.array([[1, 2, 3 ], [ np.nan, 5, 6], [7, np.nan, 9], [7, np.nan, 9]]),
columns=['a', 'b', 'c'])
Output:
[2,3]
How can I do this? I would like to get the indices as a list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66039584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Show ActionBar with Centred Logo In ListActivity Trying to show an ActionBar with the app logo to the left, title of the screen centred and menu icons to the right. The class below extends a ListActivity how can i go about doing this:
The method i have created was centerlogo(); See code extract below:
public class NewsActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ListView list;
String[] itemname = { "Bafana crash out of Afcon",
"Mali and Guinea face ultimate lottery",
"Orlando Pirates eye cup glory",
"Ivory Coast advance to Afcon quarters",
"Algeria qualify for Afcon quarter-finals",
"Reflect on Afcon lessons - Mbalula",
"Tovey preaches patience with Bafana",
"SuperSport's Brockie harbours lofty goals" };
Integer[] imgid = { R.drawable.bafana, R.drawable.mailguinea,
R.drawable.orlando, R.drawable.ivorycoast, R.drawable.algeria,
R.drawable.reflection, R.drawable.tovey, R.drawable.supersport, };
CustomListAdapter adapter = new CustomListAdapter(this, itemname, imgid);
setListAdapter(adapter);
centreLogo();
}
private void centreLogo() {
// TODO Auto-generated method stub
Drawable d = getResources().getDrawable(R.drawable.banner);
android.app.ActionBar bar = getActionBar();
bar.setBackgroundDrawable(d);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowCustomEnabled(true);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
bar.setCustomView(R.layout.news_view);
bar.setDisplayShowHomeEnabled(true);
bar.setIcon(R.drawable.icon);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public void readMore(View view) {
Intent read = new Intent(NewsActivity.this, ReadMoreActivity.class);
startActivity(read);
}
}
I get the following error:
01-29 13:45:40.093: E/AndroidRuntime(15402): FATAL EXCEPTION: main
01-29 13:45:40.093: E/AndroidRuntime(15402): java.lang.RuntimeException: Unable to start activity ComponentInfo{platinum.platinumstars/platinumnews.NewsActivity}: java.lang.NullPointerException
01-29 13:45:40.093: E/AndroidRuntime(15402): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
01-29 13:45:40.093: E/AndroidRuntime(15402): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
01-29 13:45:40.093: E/AndroidRuntime(15402): at android.app.ActivityThread.access$700(ActivityThread.java:150)
01-29 13:45:40.093: E/AndroidRuntime(15402): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
01-29 13:45:40.093: E/AndroidRuntime(15402): at android.os.Handler.dispatchMessage(Handler.java:99)
01-29 13:45:40.093: E/AndroidRuntime(15402): at android.os.Looper.loop(Looper.java:176)
01-29 13:45:40.093: E/AndroidRuntime(15402): at android.app.ActivityThread.main(ActivityThread.java:5279)
01-29 13:45:40.093: E/AndroidRuntime(15402): at java.lang.reflect.Method.invokeNative(Native Method)
01-29 13:45:40.093: E/AndroidRuntime(15402): at java.lang.reflect.Method.invoke(Method.java:511)
A: I decided to go with GareginSargsyan suggestion. The main problem was that i was trying to inflate the default android list, so i instantiated a new ListView ,
set the ContentView of the list view and the rest is history.
public class NewsActivity extends ActionBarActivity {
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_platinum_news_list);
String[] itemname = { "Bafana crash out of Afcon",
"Mali and Guinea face ultimate lottery",
"Orlando Pirates eye cup glory",
"Ivory Coast advance to Afcon quarters",
"Algeria qualify for Afcon quarter-finals",
"Reflect on Afcon lessons - Mbalula",
"Tovey preaches patience with Bafana",
"SuperSport's Brockie harbours lofty goals" };
Integer[] imgid = { R.drawable.bafana, R.drawable.mailguinea,
R.drawable.orlando, R.drawable.ivorycoast, R.drawable.algeria,
R.drawable.reflection, R.drawable.tovey, R.drawable.supersport, };
// CustomListAdapter adapter = new CustomListAdapter(this, itemname, imgid);
// setListAdapter(adapter);
CustomListAdapter test = new CustomListAdapter(this, itemname, imgid);
list = (ListView) findViewById(R.id.list);
list.setAdapter(test);
centreLogo();
}
private void centreLogo() {
// TODO Auto-generated method stub
Drawable d = getResources().getDrawable(R.drawable.banner);
getSupportActionBar().setBackgroundDrawable(d);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setCustomView(R.layout.news_view);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.icon);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
getMenuInflater().inflate(R.menu.newsmenu, menu);
return true;
}
public void readMore(View view) {
Intent read = new Intent(NewsActivity.this, ReadMoreActivity.class);
startActivity(read);
}
}
A: Most likely, getActionBar() is causing the exception. Try using getSupportActionBar() instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28213996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Prove device enrollment with MDM from an iOS App We want to make an iOS enterprise app that communicates with a server A - we also have our own MDM server as a separate solution which could communicate with the A server if needed. Q: How can the app securely prove to its server, with every request, that it is coming from a device that is enrolled with the MDM?
I thought there would be some UUID that the app could send together with a signed challenge to A. A would then comunicate with MDM server to validate. But seems impossible.
A: The MDM is supposed to handle this. You should not be required to check every request in the API to make sure it is secure. Airwatch, for instance, makes all of your applications downloadable only through their catalog and the agent or vpn system connects when the application is opened. If the user were to attempt to circumvent these limits it unenrolls their device and disallows access until a new enrollment code is issued by your tech department.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48458892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I split compressed sql file using split linux command? If not, then any other method to do? I have a 30 GB compressed sql file (with extension .sql.bz2) and if I unzip it will become 300 GB. However due to disk space issue, I can't do the same.
Could I split the compressed sql file something like using split linux command?
I tried but with no success. Any other approach?
Thanks!
A: You might take a look at this question: split-files-using-tar-gz-zip-or-bzip2
I assume the reason you want to split it is to move it? And that you know you probably wont be able to import a small slice of the file into a database?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40486961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: how to switch image on slidepanellayout in android how to use image to show more & less in slidepanellayout in android.i am using demo application from this link,check this layout.xml
https://github.com/umano/AndroidSlidingUpPanel/blob/master/demo/res/layout/activity_demo.xml
if data hidden it has to show down icon & and when it expanded it has to show up icon
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23221805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to write a base class for DRY in this situation without DI in Kotlin? I got 2 cases for a class, one is like this:
class User {
private val name:Name = NameGenerator()
fun sayName() {
println(this.name.fakeName)
}
}
The other one is:
class User(suggestion:String) {
private val name:Name = NameGenerator(suggestion)
fun sayName() {
println(this.name.fakeName)
}
}
Now you see the differences, it's all about that name, it has 2 different ways to initialize.
How could I write a base class to DRY in this case?
I end up with something like this:
abstract class BaseUser {
protected val name:Name = MockName()
fun sayName() {
println(this.name.fakeName)
}
}
Then I can use it like:
class UserCaseOne():BaseUser() {
}
class UserCaseTwo(suggestion:String):BaseUser() {
init {
this.name = NameGenerator(suggestion)
}
}
This is pretty lame considering that I have to use a mock object to initialize.
Are there better ways to do this? Without injecting the implementation? I don't want to force the UserCaseTwo to have a redundant constructor.
A: If your goal is essentially two combine your first two User classes into a single class, you could do this:
class User(suggestion: String? = null) {
private val name: NameGenerator = suggestion?.let { NameGenerator(it) } ?: NameGenerator()
fun sayName() {
println(this.name.fakeName)
}
}
A: Would it be acceptable to make the name provisioning part of the constructor signature by taking a function as a parameter? The following approach enables the desired abstraction imho:
class User(private val nameProvider: () -> Name) {
private val name: Name by lazy(nameProvider)
fun sayName() {
println(this.name.fakeName)
}
}
You can create Users with any nameProvider such as:
User { MockName() }
User { NameGenerator("blah") }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49397687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Class library project build error, broken references The class library project in Visual Studio is throwing an error when I try building it. The error says:
"Your project is not referencing the ".NETFramework,Version=v4.5.2" framework. Add a reference to ".NETFramework,Version=v4.5.2" in the "frameworks" section of your project.json, and then re-run NuGet restore."
This project is under source control and builds perfectly on other machines with the same Visual Studio version installed. The projects's target network is 4.5.2 as specified in project file.
project.json file looks like this:
{
"version": "1.0.0-*",
"description": "Test Class Library",
"authors": [ "author" ],
"tags": [ "" ],
"projectUrl": "",
"licenseUrl": "",
"dependencies": {
"System.Collections": "4.0.10-beta-23019",
"System.Linq": "4.0.0-beta-23019",
"System.Threading": "4.0.10-beta-23019",
"System.Runtime": "4.0.10-beta-23019",
"Microsoft.CSharp": "4.0.0-beta-23019"
},
"frameworks": {
"dotnet": { }
}
}
I noticed when I build the project, the file project.lock.json gets generated in the project folder, and in it .NETPlatform verision is set to be ".NETPlatform,Version=v5.0". Not sure if this is what causing this problem. It if does, why would project.lock.json set the version to 5.0?
Can anyone suggest a solution to this problem? So far, I am unable to build this project on my machine.
A: Hit this issue with VS2017, what it happened is we converted a dotnet core project back to use .Net frameworks. The old project.assets.json was left in obj folder. And it caused this error. When the file or the obj folder is removed, it builds fine.
A: I resolved this by not using NuGet for this project anymore.
*
*Removed all NuGet packages from the project.
*
*Right-click the project in Visual Studio
*Manage NuGet Packages...
*Uninstall packages one by one until there are none
*Deleted project.json file in the root directory of the project.
*Restarted the Visual Studio. This step might not be necessary, but sometimes when you remove project.json file, you get the NuGet related error when building the project. If this happens, restart the Visual Studio.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36875205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Add link to this JavaScript code I have the following javascript code for a rotating image. Those images are in a separate folder from the javascript. I want to link the rotation itself to another page. All images will go to the same link. The current code works great but I just don't know where I add the a href code or its syntax.
// JavaScript Document
//
// Type the number of images you are rotating.
NumberOfImagesToRotate = 3;
FirstPart = '<img src="domain/rotatingimages';
LastPart = '.gif" height="250" width="388">';
function printImage() {
var r = Math.ceil(Math.random() * NumberOfImagesToRotate);
document.write(FirstPart + r + LastPart);
}
A: Try this format
<a href="link_to_target" target="_blank"><img src='image_src' border="0"/></a>
It is up to you if you want to define the target attribute in <a> tag.
A: // JavaScript Document
//
// Type the number of images you are rotating.
var numberOfImagesToRotate = 3;
// Edit the destination URl here
var linkUrl = 'example.html';
// HTML-partials
var imgFirstPart = '<img src="domain/rotatingimages';
var imgLastPart = '.gif" height="250" width="388" border="0">';
var anchorFirstPart = '<a href="';
var anchorSecondPart = '">';
var anchorLastPart = '</a>';
function printImage() {
var r = Math.ceil(Math.random() * numberOfImagesToRotate);
document.write(anchorFirstPart + linkUrl + anchorSecondPart + imgFirstPart + r + imgLastPart + anchorLastPart);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20247055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A question on text classification with more than one level of category I am trying to produce a series of product classifiers based on the text description that each product has. The data frame I have is similar to the following but is more complicated. Python and the sklearn library are used.
data = {'description':['orange', 'apple', 'bean', 'carrot','pork','fish','beef'],
'level1':['plant', 'plant', 'plant', 'plant','animal','animal','animal'],
'level2:['fruit','fruit','vegatable','vegatable','livestock', 'seafood','livestock'}
# Create DataFrame
df = pd.DataFrame(data)
"Description" is the textual data. Now it is only a word. But the real one is a longer sentence.
"Level1" is the top category.
"Level2" is a sub-category.
I know how to train a classification model to classify the products into Level 1 categories by using the sklearn library.
Below is what I did:
import pandas as pd
import numpy as np
import nltk
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report, f1_score, accuracy_score, confusion_matrix
from sklearn.metrics import roc_curve, auc, roc_auc_score
import pickle
# Train/Test split
X_train, X_test, y_train, y_test = train_test_split(df['description'],
df[['Level1','Level2']], test_size = 0.4, shuffle=True)
#use the TF-IDF Vectorizer
tfidf_vectorizer = TfidfVectorizer(use_idf=True)
#transforming the training data into tf-idf matrix
X_train_vectors_tfidf = tfidf_vectorizer.fit_transform(X_train)
#transforming testing data into tf-idf matrix
X_test_vectors_tfidf = tfidf_vectorizer.transform(X_test)
#Create and save model for level 1
naive_bayes_classifier = MultinomialNB()
model_level1 = naive_bayes_classifier.fit(X_train_vectors_tfidf, y_train['Level1'])
with open('model_level_1.pkl','wb') as f:
pickle.dump(model_level1, f)
What I don't know how to do is to build a classification model for each Level 1 category that can predict the products' Level 2 category. For example, based on the above dataset, there should be one classification model for 'plant' (to predict fruit or vegetable) and another model for 'animal' (to predict seafood or livestock). Do you have any ideas to do it and save the models by using loops?
A: Assuming you will be able to get all the columns of the dataset then it would be a mix of features with Levels being the class labels. Formulating on the same lines:
cols = ["abc", "Level1", "Level2", "Level3"]
From this now let's take only levels because that is what we are interested in.
level_cols = [val for val in levels if "Lev" in val]
The above just check for the presence of "Lev" starts with these three characters.
Now, with level cols in place. I think you could do the following as a starting point:
1. Iterate only the level cols.
2. Take only the numbers 1,2,3,4....n
3. If step-2 is divisible by 2 then I do the prediction using the saved level model. Ideally, all the even ones.
4. Else train on other levels.
for level in level_cols:
if int(level[-1]) % 2 == 0:
# open the saved model at int(level[-1]) - 1
# Perform my prediction
else:
level_idx = int(level[-1])
model = naive_bayes_classifier.fit(x_train, y_train[level])
mf = open("model-x-"+level_idx, "wb")
pickle.dump(model, mf)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70382013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Respect negative conditions for advanced collection associations I was trying to use this functionality introduced in #645 with conditional 2nd degree has_many ... through relationships with little success.
In my case:
*
*a Course has_many :user_assigned_content_skills, -> { where(source: 'user') }, class_name: "ContentSkill"
*and a ContentSkill belongs_to :skill and belongs_to :course
Then Course.ransack({user_assigned_content_skills_skill_name_not_cont: 'ruby'}).result.to_sql returns the following:
"SELECT courses.* FROM courses LEFT OUTER JOIN content_skills ON content_skills.course_id = courses.id AND content_skills.source = 'user' LEFT OUTER JOIN skills ON skills.id = content_skills.skill_id WHERE (skills.name NOT ILIKE '%ruby%')"
This means false positives again if a course has multiple content_skills. Any ideas how to retrieve all courses not being associated with a given skill name?
Many thanks for any insights!
A: You can get ids of courses associated with a given skill name, and then get a list of courses with ids that don't match the previous found. You can even make it as one composite SQL query.
Course.where.not(id: Course.ransack({user_assigned_content_skills_skill_name_cont: 'ruby'}).result)
This will generate an SQL like this:
SELECT courses.*
FROM courses
WHERE courses.id NOT IN (
SELECT courses.id FROM courses
LEFT OUTER JOIN content_skills ON content_skills.course_id = courses.id AND content_skills.source = 'user'
LEFT OUTER JOIN skills ON skills.id = content_skills.skill_id
WHERE (skills.name ILIKE '%ruby%')
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41717007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error: Call to a possibly undefined method I have the simplest code ever. Main class:
package
{
import field.Field;
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var field:Field = new Field();
addChild(field);
field.test();
}
}
}
and a Field class:
package field
{
import flash.display.Sprite;
public class Field extends Sprite
{
public function Field()
{
super();
}
public function test():void
{
}
}
}
test method is presented.
But when I try to compile I get this:
Main.as(26): col: 10 Error: Call to a possibly undefined method test.
field.test();
How could this be happening?
A: field is your package, that's why you can not do field.test(). So you have to choose another name of your Field instance. You can do like this :
var _field:Field = new Field();
addChild(_field);
_field.test();
Hope that can help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28237588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reading specific number of bytes from a buffered reader in golang I am aware of the specific function in golang from the bufio package.
func (b *Reader) Peek(n int) ([]byte, error)
Peek returns the next n bytes without advancing the reader. The bytes
stop being valid at the next read call. If Peek returns fewer than n
bytes, it also returns an error explaining why the read is short. The
error is ErrBufferFull if n is larger than b's buffer size.
I need to be able to read a specific number of bytes from a Reader that will advance the reader. Basically, identical to the function above, but it advances the reader. Does anybody know how to accomplish this?
A: TLDR:
my42bytes, err := ioutil.ReadAll(io.LimitReader(myReader, 42))
Full answer:
@monicuta mentioned io.ReadFull which works great. Here I provide another method. It works by chaining ioutil.ReadAll and io.LimitReader together. Let's read the doc first:
$ go doc ioutil.ReadAll
func ReadAll(r io.Reader) ([]byte, error)
ReadAll reads from r until an error or EOF and returns the data it read. A
successful call returns err == nil, not err == EOF. Because ReadAll is
defined to read from src until EOF, it does not treat an EOF from Read as an
error to be reported.
$ go doc io.LimitReader
func LimitReader(r Reader, n int64) Reader
LimitReader returns a Reader that reads from r but stops with EOF after n
bytes. The underlying implementation is a *LimitedReader.
So if you want to get 42 bytes from myReader, you do this
import (
"io"
"io/ioutil"
)
func main() {
// myReader := ...
my42bytes, err := ioutil.ReadAll(io.LimitReader(myReader, 42))
if err != nil {
panic(err)
}
//...
}
Here is the equivalent code with io.ReadFull
$ go doc io.ReadFull
func ReadFull(r Reader, buf []byte) (n int, err error)
ReadFull reads exactly len(buf) bytes from r into buf. It returns the number
of bytes copied and an error if fewer bytes were read. The error is EOF only
if no bytes were read. If an EOF happens after reading some but not all the
bytes, ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and
only if err == nil. If r returns an error having read at least len(buf)
bytes, the error is dropped.
import (
"io"
)
func main() {
// myReader := ...
buf := make([]byte, 42)
_, err := io.ReadFull(myReader, buf)
if err != nil {
panic(err)
}
//...
}
Compared to io.ReadFull, an advantage is that you don't need to manually make a buf, where len(buf) is the number of bytes you want to read, then pass buf as an argument when you Read
Instead you simply tell io.LimitReader you want at most 42 bytes from myReader, and call ioutil.ReadAll to read them all, returning the result as a slice of bytes. If successful, the returned slice is guaranteed to be of length 42.
A: Note that the bufio.Read method calls the underlying io.Read at most once, meaning that it can return n < len(p), without reaching EOF. If you want to read exactly len(p) bytes or fail with an error, you can use io.ReadFull like this:
n, err := io.ReadFull(reader, p)
This works even if the reader is buffered.
A: I am prefering Read() especially if you are going to read any type of files and it could be also useful in sending data in chunks, below is an example to show how it is used
fs, err := os.Open("fileName");
if err != nil{
fmt.Println("error reading file")
return
}
defer fs.Close()
reader := bufio.NewReader(fs)
buf := make([]byte, 1024)
for{
v, _ := reader.Read(buf) //ReadString and ReadLine() also applicable or alternative
if v == 0{
return
}
//in case it is a string file, you could check its content here...
fmt.Print(string(buf))
}
A: func (b *Reader) Read(p []byte) (n int, err error)
http://golang.org/pkg/bufio/#Reader.Read
The number of bytes read will be limited to len(p)
A: Pass a n-bytes sized buffer to the reader.
A: If you want to read the bytes from an io.Reader and into an io.Writer, then you can use io.CopyN
CopyN copies n bytes (or until an error) from src to dst. It returns the number of bytes copied and the earliest error encountered while copying.
On return, written == n if and only if err == nil.
written, err := io.CopyN(dst, src, n)
if err != nil {
// We didn't read the desired number of bytes
} else {
// We can proceed successfully
}
A: To do this you just need to create a byte slice and read the data into this slice with
n := 512
buff := make([]byte, n)
fs.Read(buff) // fs is your reader. Can be like this fs, _ := os.Open('file')
func (b *Reader) Read(p []byte) (n int, err error)
Read reads data into p. It returns the number of bytes read into p.
The bytes are taken from at most one Read on the underlying Reader,
hence n may be less than len(p)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13660864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
} |
Q: Determining bar width, with a 3d matrix I have my data as follows:
var data = [[-5,7,10],[10,15,25],[-18,-14,-6]];
var margin = {top: 0, right: 30, bottom: 80, left: 30},
width = 180 - margin.left - margin.right,
height = 295 - margin.top - margin.bottom;
var x0 = Math.max(-d3.min(data[0]), d3.max(data[2]));
var x = d3.scale.linear()
.domain([-x0, x0])
.range([0, width]);
var y = d3.scale.ordinal()
.domain(d3.range(data.length))
.rangeRoundBands([0, height], .2);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.style("fill", "steelblue")
.attr("x", function(d, i) { return x(Math.min(0, d[0])); })
.attr("y", function(d, i) { return y(i); })
.attr("width", function(d, i) { return Math.abs(x(d[2]) - x(d[0])); })
.attr("height", y.rangeBand())
.append("rect");
//y axis
svg.append("g")
.attr("class", "y axis")
.append("line")
.attr("x1", x(0))
.attr("x2", x(0))
.attr("y1", 0)
.attr("y2", height+10);
What I want to do is create a bar chart where data[0] is the starting point, data[1] has a vertical line bisecting the bar and data[2] is the max value of the bar. So far, I think I'm covering the first two use cases correctly, but the third one fails. Any ideas?
http://jsfiddle.net/NPqEm/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12379226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detecting Gameobjects under Linerenderer I have made a LineRenderer and I added an EdgeCollider2D to it.
Now I am trying to detect all GameObjects below my LineRenderer.
The objects below have Colliders as well.
*
*LineRenderer starts with first mouse position and ends with last mouse position
*LineRenderer has an EdgeCollider2D
*I need to get value from all objects which are under LineRenderer
*Project is in 2D
What I tried:
*
*Use Raycast,but using raycast I am getting values from object around too.
And i want only to get values of Gameobjects under Linerenderer not values from All gameobjects touched by mouse
*Or if it is Possible to get gameobjects between 2 positions
*So basicaly i need to get values from 10 of 100 objects,which are all together.F.E i have 100 mushrooms placed together,and every mushroom have its int value which is different.
So moving my mouse around i need to select only this 10 mushrooms and take its value.
Here is my code so far
RaycastHit2D[] rays = Physics2D.RaycastAll(mousePos, lr.transform.forward);
Debug.DrawRay(new Vector3(startMousePosition.x, startMousePosition.y, 0), Vector3.up, Color.red, 5);
for (int i = 0; i < rays.Length; i++)
{
RaycastHit2D ray = rays[i];
if (isTOuched)
{
if (ray.collider.gameObject.tag == "Player")
{
if (objektiOdRaycast.Contains(ray.collider.gameObject) == false)
{
objektiOdRaycast.Add(ray.collider.gameObject);
for (int t = 0; t < objektiOdRaycast.Count; t++)
{
tekst = objektiOdRaycast[t].GetComponent < GridSquare().tekst;
}
words.tekstSlova.text += tekst;
}
}
}
}
A: The problem with a Raycast is: It only checks one single ray direction. That makes no sense in your use case.
You probably want to use Physics2D.OverlapCollider
Gets a list of all Colliders that overlap the given Collider.
and do e.g.
// Reference via the Inspector
public LineRenderer theLine;
// configure via the Inspector
public ContactFilter2D filter;
private Collider2D lineCollider;
private readonly List<Collider2D> overlaps = new List<Collider2D>();
private readonly HashSet<Collider2D> alreadySeen = new HashSet<Collider2D>();
private void Awake()
{
// as fallback assume same GameObject
if(!theLine) theLine = GetComponent<LineRenderer>();
lineCollider = theLine.GetComponent<Collider2D>();
}
public void GetOverlappingObjects()
{
var amount = Physics2D.OverlapCollider(lineCollider, filter, overlaps);
for(var i = 0; i < amount; i++)
{
var overlap = overlaps[i];
if(alreadySeen.Contains(overlap)) continue;
alreadySeen.Add(overlap);
var overlapObject = overlap.gameObject;
// These checks are actually kind of redundant
// the second heck for the component should already be enough
// instead of the tag you could rather use a Layer and configure the filter accordingly
if (!overlapObject.CompareTag("Player")) continue;
if (!overlapObject.TryGetComponent<GridSquare>(out var gridSquare)) continue;
words.tekstSlova.text += gridSquare.tekst;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71326052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can session be maintained if we turn off javascript in the browser? So recently i was asked this question in an interview that "Can you manage session in MVC .NET if javascript is turned off in the browser"?
I replied "Yes we can" but I am not very sure and I need some assistance on this topic.
A: Sessions, SessionIDs and Session state are managed by the .NET server (by default), not by the client. Turning off JavaScript at the client won't affect the server.
Quote from MS Docs:
The in-memory [default session state] provider stores session data in the memory of the server where the app resides.
A: Session is stored on server side and session id is stored on client side, and javascript don't impact the session. So session will work if you turn off the javascript
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56166639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: reliable way to get line / column number from javascript Error? I have a little embedded JS editor on my site and when the code inside it throws an error I'd like to underline where the error is happening. The error stack trace looks like this:
err ReferenceError: a is not defined
at isNumber (eval at handle_message (about:srcdoc:11:7), <anonymous>:5:5)
at Array.filter (<anonymous>)
at removeNumbers (eval at handle_message (about:srcdoc:11:7), <anonymous>:13:15)
at eval (eval at handle_message (about:srcdoc:11:7), <anonymous>:16:28)
at handle_message (about:srcdoc:14:7)
In this case my desired solution would return { line: 5, column: 5 } (the first entry of the stack trace)
My first instinct is just to do some text parsing + regex to get the last 2 numbers from the second line. This seems like a super unreliable solution though, and I'm not sure if stack traces will follow this format for all types of errors and on all browsers.
Is there a more reliable way to extract the error location from a javascript Error object?
A: There is a built-in way to get the line and column number in JavaScript, but unfortunately, it isn't supported in (literally) all browsers. The only browser that supports it is Firefox.
Right now, the best thing you can do is just get it from the browser console.
However, to get it from the Error object, you can first wrap your code in a try/catch statement.
try {
a();
} catch (err) {
console.log(err); // ReferenceError: a is...
}
Then, you can get the line and column numbers from it. Beware; it's only supported in Mozilla!
console.log(err.lineNumber, err.columnNumber); // 5 5
The only properties that aren't non-standard in the Error object is the name and message.
In conclusion, even though there is a built-in way to get the line and column number in JavaScript, it is non-standard and only supported in Firefox.
The best way to get it is to get it from the browser console (or to get it from third-party libraries, if possible).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72051481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ggplot - add title based on the variable in the dataframe used for plotting This is a follow-up to my previous question where I asked how to use ggplot inside of purr::map.
I have a dataframe that looks like this:
I have a dataframe named data which looks like this:
Country Year Incidence
USA 1995 20000
USA 2000 23000
UK 1995 16000
UK 2000 22000
I am using this code to make a year/incidence plot split by country (each country has a separate plot, not one single, but faceted plot for all countries).
list_plot <- data %>%
group_split(Country) %>%
map(~ggplot(., aes(x = Year, y = Incidence) ) +
geom_line()+ geom_point())
Now I would like to put the name of the country in the title of each of the graphs. I tried the following:
list_plot <- data %>%
group_split(Country) %>%
map(~ggplot(., aes(x = Year, y = Incidence) ) +
geom_line()+ geom_point() + labs(title = Country))
But it's not working (it's telling me the object 'Country' is not found). How can I achieve this?
A: Using .$Country instead of Country should fix it
data = data.frame(Country = c('USA','USA','UK','UK'),
Year = c(1995,2000,1995,2000),
Incidence = c(20000,23000,16000,22000))
list_plot <- data %>%
group_split(Country) %>%
map(~ggplot(., aes(x = Year, y = Incidence) ) +
geom_line()+ geom_point() + labs(title = .$Country))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60671725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: masstransit handle/consume messages in batches I have a clear understanding of consuming messages: http://docs.masstransit-project.com/en/latest/usage/consumer.html
these implementations only handle ONE message at a time.
I need to handle multiple messages at a time, in bulk, in batches.
A: Mass Transit now has an experimental feature to process individual message's in a batch.
Configure your bus:
_massTransitBus = Bus.Factory.CreateUsingRabbitMq(
cfg =>
{
var host = cfg.Host(new Uri("amqp://@localhost"),
cfg =>
{
cfg.Username("");
cfg.Password("");
});
cfg.ReceiveEndpoint(
host,
"queuename",
e =>
{
e.PrefetchCount = 30;
e.Batch<MySingularEvent>(
ss =>
{
ss.MessageLimit = 30;
ss.TimeLimit = TimeSpan.FromMilliseconds(1000);
ss.Consumer(() => new BatchSingularEventConsumer());
});
});
});
And Create your Consumer:
public class BatchSingularEventConsumer: IConsumer<Batch<MySingularEvent>>
{
public Task Consume(ConsumeContext<Batch<MySingularEvent>> context)
{
Console.WriteLine($"Number of messages consumed {context.Message.Length}");
return Task.CompletedTask;
}
}
You can configure your Batch with a Message Limit and a Time Limit.
I suggest reading Chris Patterson's issue on the matter Batch Message Consumption especially the part regarding prefetch
The batch size must be less than or equal to any prefetch counts or concurrent message delivery limits in order reach the size limit. If other limits prevent the batch size from being reached, the consumer will never be called.
Batch consumption is also documented on the MassTransit website.
A: As it turns out, today you can do this:
public class MyConsumer : IConsumer<Batch<MyMessage>>
{
public async Task Consume(ConsumeContext<Batch<MyMessage>> context)
{
...
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40923409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Hacked, Extension Stolen - How To Recover Quickly? My Google account was hacked, and my popular (~200k users) extension was stolen and transferred to a malicious account. The extension was updated with new code and my users are being automatically updated.
I've tried to contact Google 3 different ways, but no response so far. What's the best way to quickly shut down the stolen extension, and get ownership back to me?
I don't want the extension listing and id to be just deleted, because I want to retain all my existing users and thousands of positive reviews.
Has anyone had success with a particular method of contacting Google? Any advice would be appreciated. Thanks.
Matt Kruse
Social Fixer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44891134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to stop one specific user to delete his account in Ruby on Rails? I have this code in /views/devise/registrations/edit.html.erb
<b>Cancel my account</b>
<%= link_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %>.
which allows the logged in user to delete his account. Now I do NOT want one user with id=223 to have this permission/link. How can I do this ? I am not not sure the below cod in edit.html.erb file will work (or is there any better way to do it?)
EDIT - Ok this below code is working but how to do it through controller ?
<% if current_user.id != 223 %>
<b>Cancel my account</b>
<%= link_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %>.
<% end %>
A: Controller has nothing to do with a link being displayed or not. However you can disable the deletion in the controller by checking the same condition.
Anyways, you should create at least a model property for this. This id hardcode thingy is not nice, so hide it at least and make it not being repeated.
model User
...
def can_delete_account?
id != 223 # ugly hack
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17090904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling a fun with reified type parameter if you just have a KClass object? One can only use reified type parameters with inline functions. So if I want such a parameter for a class I need a trick like this:
class Foo<T : Any>(private val clazz: KClass<T>) {
companion object {
inline fun <reified T: Any> create() = Foo(T::class)
}
}
I can then create instances of Foo like this:
val foo = Foo.create<Bar>()
Within Foo I have access clazz but my question is can I then use clazz when I need to call methods that require a reified type parameter`?
E.g. within Foo I'd like to add a method like this:
fun print(list: List<Alpha>) {
list.filterIsInstance<T>().forEach { print(it) }
}
But as far as I can see there's no way to get from clazz to something I can use as a type parameter here.
And yes, I know there's a form of filterIsInstance that takes a Class so I can do:
list.filterIsInstance(clazz.java).forEach { print(it) }
However many libraries contain methods where both forms (explicit class parameter and reified type parameter) are not provided.
E.g. the Jackson Kotlin Extensions.kt. Actually this isn't a great example as the non-reified equivalents are all one-liners but this isn't always the case - then you end up unpacking the implementation of the reified-type-parameter method into your code.
A: no, because those functions are inline, they are inlined at compiletime
and a Class or KClass is using reflection at runtime
there are some tricks that you can do.. like with the companion class, but that does nto need the KClass<T> at all.. anything else that provides a generic argument of T would work just as well for the reified type info
PS: reflection also cannot help you reliably because inline functions do not really exist at runtime, as explained by their modifier inline
A: Unless I am missing something, everything you can do with T in a function with reified T can be translated to a use of KClass: e.g. x is T becomes clazz.isInstance(x), x as T becomes clazz.cast(x), calls of other functions with reified type parameters are translated recursively, etc. Since the function has to be inline, all APIs it uses are visible at the call site so the translation can be made there.
But there's no automatic way to do this translation, as far as I know.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55399737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: SUM without duplicated row with GROUP BY SELECT SUM(man+woman) AS over65,
a.cod,
a.city,
b.cod2
FROM a LEFT JOIN
b ON b.cod2 = a.cod
GROUP BY cod
--
table a
cod city
28001 rome
28001 rome
28002 milan
28002 milan
table b
cod2 age man woman
28001 65 156 220
28001 66 250 280
28001 67 350 483
28002 65 556 524
28002 66 650 683
28002 67 450 342
result Is:
cod city over65
28001 rome 3478
28002 milan 6410
instead Of :
cod city over65
28001 rome 1739
28802 milan 3205
What should i do for this?
thanks
A: Use a subquery to get rid of the duplicates in table a.
SELECT SUM(man+woman) AS over65,
a.cod,
a.city,
b.cod2
FROM (SELECT DISTINCT cod, city
FROM a) AS a
LEFT JOIN
b ON b.cod2 = a.cod
GROUP BY a.cod
I also wonder why table a has those duplicates in the first place. If city is always the same for a given cod, the data is not properly normalized.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48014940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is readxl so much faster than xlsx package? We used the two packages xlsx and readxl and now it seems, readxl is much faster. Why? As long-term stability is important to us, I would then always use the readxl package.
Reproducible example:
path <- "C:/Temp/"
name <- "myexcel.xlsx"
filename <- paste0(path, name)
dim <- c(14000, 30)
rands <- matrix(data = runif(n = dim[1]*dim[2], min = 0, max = 1), nrow = dim[1], ncol = dim[2])
df <- as.data.frame(rands)
writexl::write_xlsx(x = df, path = filename, col_names = TRUE)
# xlsx::write.xlsx(x = df, file = filename, sheetName = "Sheet1")
# Does not give a result
mytable <- readxl::read_excel(path = filename, sheet = "Sheet1")
# mytable2 <- xlsx::read.xlsx(file = filename, sheetName = "Sheet1")
# Does not give a result
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68345179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Azure Automation Credentials using Azure Key Vault secrets Is there a way to create an Azure Automation Credential asset which links to an Azure Key Vault secret? Similar question for a Certificate in Azure Automation.
I want to be able to store my passwords and such all in one place, the Key Vault, so that when I change it I don't have to change it in a bunch of places. I cannot find any documentation that indicates this is possible though. Am I missing it?
Thank you for any suggestions....
A: You can't link a Credential asset directly to Key Vault, however it should be possible to write a script that connects to Key Vault and updates the appropriate Automation Credentials from there.
This could either be fired on a schedule, a webhook, or by picking up Key Vault events from the new Event Grid (presuming they are currently wired up)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45746366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Camera access in WebView in Java 8 I have a WebView in my JavaFX application that loads an HTML5 file that accesses the webcam of the local computer. It runs perfectly in Chrome and Mozilla but not in JavaFX's WebView. Is there a configuration that I need to set in order to run it in WebView? Im using Java 8u60.
A: Seems that the WebKit in WebEngine does not support it:
With the following javascript:
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
if (navigator.getUserMedia) {
alert("getUserMedia supported");
navigator.getUserMedia({video: true}, handleVideo, videoError);
} else {
alert("getUserMedia not supported");
}
and this Java code:
WebEngine webEngine = webView.getEngine();
webEngine.setOnAlert(event -> System.err.println(event.toString()));
the output shows:
WebEvent [source = javafx.scene.web.WebEngine@3dd89471, eventType = WEB_ALERT, data = getUserMedia not supported]
I tried setting a confirm handler in case that the WebEngine tries to ask for permission, but that is never called.
Tried it with Java 1.8.0_66 on OSX 10.11.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32623307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Array combining 2 or more values together I am curious know if and how it is possible to combine 2 values of an array together instead of overriding the other. I will show you an example:
I have a form that is mapping fields to a database from a CSV file. The problem I am running into is say for example there are 2 address fields that need to be merged into 1 address field in my database. (IE: photo below)
So my problem comes when I look at the $_POST[] array. It will show that there are 2 HOME ADDRESSES Selected and import into my database with the LAST selected home-address.
How can I merge the information into 1. I hope this gives you enough information on my problem, please let me know if you need something specific.
I am dealing with all arrays, and when I post into my database it requires an Array to loop through, as I use a reflection class. I hope this makes sense...
Any light would be appreciated on this matter.
Cheers,
I appreciate the quite comments back, the problem that I have with your responses is that I can't create my inputs to be address[] as that will be dynamic and I won't know which one will be set to address and which would perhaps be set to 'phone'... I hope this new picture helps a bit in understanding.
Some of the code (Shortened):
<select name="Home_Address_1"> // name is dynamically generated from the CSV headings
<option>...</option>
</select>
<select name="Home_Address_2"> // name is dynamically generated from the CSV headings
<option>...</option>
</select>
A: Example of using two posted values in a single array:
<!-- HTML -->
<input name="address[]" type="text" value="111" />
<input name="address[]" type="text" value="222" />
Notice the name attributes.
// PHP
$address = $_POST['address'][0] . ' ' . $_POST['address'][1];
echo $address; // prints "111 222"
UPDATE
Before your script loops through the $_POST array, merge the fields, like so:
$preformat = $_POST['Home_Address_1'];
$preformat .= ' ' . $_POST['Home_Address_2'];
$preformat .= ' ' . $_POST['Home_Address_3'];
$_POST['Home_Address_3'] = trim($preformat);
Then the last Home Address field contains all three.
A: Try array_merge()...http://php.net/manual/en/function.array-merge.php
A: Try array_merge with shuffle
$merged = array_merge($arr1,$arr2);
shuffle($merged);
with regards
Wazzy
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4560000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: NHibernate : QueryOver in generic method I have this test method, I have a problem on the "List" method. I'd like use several class (all inplement IAdminDecimal). On the QueryOver, I have this error :
The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'NHibernate.ISession.QueryOver()'
using (var session = sessions.OpenSession())
{
using (var tx = session.BeginTransaction())
{
CurrentSessionContext.Bind(session);
AdministrationService service = new AdministrationService(session);
service.List<AdminDelay>();
tx.Commit();
}
}
The class :
public class AdministrationService
{
private readonly ISession _session;
public AdministrationService(ISession session)
{
_session = session;
}
public IList<T> List<T>() where T : IAdminDecimal
{
var res = _session.QueryOver<T>().List<T>();
return res;
}
}
public interface IAdminDecimal
{
int Id { get; set; }
int Code { get; set; }
decimal Value { get; set; }
bool IsDeleted { get; set; }
}
public class AdminVAT : IAdminDecimal
{
public virtual int Id { get; set; }
public virtual int Code { get; set; }
public virtual decimal Value { get; set; }
public virtual bool IsDeleted { get; set; }
}
A: Try:
public IList<T> List<T>() where T : class, IAdminDecimal
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6368931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Airfoil plottin by data file without court line in Spyder by python I use the AeroPython codes by Barba Group's;
#import libraries and modules needed
import os
import numpy
from scipy import integrate, linalg
from matplotlib import pyplot
# load geometry from data file
naca_filepath = os.path.join('resources', 'naca0012.dat')
with open(naca_filepath, 'r') as infile:
x, y = numpy.loadtxt(infile, dtype=float, unpack=True)
# plot geometry
width = 10
pyplot.figure(figsize=(width, width))
pyplot.grid()
pyplot.xlabel('x', fontsize=16)
pyplot.ylabel('y', fontsize=16)
pyplot.plot(x, y, color='k', linestyle='-', linewidth=2)
pyplot.axis('scaled', adjustable='box')
pyplot.xlim(-0.1, 1.1)
pyplot.ylim(-0.1, 0.1);
and use from airfoil.com naca0012 data file (change the name "n0012.dat" to "naca0012.dat" and delete Tittle inside the file because the program don't use the strings in data file)
in the lesson look like figure like this
but I use the code plot this includes the courtline
Something wrong but what is it?
A: The link to the airfoil database contains the coordinates of a NACA0012 in the Lednicer format, while the code in AeroPython Lesson was written for an airfoil in Selig's format.
(The Notebook compute the flow around an airfoil using a source-panel method.)
Selig's format starts from the trailing edge of the airfoil, goes over the upper surface, then over the lower surface, to go back to the trailing edge.
Lednicer's format lists points on the upper surface (from leading edge to trailing edge), then points on the lower surface (from leading edge to trailing edge).
You can load the Selig's format (skipping the header "NACA 0012 AIRFOILS" with skiprows=1 in numpy.loadtxt) as follow:
import urllib
# Retrieve and save geometry to file.
selig_url = 'http://airfoiltools.com/airfoil/seligdatfile?airfoil=n0012-il'
selig_path = 'naca0012-selig.dat'
urllib.request.urlretrieve(selig_url, selig_path)
# Load coordinates from file.
with open(selig_path, 'r') as infile:
x1, y1 = numpy.loadtxt(infile, unpack=True, skiprows=1)
The NACA0012 airfoil here contains 131 points and you will see that the trailing edge has a finite thickness:
print('Number of points:', x1.size) # -> 131
print(f'First point: ({x1[0]}, {y1[0]})') # -> (1.0, 0.00126)
print(f'Last point: ({x1[-1]}, {y1[-1]})') # -> (1.0, -0.00126)
If you do the same with the Lednicer's format (with skiprows=2 for the header), you will load 132 points (leading-edge point is duplicated) with points on the upper surface being flipped (from leading edge to trailing edge).
(That's why you observe this line in the middle with pyplot.plot; the line connects the trailing edge from the upper surface to the leading edge from the lower surface.)
One way to re-orient the points to follow Selig's format is to skip the leading edge on the upper surface (i.e., skip the duplicated point) and flip the points on the upper surface.
Here is a possible solution:
import numpy
# Retrieve and save geometry to file.
lednicer_url = 'http://airfoiltools.com/airfoil/lednicerdatfile?airfoil=n0012-il'
lednicer_path = 'naca0012-lednicer.dat'
urllib.request.urlretrieve(lednicer_url, lednicer_path)
# Load coordinates from file (re-orienting points in Selig format).
with open(lednicer_path, 'r') as infile:
# Second line of the file contains the number of points on each surface.
_, info = (next(infile) for _ in range(2))
# Get number of points on upper surface (without the leading edge).
num = int(info.split('.')[0]) - 1
# Load coordinates, skipping the first point (leading edge on upper surface).
x2, y2 = numpy.loadtxt(infile, unpack=True, skiprows=2)
# Flip points on the upper surface.
x2[:num], y2[:num] = numpy.flip(x2[:num]), numpy.flip(y2[:num])
You will end up with 131 points, oriented the same way as the Selig's format.
print('Number of points:', x2.size) # -> 131
print(f'First point: ({x2[0]}, {y2[0]})') # -> (1.0, 0.00126)
print(f'Last point: ({x2[-1]}, {y2[-1]})') # -> (1.0, -0.00126)
Finally, we can also checks that coordinates are the same with numpy.allclose:
assert numpy.allclose(x1, x2, rtol=0.0, atol=1e-6) # -> True
assert numpy.allclose(y1, y2, rtol=0.0, atol=1e-6) # -> True
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59871036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using Facebook Async Display Kit in Swift I want to use facebook async display kit in my project for smooth loading in tableview. I read them GitHub page but it's not clear for me. Can anyone help me to understand it?
(ASDK can also be used as a regular static library: Copy the project to your codebase manually, adding AsyncDisplayKit.xcodeproj to your workspace. Add libAsyncDisplayKit.a, AssetsLibrary, and Photos to the "Link Binary With Libraries" build phase. Include -lc++ -ObjC in your project linker flags.)
I did copy xcodeproj file into my own project and add -ObjC. But I do not know what they means by Add libAsyncDisplayKit.a, AssetsLibrary, and Photos to the "Link Binary With Libraries" build phase.. I did not find such files.
Please, do not minus my question, I'm new in Swift. Just show me the road. Thank you!
A: What it means is that you have to add the libraries you mention in the "link binary with libraries" row of the Build Phases section.
You can arrive to that section by:
- clicking in the project file in the project navigator view
- clicking in the target of the project where you want to use the library in the targets column
- clicking in the Build Phases section you will see the Link Binary With Libraries row.
Just click on the + button and add libAsyncDisplayKit.a, Photos.framework and the AssetsLibrary.framework.
A: A convenient way of adding external libs is to use cocoa pods as employeed here. (A collectionsview implementation a tableView should be somewhat similar)
(I am not the writer of that article)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30273136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can i get my container to go from starting -> healthy Background: My Docker container has a very long startup time, and it is hard to predict when it is done. And when the health check kicks in, it first may show 'unhealthy' since the startup is sometimes not finished. This may cause a restart or container removal from our automation tools.
My specific question is if I can control my Docker container so that it shows 'starting' until the setup is ready and that the health check can somehow be started immediately after that? Or is there any other recommendation on how to handle states in a good way using health checks?
Side question: I would love to get a reference to how transitions are made and determined during container startup and health check initiating. I have tried googling how to determine Docker (container) states but I can't find any good reference.
A:
My specific question is if I can control my container so that it shows
'starting' until the setup is ready and that the health check can
somehow be started immediately after that?
I don't think that it is possible with just K8s or Docker.
Containers are not designed to communicate with Docker Daemon or Kubernetes to tell that its internal setup is done.
If the application takes a time to setup you could play with readiness and liveness probe options of Kubernetes.
You may indeed configure readynessProbe to perform the initial check after a specific delay.
For example to specify 120 seconds as initial delay :
readinessProbe:
tcpSocket:
port: 8080
initialDelaySeconds: 5
periodSeconds: 120
Same thing for livenessProbe:
livenessProbe:
httpGet:
path: /healthz
port: 8080
httpHeaders:
- name: Custom-Header
value: Awesome
initialDelaySeconds: 120
periodSeconds: 3
For Docker "alone" while not so much configurable you could make it to work with the --health-start-period parameter of the docker run sub command :
--health-start-period : Start period for the container to initialize
before starting health-retries countdown
For example you could specify an important value such as :
docker run --health-start-period=120s ...
A: Here is my work around. First in docker-compose set long timeout, start_period+timeout should be grater than max expected starting time, eg.
healthcheck:
test: ["CMD", "python3", "appstatus.py", '500']
interval: 60s
timeout: 900s
retries: 2
start_period: 30s
and then run script which can wait (if needed) before return results. In example above it is appstatus.py. In the script is something like:
timeout = int(sys.argv[1])
t0 = time.time()
while True:
time.sleep(2)
if isReady():
sys.exit(os.EX_OK)
t = time.time() - t0
if t > timeout:
sys.exit(os.EX_SOFTWARE)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63480418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Scriptable way to create flat .pkg files with custom resources and scripts I have created a flat .pkg file with following options on 10.7 using PackageMaker 3.0.6:
/Applications/PackageMaker.app/Contents/MacOS/Package --root ./myroot \
--id com.myroot.pkg --title "My Root" --scripts ./scripts --target 10.5 \
--verbose --resources ./resources --root-volume-only --domain system \
--no-relocate --versio 1.0 --certificate "My Cert Name"
In the resources folder I have background.png, Welcome.rtf and License.rtf and in the scripts folder I have preflight, postflight and various support files for those scripts. The resulting .pkg appears to be fully functional except that the installer does not display my background, welcome or license.
How can I add a custom background, welcome and license to a flat package?
As far as I can tell, the Distribution file in the .pkg is missing references to the background, welcome and license files.
As a workaround I tried using xar. If I unpack the package with xar like so:
xar -xf ./myroot.pkg -C work
and add the 3 tags for those files, then pack it again with xar:
cd work && xar -cf ../myroot2.pkg *
I get a package that starts installation ok with my background etc., but when it comes time to install my .app I get these errors (from /var/log/install.log):
run preupgrade script for myroot
Could not create task for action: run preupgrade script for myroot2
Install failed: The Installer could not extract files from the package for myroot2. Contact the software manufacturer for assistance.
IFDInstallController 863170 state = 7
I have also tried Flat Package Editor: open myroot.pkg, drag out Distribution, edit it, drag it back, delete old Distribution, save. Same problem as with xar.
I would prefer to have a fully scriptable solution as opposed to using GUIs.
Edit: I have also tried to use pkgutil to expand, edit Distribution, and reflatten a flat package. This gets the icons and readme in the installer, but the installer is then unable to unpack the payload. Same if I reflatten with Flat Package Editor. I have also tried to create an expanded package without PackageMaker (which works, except on 10.8), but when I try to flatten that with pkgutil the result is a corrupted package again.
A: PackageMaker always was buggy has hell, and got deprecated with Mac OS X 10.6 Snow Leopard.
You should use pkgbuild together with productbuild.
A: This Mac Installers Blog has some useful posts about Packagemaker including details about the usage and solutions to common problems. Hope it will help.
A: Check out the Luggage - it's a Makefile helper file that lets you create OS X packages with sane Makefiles. Disclaimer: I am the original author for it, though there are a lot of other people's contributions in it now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11803972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MapReduce/Aggregate operations in SpringBatch Is it possible to do MapReduce style operations in SpringBatch?
I have two steps in my batch job. The first step calculates average. The second step compares each value with average to determine another value.
For example, Lets say i have a huge database of Student scores. The first step calculates average score in each course/exam. The second step compares individual scores with average to determine grade based on some simple rule:
*
*A if student scores above average
*B if student score is Average
*C if student scores below average
Currently my first step is a Sql which selects average and writes it to a table. Second step is a Sql which joins average scores with individual scores and uses a Processor to implement the rule.
There are similar aggregation functions like avg, min used a lot in Steps and I'd really prefer if this can be done in Processors keeping the Sqls as simple as possible. Is there any way to write a Processor which aggregates results across multiple rows based on a grouping criteria and then Writes Average/Min to the Output table once?
This pattern repeats a lot and i'm not looking for a Single processor implementation using a Sql which fetches both average and individual scores.
A: It is possible. You do not even need more than one step. Map-Reduce can be implemented in a single step. You can create a step with ItemReader and ItemWriter associated with it. Think of ItemReader -ItemWriter pair as of Map- Reduce. You can achieve the neccessary effect by using custom reader and writer with propper line aggregation. It might be a good idea for your reader/writer to implement Stream interface to guarantee intermediate StepContext save operation by Spring batch.
I tried it just for fun, but i think that it is pointless since your working capacity is limited by single JVM, in other words: you could not reach Hadoop cluster (or other real map reduce implementationns) production environment performance. Also it will be really hard to be scallable as your data size grows.
Nice observation but IMO currently useless for real world tasks.
A: I feel that a batch processing framework should separate programming/configuration and run-time concerns.It would be nice if spring batch provides a generic solution over a all major batch processing run times like JVM, Hadoop Cluster(also uses JVM) etc.
-> Write batch programs using Spring batch programming/Configuration model that integrates other programming models like map-reduce ,traditional java etc.
-> Select the run-times based on your need (single JVM or Hadoop Cluster or NoSQL).
Spring Data attempts solve a part of it, providing a unified configuration model and API usage for various type of data sources.).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6120654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: React view not updating even if the state is changing I'm trying to create a HackerNews with reddit.json
I'm fetching the data that's returining an array and i'm storing it in a variable
For the moment in my view i can only acess a fake json data:
results= [
{'author' : Mister1,'url':'http://url1.com','score':400},
{'author' : Mister2,'url':'http://url2.com','score':350},
{'author' : Mister3,'url':'http://url3.com','score':500},
{'author' : Mister4,'url':'http://url1.com','score':456},
]
so when i change the topic i want to search in the bar, the state is changing and i'm getting what i want, my problem is the view it's not updating and stying with the old result
The problem i think is comming from my render code :
const list = (
results
&&
results[searchKey]
&&
results[searchKey].hits
) || [
{'author' : Mister1,'url':'http://url1.com','score':400},
{'author' : Mister2,'url':'http://url2.com','score':350},
{'author' : Mister3,'url':'http://url3.com','score':500},
{'author' : Mister4,'url':'http://url1.com','score':456},
]
even if the result is changing it's stying with the fake json data.
My code : https://codesandbox.io/embed/mqpjrk3loy
Sorry if my question is dumb.
A: I could be wrong, but I think it could be the || operator. Have you tried a ternary operator?
{results ? results[searchKey].hits : ' // your hardcoded data '}
A: If I understand correctly, you are trying too set list variable as results[searchKey].hits, which have the wrong shape with your this.state.results
What you really want is this:
(results && results.results) || HARDCODED_FALLBACK_DATA
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53602870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: correct method to Use sub string in where clause mysql query I have a table in mysql with column called type. contents are below
Type
Test 12
Test abc
start 1
start abcd
end 123
Now I want to select records where type starts with Test
Expected result:
Test 12
Test abc
But I am getting either
Test 12
or empty results
I have tried like below:
select * from table where type = 'Test 12'
select * from table where type = '%Test%'
select * from table where type = '%Test'
What should be the correct sql statement.
A: If you want to do partial matches you need the LIKE operator:
SELECT * FROM table WHERE type LIKE 'Test%'
A: Use the Like keyword
select * from table where type LIKE 'Test%'
A: The equality (=) operator doesn't accept wild cards. You should use the like operator instead:
SELECT * FROM table WHERE type LIKE 'Test%'
A: Sooo close! You want to start with the string, then don't use % in the start, and use LIKE instead of =
select * from table where type LIKE 'Test%'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46411733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sort the list by the field of another table There are two tables:
Table1
Id
Name
Table2
Id
Table1ID(foreign key Table1 ID)
Date
With EntityFramework I use:
var list = db.Table1.Where(some selection).ToList();
How can I sort "list" by "Date" field in Table2?
A: Using OrderBy on Table2.Date
var list = db.Table1.Where(some selection)
.Where(x => x.Table2.Count() > 0)
.OrderBy(x => x.Table2.FirstOrDefault().Date)ToList();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31502993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to resolve java result 1 errors How to resolve 1 particular flavor of 'java result 1' in the context of using JVMTI agents?
A: Here's how I resolved an issue in my context:
The server is run through an ANT script with jvm configured with an agent (the property name 'agentfile' below is associated with a value pointing to the agent library)
Now, I would get the error 'java result 1' whenever the server was run, without any indication of the actual error.
Here's how this issue was debugged.
1) The agent was turned off (i.e.) the above 2 lines were commented out.
2) Then when ANT was run, the actual error message was clearly shown - the problem was: a class file was missing. This error was being eaten by the agent, since it is low level C code and just looks to load a class that it cannot find and throws the Java error.
Lesson learnt: if you have an agent, turn it off and then run your ANT - it may throw up the reasons for error seen. This is of course one of many scenarios noticed for the java result 1 error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4230940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to filter arrays in json based on specific value using jq I am trying to make a filter using jq to filter the arrays in this json to get only the arrays that have "policy_id": 199383 and exclude the arrays that contain different policy_id value.
{
"links": {
"policy_id": 199383,
"violations": [
69892478
]
},
"incident_preference": "PER_CONDITION_AND_TARGET",
"closed_at": 1519408001909,
"opened_at": 1519407125437,
"id": 17821334
}
{
"links": {
"policy_id": 199383,
"violations": [
69889831
]
},
"incident_preference": "PER_CONDITION_AND_TARGET",
"closed_at": 1519408011851,
"opened_at": 1519406230858,
"id": 17820349
}
{
"links": {
"policy_id": 194774,
"violations": [
68446755
]
},
"incident_preference": "PER_POLICY",
"closed_at": 1518835775531,
"opened_at": 1518835745303,
"id": 17422347
}
{
"links": {
"policy_id": 199383,
"violations": [
69892488
]
},
"incident_preference": "PER_CONDITION_AND_TARGET",
"closed_at": 1519402345676,
"opened_at": 1519401235467,
"id": 17821334
}
I tried this :
jq '.incidents[] | select (.links.policy_id == "199383")' file.json. But not having anything in return ? Can anyone help.
Thank you
A: jq '.incidents[]| select(.links.policy_id==199383)' file.json
should do it.
Output
{
"links": {
"policy_id": 199383,
"violations": [
69892478
]
},
"incident_preference": "PER_CONDITION_AND_TARGET",
"closed_at": 1519408001909,
"opened_at": 1519407125437,
"id": 17821334
}
{
"links": {
"policy_id": 199383,
"violations": [
69889831
]
},
"incident_preference": "PER_CONDITION_AND_TARGET",
"closed_at": 1519408011851,
"opened_at": 1519406230858,
"id": 17820349
}
{
"links": {
"policy_id": 199383,
"violations": [
69892488
]
},
"incident_preference": "PER_CONDITION_AND_TARGET",
"closed_at": 1519402345676,
"opened_at": 1519401235467,
"id": 17821334
}
From json.org
A string is a sequence of zero or more Unicode characters, wrapped in
double quotes, using backslash escapes. A character is represented as
a single character string. A string is very much like a C or Java
string.)
and
A number is very much like a C or Java number, except that the octal
and hexadecimal formats are not used.
So 199383 is clearly different from "199383". They are number and string respectively.
Note : Emphasis in quoted text are mine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48956030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change php variable depending on what selected in dropdown I want to create a page on my website which will be used to view users profiles. When the user first visits the page I want it show their own profile. But I want to put in a drop-down menu or something which will give them the ability to view other users profiles. I haven't started creating this yet however I just want to know if what I want to achieve is possible with what I have planned.
What I am thinking of doing is have a php variable which would be $UserID or something.
To start with $UserID would be equal to the current user viewing the page's id e.g. 1 for Admin.
Then I would get all the data from the database through that variable $UserID.
But in order to view other user's profiles I want to change that $UserID variable depending on which user's name is selected in the dropdown.
e.g. If dropdownuser = Test3 then $UserID = 5.
Then it would display Test3's user profile.
Have I got this correct??
A: Usually this is done on two separate pages: profile of the current user (my profile) and general profile page.
On my profile page you use the logged in user's ID, something like $_SESSION['user-id'] and on general profile pages you use the ID from a drop down or whatever coming through the URL so something like $_GET['user-id'].
A: Correct. When you query the database, pass in an ID so it get's the info for that specific ID
$select = $db->query('SELECT id, name, info FROM table WHERE id = :id');
$select->execute(array(':id' => $_POST['id']));
and your html would be
<form method="post">
<select name="id">
<option value="1">Person 1</option>
<option value="2">Person 2</option>
</select>
<input type="submit" value="Select user" />
</form>
A: Basically, you can achieve what you want, just note that PHP script is not active while user watches a page. It works just when the page loads (or reloads). So, you will need to reload the page when user changes the selected item in the dropdown. That is easily achievable, simply make it in onchange event handler.
There is another way of doing it: AJAX. You can invoke the server-side not on page load, but on some internal page event (like dropdown selected index change). Then the page would not reload, but you will need to properly handle AJAX response. For the server it would be like a new page is being loaded. Read more about ajax.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18374491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Memory Leak: Issues with releasing NSArray in iPhone app I have a code which shows leaks in Instruments. It shows leaks where I initialize the arrayDetPerformance with the contents of arrayDetail
If I release my arrayDetail then my app crashes.
What could be wrong?
Here is the code:
NSDictionary *finalResult = [extractUsers JSONValue];
// NSLog(@" Stamp-16 : %@",[NSDate date]);
NSLog(@"Array2 : %d",[arrayDetail retainCount]); //RETAIN COUNT IS 0
arrayDetail = [[finalResult objectForKey:@"Detail"]
NSLog(@"Array2 : %d",[arrayDetail retainCount]); //RETAIN COUNT IS 2
// NSLog(@"Data is : %@",array1);
// NSLog(@" Stamp-17 : %@",[NSDate date]);
//NSLog(@"Final Value is : %@",[[allUsers objectAtIndex:0] valueForKey:@"password"]);
//[self setUserData:allUsers];
//[tblView reloadData];
[responseString release];
[request release];
}
//sleep(0.3);
//[inProgressIndicator stopAnimating];
[fileContents release];
//Release all the allocated data
[json release];
//label.text = @"Finish";
// NSLog(@" Stamp-19 : %@",[NSDate date]);
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
//NSLog(@"Array2 : %d",[array2 retainCount]);
arrayDetPerformance = [[NSMutableArray alloc] initWithArray:arrayDetail];
chartPoints= [arrayDetPerformance valueForKey:@"Points"];
NSLog(@"Chart Points: %@",chartPoints);
[def setObject:chartPoints forKey:@"yarray"];
[def setObject:@"YES" forKey:@"flagThumb"];
//array1 = [[NSMutableArray alloc] initWithObjects:@"New",@"Table",@"View",nil];
//[self.Dettable reloadData];
//sNSFileManager *fileManager = [NSFileManager defaultManager];
//[array2 release];
NSLog(@"ArrayDEtPerfomance : %d",[arrayDetPerformance retainCount]);
NSLog(@"array2 : %d",[arrayDetail retainCount]);
if([chartPoints count]>0)
{
PlotItem *plotItem = [[PlotGallery sharedPlotGallery] objectAtIndex:0];
[plotItem imageHive:Fund];
}
//[arrayDetail release];
}
Memory leak is shown on the line
arrayDetPerformance = [[NSMutableArray alloc] initWithArray:arrayDetail];
Also I am confused on why the retain count directly goes from 0 to 2 in the below code:
NSLog(@"Array2 : %d",[arrayDetail retainCount]); //RETAIN COUNT IS 0
arrayDetail = [[finalResult objectForKey:@"Detail"]
NSLog(@"Array2 : %d",[arrayDetail retainCount]); //RETAIN COUNT IS 2
What could be wrong?
A: It shows a leak because you allocate arrayDetPerformance and then not release it. Simple as that. At least that's what we can tell from the code you are showing us.
As for the rest, don't use retainCount to debug memory problems, ever! You have to understand the simple memory management rules and follow them, nothing else. Since you don't know what Apple's underlying code does, you cannot rely on the retain count of an object.
As to your question relating to this code:
NSLog(@"Array2 : %d",[arrayDetail retainCount]); //RETAIN COUNT IS 0
arrayDetail = [[finalResult objectForKey:@"Detail"]
NSLog(@"Array2 : %d",[arrayDetail retainCount]); //RETAIN COUNT IS 2
You are assigning a whole other object to arrayDetail so it's completely meaningless to compare any properties of arrayDetail before and after the assignment. The retain count could be all over the place and it would not tell you anything.
I get the impression that you don't really know what you are doing here. You should read the memory management rules again and again until you understand them thoroughly.
A: retainCount won't help you debug your problem (in fact it will almost never be relevant to debugging, so best forget it's even there).
Don't release arrayDetail, as you don't own it. The problem is with arrayDetPerformance. You're allocing an object on that line, and it's not being released anywhere. Now, you may be doing that elsewhere in your code, but if you aren't, send it a release when you've finished using it.
Edit
If you're deallocating arrayDetPerformance in your dealloc method, I'm assuming it's an instance variable? In this case, you can't assume that it doesn't already point at an object, so you should send it a release before assigning it to the new object.
Alternatively, if it is configured as a property, just use self.arrayDetPerformance = ... which will take care of the memory management for you.
A: Do not call retainCount
retainCount is useless. The absolute retain count of an object is an implementation detail. The rule is simple; if you cause something to be retained, you must cause it to be released when you are done with it. End of story.
The memory management documentation discusses this fully.
First, retainCount can never return zero. The only time you'll get a zero is if you happened to message nil. This:
NSLog(@"Array2 : %d",[arrayDetail retainCount]); //RETAIN COUNT IS 0
arrayDetail = [[finalResult objectForKey:@"Detail"]
NSLog(@"Array2 : %d",[arrayDetail retainCount]); //RETAIN COUNT IS 2
You are causing arrayDetail to point to a different object on that second line. Thus, no relation between the retain count before/after that line.
When leaks tells you a leak is on a particular line like this one...
arrayDetPerformance = [[NSMutableArray alloc] initWithArray:arrayDetail];
... it is telling you that said object allocated on that line was leaked. It is not telling you that particular line was the cause of the leak. The leak is likely because you either over-retained it somewhere else or forgot to leak it.
You've said in several comments that you are "deallocating [something] in your dealloc". Show your dealloc method's implementation.
A: [arrayDetPerformance release]; is not written in your code;
So, its show memory leak.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5675481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check if current user is owner of GitHub remote in zsh I'm trying to write a git pre-push hook that performs some actions prior to pushing to origin if the person pushing is the repo's owner. Is there a way to check this in bash/zsh?
A: You can do this if the user is using HTTPS. You'd need to use the authenticated user endpoint to find the user ID of the current user, say, using curl, and then see if that user is the same as the owner of the repository by checking the URL.
To get the appropriate credentials, you can take the remote URL (e.g., https://github.com/git/git.git) and pipe it to git credential fill to find the username and password, like so:
echo url=https://github.com/git/git.git | git credential fill
The output format is defined in the git-credential man page. These credentials should also be able to be used for the API to make your request, although note that since curl requires the password to be passed on the command line, you will expose those credentials to anyone else on the machine. A non-shell option may be a more security-conscious choice.
Technically, there are also ways to determine this via SSH, but those rely on parsing fixed output that is subject to change, and as such, you should assume that you cannot get that information for SSH remotes.
Note that this tells you the current user, which you can check against the URL, but it doesn't tell you whether the user has administrative privileges on a repo that they don't own themselves (such as one owned by an organization). Since you haven't told us what you want to do with this information, we can't help you out there, although if you're trying to use the API, you can just do it and see if it succeeds or not.
Since you are using the user's credential store in this case, you need to be explicit and up front with the user about what you're doing so that the user isn't surprised by your use of the credentials. It would be unethical and probably illegal to use the user's credentials in the way I've described without their knowledge and consent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58665382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JSF Datatable link to another page I've got this table:
<p:dataTable value="#{requestBean.requestsList}" var="requestClass" style="width:50px;" id="requestList">
<p:column>
<f:facet name="header">
<h:outputText value="ID" />
</f:facet>
<h:outputText value="#{requestClass.requestID}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Status" />
</f:facet>
<h:outputText value="#{requestClass.requestStatus}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Details" />
</f:facet>
<h:outputText value="#{requestClass.requestTitle}" />
</p:column>
</p:dataTable>
Now the rows display the data properly but I want to be able to click on a record ID. When I do I go to another page e.g. review.xhtml where the url parameter would be that ID. So something like this: review.xhtml?id="clicked request". How is that done?
Update: I tried this and it did kinda work, but is it correct in practice?
<p:column>
<f:facet name="header">
<h:outputText value="ID" />
</f:facet>
<a href="review.xhtml?id=#{requestClass.requestID}">
<h:outputText value="#{requestClass.requestID}" />
</a>
</p:column>
A: Try this one:
<p:column>
<f:facet name="header">
<h:outputText value="ID" />
</f:facet>
<h:link outcome="review" value="#{requestClass.requestID}" >
<f:param name="id" value="#{requestClass.requestID}" />
</h:link>
</p:column>
A: try this code
<h:outputLink value="#{bean.url}">
<h:outputText value="Go to another page."/>
<f:param name="paramid" value="#{bean.id}" />
</h:outputLink>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8551706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change stream update and array of sub document update need help on writing some proper aggregation for change stream
I am getting data some thing like
{
"_id": {
"$oid": "6285ee2b91c6e50012a76e0b"
},
"status": "new",
"lastUpdatedData": {
"timestamp": {
"$date": {
"$numberLong": "1670602175000"
}
},
"priority": 0,
"gps": {
"longitude": 0,
"latitude": 0,
"altitude": 0,
"angle": 0,
"satellites": 0,
"speed": 0
},
"event_id": 0,
"properties_count": 8,
"ioElements": [
{
"id": 239,
"label": "Ignition",
"value": 0,
"valueHuman": "Ignition Off",
"valueDB": 0,
"_id": {
"$oid": "63935e17ac1fa5b006927e26"
}
},
{
"id": 240,
"label": "Movement",
"value": 0,
"valueHuman": "Movement Off",
"valueDB": 0,
"_id": {
"$oid": "63935e17ac1fa5b006927e27"
}
},
{
"id": 200,
"label": "Sleep Mode",
"value": 2,
"valueHuman": "Deep Sleep",
"valueDB": 2,
"_id": {
"$oid": "63935e17ac1fa5b006927e28"
}
},
{
"id": 67,
"label": "Battery Voltage",
"value": 3791,
"valueHuman": "3.791 V",
"valueDB": 3.791,
"_id": {
"$oid": "63935e17ac1fa5b006927e2b"
}
},
{
"id": 68,
"label": "Battery Current",
"value": 0,
"valueHuman": "0 A",
"valueDB": 0,
"_id": {
"$oid": "63935e17ac1fa5b006927e2c"
}
}
]
},
"category": "companyCar"
}
*
*My first question is regarding updating the ‘ioElements’ array and I want to update
{
"id": 239,
"label": "Ignition",
"value": 0,
"valueHuman": "Ignition Off",
"valueDB": 0,
}
to
{
"id": 239,
"label": "Ignition",
"value": 1,
"valueHuman": "Ignition On",
"valueDB": 1,
}
I want to perform a kind of upsert on ioElements array i.e update the existing fields with new fields if any new object is present inside ioElements I receive I need to push to ioElements array how to achieve this in an effective way. My current implementation
ioElements.forEach(async (singleIoEle) => {
const ioElementExist = await Vehicle.findOne({
_id: mongoose.Types.ObjectId(vehicleId),
"lastUpdatedData.ioElements.id": singleIoEle.id,
});
if (ioElementExist) {
await Vehicle.updateMany(
{
_id: mongoose.Types.ObjectId(vehicleId),
"lastUpdatedData.ioElements.id": singleIoEle.id,
},
{
$set: {
"lastUpdatedData.ioElements.$": {
...singleIoEle,
},
},
}
);
} else {
await Vehicle.findByIdAndUpdate(
mongoose.Types.ObjectId(vehicleId),
{
$addToSet: { "lastUpdatedData.ioElements": { ...singleIoEle } },
}
);
}
}),
Can the above code be improved and perform update in effective way?
We also have a change stream opened to show updates on latest values on frontend my change stream aggregation pipeline
const ids = Array.of(ObjectId(...vehicleIds));
const pipeline = [
{
$match: {
operationType: 'update',
'documentKey._id': { $in: ids }
},
},
];
Now issue is this pipeline is triggered on each of ioElement is updated which is creating load on servers. I want to get update only once when my updating code has finished(get update not everytime a single ioElement is update rather get update only one after all the single ioElements are written)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74768143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript package or plugin to create network diagrams with IPs Is there a plugin or a package where I can create visual network diagrams like in cisco packet tracer, so that our technicians can request their network schedule per customer.
I have already seen protovis and infovis go by, but it can not do what I really want.
What I actually want is something like the picture.
If you need more information, let me know and if the question is wrong, do not hesitate to correct me.
thank you in advance
A: Please look up https://gojs.net/latest/samples/index.html
- these are javascript based
- Individual classes are also available (which you can customize for a new visualization)
- It can be installed via npm, and, if you don't like it, can be easily removed from the system.
I hope this helps.
regards
SS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54130817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: recursion of objects and methods in python I wanna create a class which consist of parents and children and a recursion method to call the last child :
class MyClass:
def __init__(self,val,child =None):
self.val = val
self.child = child
def findLastChildVal(self):
if self.child ==None:
return self.val
return (...)
c = MyClass("I'm child")
p = MyClass("I'm parent",c)
p.findLastChildVal()
I have no Idea what to write instead of (...). It's confusing.
A: This is a classic recursion problem, in my opinion it will be much easier to use a static function instead of a member function:
class MyClass:
def __init__(self, val, child =None):
self.val = val
self.child = child
@staticmethod
def find_last_child_val(current_node: MyClass):
if current_node.child == None:
return current_node.val
else:
return MyClass.find_last_child_val(current_node.child)
c = MyClass("I'm child")
p = MyClass("I'm parent", c)
MyClass.find_last_child_val(p)
Update:
Pay attention that searching for a child using a recursion like this, is not efficient. find_last_child_val() runs in O(n) complexity. It is much more efficient to perform n iterations in a for loop instead of a recursion. If you can't think of a way to reduce the tree traversal complexity, I suggest using a different data structure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56820302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Constructing objects from data in multiple arrays: copy or reference the data? I have a data source that constructs multiple arrays of data. Each array are associated to each other by their offsets (all arrays are the same length). I am using a library that works on singular objects of this data through a public interface.
An example with two pieces of data a and b that make up single objects.
// three 'objects'
static int a[] = { 5, 6, 7};
static double b[] = {402, 24014, 52.3};
And I have this interface of the object that the library uses:
class ISomeInterface {
public:
virtual ~ISomeInterface{}
virtual int GetA() const = 0;
virtual double GetB() const = 0;
}
How would I best to get an interface 'view' this data if the ISomeInterface can be added to a vector, get sorted and filtered in the library.
std::vector<shared_ptr<ISomeInterface> > data;
Would I just construct a class that points to the index in the data arrays? Assuming the references to the array are accessible:
class MyClass : ISomeInterface {
public:
MyClass(int index) : _index(index) {};
virtual int GetA() const { return a[_index];}
virtual double GetB() const { return b[_index];}
private:
int _index;
}
Or I could just copy the data from the arrays to an object:
class MyClass2 : ISomeInterface {
public:
MyClass2(int a, double b) : _a(a), _b(b) {};
virtual int GetA() const { return _a;}
virtual double GetB() const { return _b;}
private:
int _a;
double _b;
}
I could potentially have a lot of data in these arrays, so I thought the first approach would avoid duplicating all the data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32382152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to use linearGradient in react-native-svg I have some SVG graphics that I would like to apply conditional styling on (e.g. linearGradient when it's active). How would I go about achieving this? I'd rather not (if there's another way) have to go in a manually add a defs tag with linearGradients in there, and I've seen stuff about using an externals defs file to access the fill I want (so I can specify either a solid color or gradient depending on state). I'm not sure how to ask, or where to look.
An example:
An SVG file:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 26 26">
<path d="M20.94 9.56c.74 0 1.35.62 1.35 1.38v1.84c0 3.79-2.48 7.85-6.44 8.81v1.36A3.02 3.02 0 0 1 12.88 26a3.02 3.02 0 0 1-2.97-3.05v-1.34c-3.36-.83-6.2-5.05-6.2-8.83v-1.84c0-.76.6-1.38 1.35-1.38.74 0 1.34.62 1.34 1.38v1.84a6.7 6.7 0 0 0 6.6 6.79 6.7 6.7 0 0 0 6.6-6.79v-1.84c0-.76.6-1.38 1.34-1.38ZM13.08 0c2.77 0 5 2.28 5 5.09v7.44c0 2.8-2.23 5.08-5 5.08-2.76 0-5-2.28-5-5.08V5.09a5.05 5.05 0 0 1 5-5.09Z" fill-rule="evenodd"/>
</svg>
Now - I have a LOT of these, so I was hoping I could link the gradient from an external source, or use some other way to just slap a linear gradient on top of them. Is there such a way? What would be the best way to add gradients to 100+ icons without having to go in and edit each one of them? Is there a bulk editor somewhere that I don't know about?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70369360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to click outside button and keep active style? - AlpineJS & TailwindCSS I'm using TailwindCSS and AlpineJS on this project. There are two buttons that switch tabs and the first one have autofocus. When a tab is switched, the other button becomes active:
I want the button to become inactive only when the other button is clicked. Is there a way to do this using AlpineJS and TailwindCSS? Something like bind the active class with @click.away.
Thanks in advance.
Here is my code:
<div class="flex flex-col">
<div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div class="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8">
<div x-data="{ openTab: 1, coin: 0 }" class="overflow-hidden border-b border-gray-200 shadow sm:rounded-lg">
<div class="flex items-center justify-between px-10 py-8 bg-white wrapper">
<div>
<h3 class="lg:text-2xl sm:text-lg">Saldos</h3>
<h1 class="font-normal lg:text-4xl sm:text-3xl">$0.00</h1>
</div>
<div class="inline-flex items-center justify-center mr-2">
<div aria-label="Lista" data-balloon-pos="up" id="show-tip">
<button class="p-1 mr-1 text-gray-500 rounded-lg outline-none active:text-gray-200 hover:text-gray-200 focus:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 1" autofocus>
<svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M9 2a1 1 0 000 2h2a1 1 0 100-2H9z"></path><path fill-rule="evenodd" d="M4 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v11a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm3 4a1 1 0 000 2h.01a1 1 0 100-2H7zm3 0a1 1 0 000 2h3a1 1 0 100-2h-3zm-3 4a1 1 0 100 2h.01a1 1 0 100-2H7zm3 0a1 1 0 100 2h3a1 1 0 100-2h-3z" clip-rule="evenodd"></path></svg>
</button>
</div>
<div aria-label="Alocação de Ativos" data-balloon-pos="up" id="show-tip">
<button class="p-1 mr-1 text-gray-500 rounded-lg outline-none hover:text-gray-200 focus:text-gray-200 active:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 2">
<svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M2 10a8 8 0 018-8v8h8a8 8 0 11-16 0z"></path><path d="M12 2.252A8.014 8.014 0 0117.748 8H12V2.252z"></path></svg>
</button>
</div>
</div>
</div>
<div x-show="openTab === 1">
etc
</div>
<div class="flex flex-col justify-between py-2 bg-white lg:flex-row sm:px-6 lg:px-8" x-show="openTab === 2">
etc
</div>
</div>
</div>
</div>
A: You can toggle classes using the Alpine.js x-bind:class object syntax, eg. :class="{ 'active classes': openTab === 1 }" for your first tab, see the following snippet. You could also bind :disabled="openTab !== 1" to disable the button (for the first button).
<div aria-label="Lista" data-balloon-pos="up" id="show-tip">
<button :class="{ 'active classes': openTab === 1 }" class="p-1 mr-1 text-gray-500 rounded-lg outline-none active:text-gray-200 hover:text-gray-200 focus:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 1" autofocus>
<svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M9 2a1 1 0 000 2h2a1 1 0 100-2H9z"></path><path fill-rule="evenodd" d="M4 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v11a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm3 4a1 1 0 000 2h.01a1 1 0 100-2H7zm3 0a1 1 0 000 2h3a1 1 0 100-2h-3zm-3 4a1 1 0 100 2h.01a1 1 0 100-2H7zm3 0a1 1 0 100 2h3a1 1 0 100-2h-3z" clip-rule="evenodd"></path></svg>
</button>
</div>
<div aria-label="Alocação de Ativos" data-balloon-pos="up" id="show-tip">
<button :class="{ 'active classes': openTab === 2 }" class="p-1 mr-1 text-gray-500 rounded-lg outline-none hover:text-gray-200 focus:text-gray-200 active:text-gray-200 focus:outline-none hover:bg-gray-700 focus:bg-gray-700" type="button" @click="openTab = 2">
<svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M2 10a8 8 0 018-8v8h8a8 8 0 11-16 0z"></path><path d="M12 2.252A8.014 8.014 0 0117.748 8H12V2.252z"></path></svg>
</button>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64702779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why doesn't os.system ignore SIGINT? I am reading Linux System Programming.
When introducing the system(command) function, the book states that during execution of the command, SIGINT is ignored.
So, assuming that os.system is just a wrapper of the underlying system function, I try the following:
loop.py
while True:
print 'You should not be able to CTRL+C me ;p'
test_loop.py
import os
os.system("python loop.py")
Now that I'm executing loop.py with system, I'm expecting SIGINT to be ignored, but when I use CTRL+C on the running program it still get killed.
Any idea why os.system differ from the system() function?
A: SIGINT is ignored by the application that calls system (for as long as system is executing). It's not ignored by the application that's spawned by system. So if you hit CTRL+c, that will abort the execution of loop.py, but not of test_loop.py. So if you add some code after the call to system, you'll see that that code will execute after you press CTRL+c.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18426975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Perfect minimal hash for mathematical combinations First, define two integers N and K, where N >= K, both known at compile time. For example: N = 8 and K = 3.
Next, define a set of integers [0, N) (or [1, N] if that makes the answer simpler) and call it S. For example: {0, 1, 2, 3, 4, 5, 6, 7}
The number of subsets of S with K elements is given by the formula C(N, K). Example
My problem is this: Create a perfect minimal hash for those subsets. The size of the example hash table will be C(8, 3) or 56.
I don't care about ordering, only that there be 56 entries in the hash table, and that I can determine the hash quickly from a set of K integers. I also don't care about reversibility.
Example hash: hash({5, 2, 3}) = 42. (The number 42 isn't important, at least not here)
Is there a generic algorithm for this that will work with any values of N and K? I wasn't able to find one by searching Google, or my own naive efforts.
A: There is an algorithm to code and decode a combination into its number in the lexicographical order of all combinations with a given fixed K. The algorithm is linear to N for both code and decode of the combination. What language are you interested in?
EDIT: here is example code in c++(it founds the lexicographical number of a combination in the sequence of all combinations of n elements as opposed to the ones with k elements but is really good starting point):
typedef long long ll;
// Returns the number in the lexicographical order of all combinations of n numbers
// of the provided combination.
ll code(vector<int> a,int n)
{
sort(a.begin(),a.end());
int cur = 0;
int m = a.size();
ll res =0;
for(int i=0;i<a.size();i++)
{
if(a[i] == cur+1)
{
res++;
cur = a[i];
continue;
}
else
{
res++;
int number_of_greater_nums = n - a[i];
for(int j = a[i]-1,increment=1;j>cur;j--,increment++)
res += 1LL << (number_of_greater_nums+increment);
cur = a[i];
}
}
return res;
}
// Takes the lexicographical code of a combination of n numbers and returns the
// combination
vector<int> decode(ll kod, int n)
{
vector<int> res;
int cur = 0;
int left = n; // Out of how many numbers are we left to choose.
while(kod)
{
ll all = 1LL << left;// how many are the total combinations
for(int i=n;i>=0;i--)
{
if(all - (1LL << (n-i+1)) +1 <= kod)
{
res.push_back(i);
left = n-i;
kod -= all - (1LL << (n-i+1)) +1;
break;
}
}
}
return res;
}
I am sorry I have an algorithm for the problem you are asking for right now, but I believe it will be a good exercise to try to understand what I do above. Truth is this is one of the algorithms I teach in the course "Design and analysis of algorithms" and that is why I had it pre-written.
A: This is what you (and I) need:
hash() maps k-tuples from [1..n] onto the set 1..C(n,k)\subset N.
The effort is k subtractions (and O(k) is a lower bound anyway, see Strandjev's remark above):
// bino[n][k] is (n "over" k) = C(n,k) = {n \choose k}
// these are assumed to be precomputed globals
int hash(V a,int n, int k) {// V is assumed to be ordered, a_k<...<a_1
// hash(a_k,..,a_2,a_1) = (n k) - sum_(i=1)^k (n-a_i i)
// ii is "inverse i", runs from left to right
int res = bino[n][k];
int i;
for(unsigned int ii = 0; ii < a.size(); ++ii) {
i = a.size() - ii;
res = res - bino[n-a[ii]][i];
}
return res;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14160942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the equivalent SOAP API call to the command *S? We have an agent desktop application that runs against the current PNR/session in Sabre Red. We're using Native API to interact with Sabre Red and we have a Sabre Red App.
If an agent begins to build a reservation/PNR and has NOT ended the current PNR, the data in GetReservation.ReservationPNRB.POS.Source.PseudoCityCode is empty. We need to know what PCC (Pseudo City Code) the agent is working it. Is there a way to 'get current context' (agent session) via SOAP API? The equivalent Sabre command would be *S. If not, I assume this value would be available within the Red App SDK and plug-in environment?
A: could be the SabreCommandLLSRQ which can be used to use host commands but using soap.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73887796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need assistance with below query I'm getting this error:
Error tokenizing data. C error: Expected 2 fields in line 11, saw 3
Code: import webbrowser
website = 'https://en.wikipedia.org/wiki/Winning_percentage'
webbrowser.open(website)
league_frame = pd.read_clipboard()
And the above mentioned comes next.
A: I believe you need use read_html - returned all parsed tables and select Dataframe by position:
website = 'https://en.wikipedia.org/wiki/Winning_percentage'
#select first parsed table
df1 = pd.read_html(website)[0]
print (df1.head())
Win % Wins Losses Year Team Comment
0 0.798 67 17 1882 Chicago White Stockings best pre-modern season
1 0.763 116 36 1906 Chicago Cubs best 154-game NL season
2 0.721 111 43 1954 Cleveland Indians best 154-game AL season
3 0.716 116 46 2001 Seattle Mariners best 162-game AL season
4 0.667 108 54 1975 Cincinnati Reds best 162-game NL season
#select second parsed table
df2 = pd.read_html(website)[1]
print (df2)
Win % Wins Losses Season Team \
0 0.890 73 9 2015–16 Golden State Warriors
1 0.110 9 73 1972–73 Philadelphia 76ers
2 0.106 7 59 2011–12 Charlotte Bobcats
Comment
0 best 82 game season
1 worst 82-game season
2 worst season statistically
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55561151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to implement Transactions with Generic Repository Pattern? I am developing a .NET Core application where I leverage the Generic Repository pattern and I would like to know how can I implement a transaction:
IGenericRepository
public interface IGenericRepository<T>
{
Task InsertAsync(T insert);
Task<bool> RemoveAsync(object id);
Task UpdateAsync(T entity);
Task<T> GetByIdAsync(object id,string includeProperties="");
Task<IQueryable<T>> GetAsync(Expression<Func<T, bool>> filter=null,
int? skip=null,
int? take=null,
Func<IQueryable<T>,IOrderedQueryable<T>> orderBy = null,
string includeProperties = "");
Task SaveAsync();
}
I was looking at this implementation which uses UnitOfWork as well, but in .NET Core, I do not have a DbContextTransaction.
I am not using UnitOfWork yet. Currently my service looks like this:
public class SomeService
{
IGenericRepository<A> arepo;
IGenericRepository<B> brepo;
public SomeService(IGenericRepository<A> arepo,IGenericRepository<B> brepo)
{
this.arepo=arepo;
this.brepo=brepo;
}
public async Task DoTransaction(id)
{
var a=await arepo.GeyById(id)
await brepo.RemoveAsync(a.Id);
await brepo.SaveChangesAsync();
await arepo.InsertAsync([something]);
await arepo.SaveChanges();
}
}
I would want to make this transactional and also, avoid using SaveChangesAsync for all repositories that get involved.
What would be a solution?
A: Well I am not expert in entity framework, but I am answering in terms of repository and unit of work.
To begin with, avoid unnecessary wrapper of additional generic repository as you are already using full-ORM. Please refer to this answer.
but in .NET Core i do not have a DbContextTransaction.
The DbContextTransaction is important but not a key for implementing unit of work in this case. What is important is DBContext. It is DBContext that tracks and flushes the changes. You call SaveChanges on DBContext to notify that you are done.
I would want to make this transactional
I am sure there must be something available to replace DbContextTransaction or to represent transaction.
One way suggested by Microsoft is to use it as below:
context.Database.BeginTransaction()
where context is DbContext.
Other way is explained here.
also ,avoid using SaveChangesAsync for all repos that get involved
That is possible. Do not put SaveChanges in repositories. Put it in separate class. Inject that class in each concrete/generic repository. Finally, simply call SaveChanges once when you are done. For sample code, you can have a look at this question. But, code in that question have a bug which is fixed in the answer I provided to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59625929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get Inner HTML - PHP I have the following code:
$data = file_get_contents('http://www.robotevents.com/robot-competitions/vex-robotics-competition?limit=all');
echo "Downloaded";
$dom = new domDocument;
@$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(2)->getElementsByTagName('tr');
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
for ($i = 0; $i < $cols->length; $i++) {
echo $cols->item($i)->nodeValue . "\n";
}
}
The final field has an Link which I need to store the URL of. Also, The script outputs characters such as "Â". Does anyone know how to do/fix these things?
A: I would recommend not using DOM to parse HTML, as it has problems with invalid HTML. INstead use regular expression
I use this class:
<?php
/**
* Class to return HTML elements from a HTML document
* @version 0.3.1
*/
class HTMLQuery
{
protected $selfClosingTags = array( 'area', 'base', 'br', 'hr', 'img', 'input', 'link', 'meta', 'param' );
private $html;
function __construct( $html = false )
{
if( $html !== false )
$this->load( $html );
}
/**
* Load a HTML string
*/
public function load( $html )
{
$this->html = $html;
}
/**
* Returns elements from the HTML
*/
public function getElements( $element, $attribute_match = false, $value_match = false )
{
if( in_array( $element, $this->selfClosingTags ) )
preg_match_all( "/<$element *(.*)*\/>/isU", $this->html, $matches );
else
preg_match_all( "/<$element(.*)>(.*)<\/$element>/isU", $this->html, $matches );
if( $matches )
{
#Create an array of matched elements with attributes and content
foreach( $matches[0] as $key => $el )
{
$current_el = array( 'name' => $element );
$attributes = $this->parseAttributes( $matches[1][$key] );
if( $attributes )
$current_el['attributes'] = $attributes;
if( $matches[2][$key] )
$current_el['content'] = $matches[2][$key];
$elements[] = $current_el;
}
#Return only elements with a specific attribute and or value if specified
if( $attribute_match != false && $elements )
{
foreach( $elements as $el_key => $current_el )
{
if( $current_el['attributes'] )
{
foreach( $current_el['attributes'] as $att_name => $att_value )
{
$keep = false;
if( $att_name == $attribute_match )
{
$keep = true;
if( $value_match == false )
break;
}
if( $value_match && ( $att_value == $value_match ) )
{
$keep = true;
break;
}
elseif( $value_match && ( $att_value != $value_match ) )
$keep = false;
}
if( $keep == false )
unset( $elements[$el_key] );
}
else
unset( $elements[$el_key] );
}
}
}
if( $elements )
return array_values( $elements );
else
return array();
}
/**
* Return an associateive array of all the form inputs
*/
public function getFormValues()
{
$inputs = $this->getElements( 'input' );
$textareas = $this->getElements( 'textarea' );
$buttons = $this->getElements( 'button' );
$elements = array_merge( $inputs, $textareas, $buttons );
if( $elements )
{
foreach( $elements as $current_el )
{
$attribute_name = mb_strtolower( $current_el['attributes']['name'] );
if( in_array( $current_el['name'], array( 'input', 'button' ) ) )
{
if( isset( $current_el['attributes']['name'] ) && isset( $current_el['attributes']['value'] ) )
$form_values[$attribute_name] = $current_el['attributes']['value'];
}
else
{
if( isset( $current_el['attributes']['name'] ) && isset( $current_el['content'] ) )
$form_values[$attribute_name] = $current_el['content'];
}
}
}
return $form_values;
}
/**
* Parses attributes into an array
*/
private function parseAttributes( $str )
{
$str = trim( rtrim( trim( $str ), '/' ) );
if( $str )
{
preg_match_all( "/([^ =]+)\s*=\s*[\"'“”]{0,1}([^\"'“”]*)[\"'“”]{0,1}/i", $str, $matches );
if( $matches[1] )
{
foreach( $matches[1] as $key => $att )
{
$attribute_name = mb_strtolower( $att );
$attributes[$attribute_name] = $matches[2][$key];
}
}
}
return $attributes;
}
}
?>
Usage is:
$c = new HTMLQuery();
$x = $c->getElements( 'tr' );
print_r( $x );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20725068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I apply CSS stylesheets to a specific component? I'm working on Android app & web app in the same Next.js project and I want the recommended Ionic global stylesheets to not apply on web layout.
I have a client component imported in server component app/layout.tsx that looks like this:
<>
<WindowContextProvider>
{Capacitor.isNativePlatform() ? (
<NoSSRWrapper>
<NativeLayout>{children}</NativeLayout>
</NoSSRWrapper>
) : (
<WebLayout>{children}</WebLayout>
)}
</WindowContextProvider>
</>
In the NativeLayout is where I've imported all the Ionic global stylesheets but they still apply on the WebLayout, how can I fix this?
A: You can apply CSS using style tag inside the same specific component, Otherwise, you can apply CSS by targeting it with a specific class name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75043229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to reach UIPopoverController from its content view controller? I have a problem with iOS UIPopoverController. I have a UIPopoverController cleated like this:
- (UIPopoverController *)popover
{
if (!_popover)
{
_popover = [[UIPopoverController alloc] initWithContentViewController:self.viewController];
}
return _popover;
}
Is it possible somehow to reach UIPopoverController class object self.popover inside of ViewController class?
A: Good Option : Use delegate to dissmiss popover from contentView.
Another option : In iOS 8, you can dismiss the popover by using dismissViewControllerAnimated:completion: from within the popover. Note it doesn't work in iOS 7.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28854605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: insert UTF-8 characters into sql server 2008 table I'm inserting an email content text as UTF-8 string using php into an SQL server 2008 database table and it is working fine except one specific email.
The INSERT command fails with this error:
An error occurred translating the query string to UTF-16: No mapping for the Unicode character exists in the target multi-byte code page.
The text that causes it is an extension text of a phone number:
this "xF7" that supposed to be +91-98XXXXXXX (i added the XX) must have turned into UTF-16 or something?
before insert into the database I did a UTF-8 check using mb_detect_encoding:
$HTMLencode = mb_detect_encoding(HTMLString, mb_detect_order(), true);
$PLAINencode = mb_detect_encoding(PLAINString, mb_detect_order(), true);
as you can see I even take under consideration a "multipart email" - part of HTML and a part of PLAIN text.
both checks return UTF-8 (which means the "xF7" fooled me.. :))
I also did iconv() using UTF-8//IGNORE in order to ignore invalid characters,
nothing helps, how do I solve this in php?
The code above works fine for 99% of the emails except that one special one that raise this error.
A: 0xF7 encodes ÷ in Windows-1252. Are you just passing data directly to database?
You should use an email library that reads the email headers correctly, which state the character encoding that is being used in the email. The library would then ideally convert from that encoding to UTF-8 before handing it to you.
mb_detect_encoding is virtually useless because it just has access to the bytes and doesn't apply any heuristics either. It is especially useless if it gives UTF-8 for a string that has 0xF7, which cannot appear in UTF-8
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15926196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DateTime failed to open I have a problem with my DateTime function.
I'm using a function form different places
function newDateFormat($date, $format) {
$newdate = new DateTime($date);
if($format == '1')
{
$newdate = $newdate->format('Y-m-d H:i:s');
}elseif($format == '2'){
$newdate = $newdate->format('Y-m-d');
}
return $newdate;}
When I use this function for adding a new event in my fullcalendar its works fine.
But my problem is when I try to use it for an update to the calendar and it says
Warning: require(libs/DateFormat.php): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/coach/index.php on line 12
I have no such a file in my libs directory as it is from php.
any one knows ho to get this working?
Thanks for the help
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17821487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Injecting (implicit) value of abstract type into subtypes of trait Here is a simplification of my scenario that I am trying to make it work
// the UnrelatedN are mostly used as tag traits, for type-checking purposes
trait Unrelated1
trait Unrelated2
trait HasUnrelatedSupertrait {
type Unrelated // abstract type
}
trait HasUnrelated[... /*TODO: Parametrize with (factory of) UnrelatedN*/]
extends HasUnrelatedSupertrait {
type Unrelated = UnrelatedType // path-dependent type
implicit val unrelated = ... // instantiate or access (singleton) instance of Unrelated
}
trait Subtype1 extends HasUnrelated[/* Something involving Unrelated1 */] with ...
trait Subtype2 extends HasUnrelated[/* Something involving Unrelated2 */] with ...
// ... (many more similar subtypes)
Basically, I would like to inject the implicit val instance of
abstract type into (subtypes of) HasUnrelated in a non-intrusive
way, hopefully through a type parameter that I have some flexibility
over (see TODO).
(I don't care if Unrelated1/2 instances are constructed via new,
factory and how those factories are defined (as objects, classes
etc.), as long as I can get 2 distinct instances of Unrelated1/2.)
Some of the constraining factors why my attempts have failed are:
*
*HasUnrelated and HasUnrelatedSupertrait must be traits, not classes
*traits cannot have parameters (so I cannot pass (implicit) val factory)
*traits cannot have context or view bounds (to bring in ClassTag/TypeTag)
*I am not willing to clutter all the subtypes of HasUnrelated with
additional type/val declarations
However, I am willing to do one or more of the following changes:
*
*introduce (singleton) factories for Unrelated1/2
*introduce arbitrary inheritance in Unrelated1/2 as long as those
types are still unrelated (neither is subtype of the other)
*add supertype to HasUnrelated as long is it requires extra
declarations (if any) only in HasUnrelated, but not any of its subtypes
Is there a way to achieve this in Scala and if so how?
A: Probably type class is something you are looking for? Consider this example
trait Companion[T] {
val comp: T
}
object Companion {
def apply[T: Companion] = implicitly[Companion[T]]
}
object UnrelatedType {
implicit val thisComp =
new Companion[UnrelatedType.type] {
val comp = UnrelatedType
}
}
// Somewhere later
type Unrelated = UnrelatedType
implicit val unrelated = Companion[UnrelatedType]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35442977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Git won't add file I am changing and there is no gitignore I have this file inside my project, and no matter how many changes I make to it, git won't add the change.
There is no .gitignore file. And the file is inside the project. I did try --force and I tried git add --all. Nothing helps. I do remember using git add on the entire directory where the file is. Maybe that's the problem.
A: I never saw a single .gitignore file that prevented me from adding and committing the file in question. However I do remember removing that file from commit using Tortoise.
In any case, I solved the issue by renaming the file, adding it, and committing it, and later on, giving the file its former name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47438224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: Line numbers in jtextpane in Netbeans I am using Netbeans 7.1. are there any option for displaying line numbers in jtextpane?
A: You can try using Text Component Line Number.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8995431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Writing a wrapper to malloc with void as return type I have a requirement to write a wrapper to malloc with return type as void . the exact signature of the function would be
void mymalloc_wrapper(size_t size).
Any suggestion as to how this can be achieved/is it possible at all ?.
A: With your signature, the only thing you can do is:
void mymalloc_wrapper(size_t size) {
malloc(size);
}
Wonderful, you have allocated memory and you have lost the pointer to it. That's not a good idea.
If you want a void function, you can pass a pointer to return the pointer to allocated memory:
void mymalloc_wrapper(size_t size, void** ptr) {
*ptr = malloc(size);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31512047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to access mongoDB atlas from google cloud function using serverless VPC I have a google cloud function which needs to access the MongoDB hosted on Atlas (GCP).
This cloud function needs to access a specific API hosted outside GCP. For security reasons they need to allow the cloud functions IP address on their firewall rules.
To enable the static IP address request, I created a serverless VPC connector and configured all the egress traffic for my cloud function.
Once I configured, the connection for mongoDB from my cloud function is failing even if I allow all incoming traffic (just for testing).
I was thinking of VPC peering to allow cloud functions to access mongoDB, but I have not been able to configure it yet. The VPC pairing shows as "PENDING" state.
*
*Does Serverless VPC guarantee static IP address?
*Why am I not able to connect to mongoDB via serverless VPC connector even though all incoming traffic is allowed?
*Can we configure VPC peering between serverless VPC and mongodb atlas?
A: *
*Yes, Serverless VPC access guaranty a static IP address is you perform the correct set up (use a Cloud Nat and a router for routing the Serverless VPC Access IP-Range through Cloud Nat and use a static IP in Cloud Nat)
*You aren't able to reach MongoDB via serverless VPC connector because your routes aren't well defined, and because of the point 3
*You can perform a peering between MongoDB Atlas and your VPC. For this, follow this page. If you peering is in pending state, I think that is because the GCP part has not been performed. Then define correctly your route and be sure that your firewall allow communication, and that should work!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60969161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Moving Project folder within solution in VSS I have a solution in VSS with this structure (simplified):
Solution1
|-Project1
|-Project2
|--Project2
|-Project3
You see the second Project2 folder?
Somehow it got inside that wrapping project2 folder.
How can I move painlessly all content of Project2 one level up,
so that I wont have Project2/Project2?
Thanks
A: You can try the steps below:
*
*Backup the solution
*Open VSS Explorer, move project2 folder
*Open VS, go to File->Source Control->Change Source Control, update the server path of Project2
*Save the solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25493493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble with WCF and WAS with web site and web service in separate application pools None of the members of my team has ever been able to get a particular WCF service in our solution to work on our local machines. We've inherited it in legacy code and are trying to replace it, but it's very difficult to tell what it's doing since we can't run the debugger on it and we can't even get a response from it while debugging the main site that uses it.
The main part of our application is a web site. This particular service is hosted in a separate application pool on IIS due to some problems with using Excel interops (which this service uses) in the same app pool as the main site.
The service appears to use net.tcp for the protocol, and I have enabled the Windows Communication Foundation Non-HTTP Activation feature on my machine. I have also enabled the protocol on the Default Website and the node underneath it which is the WCF service in question (is this redundant?).
I can attach the debugger to w3wp.exe processes for both the site and the service. When the site makes the call to the service, however, an error is immediately returned and no breakpoints in the service are hit. The error reads:
The service 'MySvc.svc' cannot be activated due to an exception during
compilation. The exception message is: The type 'MyNamespace.MySvc',
provided as the Service attribute value in the ServiceHost directive,
or provided in the configuration element
Note, I have obviously redacted the real service name, etc, from this post. After attempting to follow solutions proposed on numerous similar questions, I have gotten nowhere. I am wondering if the problem is exacerbated by the separate app pools.
Below is the Web.config from the service project. The SVC file is named UploadAndImport.svc.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<!-- REDACTED SECTIONS PERTAINING TO LOGGING AND ENTERPRISE LIBRARY -->
</configSections>
<!-- REDACTED SECTIONS PERTAINING TO LOGGING AND ENTERPRISE LIBRARY -->
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.6.1" />
<identity impersonate="true" />
<pages controlRenderingCompatibilityVersion="4.0" />
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="ProjectName.UploadAndImport">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="" name="ExcelServiceEndPointHTTP" contract="ProjectName.IUploadAndImport" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<endpoint binding="netTcpBinding" bindingConfiguration="" name="ExcelServiceEndPointTCP" contract="ProjectName.IUploadAndImport" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!-- This line ignores the error that 'An ASP.NET setting has been detected that does not apply in Integratd managed pipeline mode (system.web/identity@impersonate is set to true)'-->
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
</configuration>
The directive in the SVC file looks like this:
<%@ ServiceHost Language="VB" Debug="true" Service="ProjectName.UploadAndImport" CodeBehind="UploadAndImport.svc.vb" %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36772508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Twilio MessagingResponse() after Flask redirect As in the Twilio Docs, I can make a MessagingResponse() object for sending a response text to my phone. However, what if I want to first redirect to an internal page? I am not able to simply make a MessagingResponse() in the redirected function, like I want to:
@app.route("/news", methods=['GET', 'POST'])
def news():
....
resp = MessagingResponse()
resp.message(msg)
return ""
@app.route("/", methods=['GET', 'POST'])
def hello():
return redirect("news")
I am not getting a text back if I use the above code. However, if I manually create a Client from twilio.rest as follows:
@app.route("/news", methods=['GET', 'POST'])
def news():
....
client = Client(account_sid, auth_token)
message = client.messages.create(to=request.values.get("From"), from_=request.values.get("To"),
body=msg)
I successfully do what I want to do. I don't understand why MessagingResponse() doesn't work when the request object is the same.
A: Your first snippet is how you respond to incoming text messages with XML or TwiML (one thing)
from twilio.twiml.messaging_response import MessagingResponse
while your second snippet is how you send text messages via REST API (another thing)
from twilio.rest import Client
Looking at your first snippet, if you're responding with an empty string to incoming text messages, you will not get a text back (Twilio will not do anything), as such:
instead of
return ""
try
return str(resp)
and make sure msg is not empty.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56204381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.