source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0028990677.txt" ]
Q: Pass a class instance to another class by reference I'm trying to pass a single instance of my "Status" class to all my other classes so that they can all set and get the status. I've been trying to do this by passing the "Status" class by reference into my "BaseStation" class. The code compiles fine but when I set the status from main and then get the status in "BaseStation" it has not changed. I think this should be possible so I must be missing something. Here is my main class #include "mbed.h" #include "Global.h" #include "MODSERIAL.h" #include "Status.h" #include "Sensors.h" #include "BaseStation.h" #include "Rc.h" #include "FlightController.h" #include "NavigationController.h" MODSERIAL _debug(USBTX, USBRX); //Unused analog pins DigitalOut _spare1(p16); DigitalOut _spare2(p17); DigitalOut _spare3(p18); DigitalOut _spare4(p19); //Classes Status _status; Sensors _sensors; BaseStation _baseStation; Rc _rc; FlightController _flightController; NavigationController _navigationController; int main() { _debug.baud(115200); DEBUG("\r\n"); DEBUG("********************************************************************************\r\n"); DEBUG("Starting Setup\r\n"); DEBUG("********************************************************************************\r\n"); //Set Status _status.initialise(); //Initialise RC //_rc.initialise(_status, p8); //Initialise Sensors //_sensors.initialise(p13, p14, p28, p27); //Initialise Navigation //_navigationController.initialise(_status, _sensors, _rc); //Initialise Flight Controller //_flightController.initialise(_status, _sensors, _navigationController, p21, p22, p23, p24); //Initalise Base Station _baseStation.initialise(_status, _rc, _sensors, _navigationController, _flightController, p9, p10); DEBUG("********************************************************************************\r\n"); DEBUG("Finished Setup\r\n"); DEBUG("********************************************************************************\r\n"); _status.setState(Status::STANDBY); int state = _status.getState(); printf("Main State %d\r\n", state); } Here is my Status.cpp #include "Status.h" Status::Status(){} Status::~Status(){} bool Status::initialise() { setState(PREFLIGHT); DEBUG("Status initialised\r\n"); return true; } bool Status::setState(State state) { switch(state) { case PREFLIGHT: setFlightMode(NOT_SET); setBaseStationMode(STATUS); setBatteryLevel(0); setArmed(false); setInitialised(false); _state = PREFLIGHT; DEBUG("State set to PREFLIGHT\r\n"); return true; case STANDBY: _state = STANDBY; DEBUG("State set to STANDBY\r\n"); return true; case GROUND_READY: return true; case MANUAL: return true; case STABILISED: return true; case AUTO: return true; case ABORT: return true; case EMG_LAND: return true; case EMG_OFF: return true; case GROUND_ERROR: return true; default: return false; } } Status::State Status::getState() { return _state; } bool Status::setFlightMode(FlightMode flightMode) { _flightMode = flightMode; return true; } Status::FlightMode Status::getFlightMode() { return _flightMode; } bool Status::setBaseStationMode(BaseStationMode baseStationMode) { _baseStationMode = baseStationMode; DEBUG("Base station mode set\r\n"); return true; } Status::BaseStationMode Status::getBaseStationMode() { return _baseStationMode; } bool Status::setBatteryLevel(float batteryLevel) { _batteryLevel = batteryLevel; return true; } float Status::getBatteryLevel() { return _batteryLevel; } bool Status::setArmed(bool armed) { _armed = armed; return true; } bool Status::getArmed() { return _armed; } bool Status::setInitialised(bool initialised) { _initialised = initialised; return true; } bool Status::getInitialised() { return _initialised; } bool Status::setRcConnected(bool rcConnected) { _rcConnected = rcConnected; return true; } bool Status::getRcConnected() { return _rcConnected; } Here is my status.h #include "mbed.h" #include "Global.h" #ifndef Status_H #define Status_H class Status // begin declaration of the class { public: // begin public section Status(); // constructor ~Status(); // destructor enum State { PREFLIGHT, STANDBY, GROUND_READY, MANUAL, STABILISED, AUTO, ABORT, EMG_LAND, EMG_OFF, GROUND_ERROR }; enum FlightMode { RATE, STAB, NOT_SET }; enum BaseStationMode { MOTOR_POWER, PID_OUTPUTS, IMU_OUTPUTS, STATUS, RC, PID_TUNING, GPS, ZERO, RATE_TUNING, STAB_TUNING, ALTITUDE, VELOCITY }; bool initialise(); bool setState(State state); State getState(); bool setFlightMode(FlightMode flightMode); FlightMode getFlightMode(); bool setBaseStationMode(BaseStationMode baseStationMode); BaseStationMode getBaseStationMode(); bool setBatteryLevel(float batteryLevel); float getBatteryLevel(); bool setArmed(bool armed); bool getArmed(); bool setInitialised(bool initialised); bool getInitialised(); bool setRcConnected(bool rcConnected); bool getRcConnected(); private: State _state; FlightMode _flightMode; BaseStationMode _baseStationMode; float _batteryLevel; bool _armed; bool _initialised; bool _rcConnected; }; #endif Here is my BaseStation.cpp #include "BaseStation.h" BaseStation::BaseStation() : _status(status){} BaseStation::~BaseStation(){} bool BaseStation::initialise(Status& status, Rc& rc, Sensors& sensors, NavigationController& navigationController, FlightController& flightController, PinName wirelessPinTx, PinName wirelessPinRx) { _status = status; _rc = rc; _sensors = sensors; _navigationController = navigationController; _flightController = flightController; _wireless = new MODSERIAL(wirelessPinTx, wirelessPinRx); _wireless->baud(57600); _wirelessSerialRxPos = 0; _thread = new Thread(&BaseStation::threadStarter, this, osPriorityHigh); DEBUG("Base Station initialised\r\n"); return true; } void BaseStation::threadStarter(void const *p) { BaseStation *instance = (BaseStation*)p; instance->threadWorker(); } void BaseStation::threadWorker() { while(_status.getState() == Status::PREFLIGHT) { int state = _status.getState(); printf("State %d\r\n", state); Thread::wait(100); } _status.setBaseStationMode(Status::RC); } Here is my BaseStation.h #include "mbed.h" #include "Global.h" #include "rtos.h" #include "MODSERIAL.h" #include "Rc.h" #include "Sensors.h" #include "Status.h" #include "NavigationController.h" #include "FlightController.h" #ifndef BaseStation_H #define BaseStation_H class BaseStation { public: BaseStation(); ~BaseStation(); struct Velocity { float accelX; float accelY; float accelZ; float gps; float gpsZ; float barometerZ; float lidarLiteZ; float computedX; float computedY; float computedZ; }; bool initialise(Status& status, Rc& rc, Sensors& sensors, NavigationController& navigationController, FlightController& flightController, PinName wirelessPinTx, PinName wirelessPinRx); private: static void threadStarter(void const *p); void threadWorker(); void checkCommand(); Thread* _thread; MODSERIAL* _wireless; Status& _status; Status status; Rc _rc; Sensors _sensors; NavigationController _navigationController; FlightController _flightController; char _wirelessSerialBuffer[255]; int _wirelessSerialRxPos; }; #endif The output when I run this is ******************************************************************************** Starting Setup ******************************************************************************** Base station mode set State set to PREFLIGHT Status initialised Rc initialised HMC5883L failed id check.IMU initialised Sensors initialised State 0 Base Station initialised ******************************************************************************** Finished Setup ******************************************************************************** State set to STANDBY Main State 1 State 0 State 0 I think this is because I'm not in fact passing a single instance of "Status" but copying it. How can I pass by reference properly? Thanks Joe A: int x = 42; int y = 9001; int& r = x; r = y; Now x is 9001. You have not changed anything about r. Similarly, in your code, although you accept a Status by reference, you then assign its value to a different object. You may only initialise references. In your case you want to chain them. Here's how you do what you want to do: struct Status {}; struct T { T(Status& _ref) // 1. Accept parameter by reference; : ref(_ref) // 2. Initialise member reference; {} // now this->ref is a reference to whatever _ref was a reference to Status& ref; }; int main() { Status s; T obj(s); // now obj holds a reference to s }
[ "stackoverflow", "0013582445.txt" ]
Q: Unable to build android test project with ant I have a sample Android app, created with Eclipse, having one Activity. I ran this command to build the ant build files for this project: android create project --target 8 --name SampleApp --path ./SampleApp --activity MainActivity --package com.example.sampleapp Running "ant debug" successfully builds the project and creates the apk files: -post-build: debug: BUILD SUCCESSFUL Total time: 1 second Now, I want to create an Android Test Project. I run this command: android create test-project -m ../SampleApp -n SampleAppTest -p SampleAppTest This successfully created the SampleAppTest directory containing the build files. I have a single class, src/com/example/sampleapp/MainActivityTest.java: package com.example.sampleapp; import android.test.ActivityInstrumentationTestCase2; public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> { public MainActivityTest() { super("com.example.sampleapp", MainActivity.class); } } I want to build this project. In the tutorial found here http://developer.android.com/tools/testing/testing_otheride.html#RunTestsAnt it says I should be able to do "ant run-tests". Unfortunately this target does not exist: $ ant run-tests Buildfile: /Users/cmuraru/Work/androidtest/SampleAppTest/build.xml BUILD FAILED Target "run-tests" does not exist in the project "SampleAppTest". Total time: 0 seconds If I try "ant debug" I receive an error when compiling, stating that the MainActivity class (from SampleApp) can not be found. -compile: [javac] Compiling 2 source files to /Users/cmuraru/Work/androidtest/build/test/classes [javac] /Users/cmuraru/Work/androidtest/SampleAppTest/src/com/example/sampleapp/MainActivityTest.java:15: cannot find symbol [javac] symbol: class MainActivity [javac] public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> { [javac] ^ [javac] /Users/cmuraru/Work/androidtest/SampleAppTest/src/com/example/sampleapp/MainActivityTest.java:18: cannot find symbol [javac] symbol : class MainActivity [javac] location: class com.example.sampleapp.MainActivityTest [javac] super("com.example.sampleapp", MainActivity.class); [javac] ^ [javac] 2 errors BUILD FAILED /Users/cmuraru/Work/android-sdk-macosx/tools/ant/build.xml:705: The following error occurred while executing this line: /Users/cmuraru/Work/android-sdk-macosx/tools/ant/build.xml:718: Compile failed; see the compiler error output for details. Total time: 1 second When trying "ant test", it also fails: test: [echo] Running tests ... [exec] INSTRUMENTATION_STATUS: id=ActivityManagerService [exec] INSTRUMENTATION_STATUS: Error=Unable to find instrumentation info for: ComponentInfo{com.example.sampleapp.tests/android.test.InstrumentationTestRunner} [exec] INSTRUMENTATION_STATUS_CODE: -1 [exec] android.util.AndroidException: INSTRUMENTATION_FAILED: com.example.sampleapp.tests/android.test.InstrumentationTestRunner [exec] at com.android.commands.am.Am.runInstrument(Am.java:616) [exec] at com.android.commands.am.Am.run(Am.java:118) [exec] at com.android.commands.am.Am.main(Am.java:81) [exec] at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method) [exec] at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:237) [exec] at dalvik.system.NativeStart.main(Native Method) What am I missing/doing wrong here? Any help is gladly appreciated. A: Okay, I spotted the problem. I failed to mention that in ant.properties, I've changed the out.dir location to "../build". Because of this, the compiler did not know where to get the class files of the SampleApp when building the SampleAppTest. So one solution is to delete the out.dir entry in ant.properties, but I did not want that. I had to find a way to tell the compiler where to get these classes. The solutions I found was to override the "-compile" target in build.xml like so: <property name="SampleApp.build.location" value="../build"/> <target name="-compile" depends="-build-setup, -pre-build, -code-gen, -pre-compile"> <do-only-if-manifest-hasCode elseText="hasCode = false. Skipping..."> <!-- merge the project's own classpath and the tested project's classpath --> <path id="project.javac.classpath"> <path refid="project.all.jars.path" /> <path refid="tested.project.classpath" /> </path> <javac encoding="${java.encoding}" source="${java.source}" target="${java.target}" debug="true" extdirs="" includeantruntime="false" destdir="${out.classes.absolute.dir}" bootclasspathref="project.target.class.path" verbose="${verbose}" classpathref="project.javac.classpath" fork="${need.javac.fork}"> <src path="${source.absolute.dir}" /> <src path="${gen.absolute.dir}" /> <compilerarg line="${java.compilerargs}" /> <classpath> <!-- steff: we changed one line here !--> <fileset dir="${SampleApp.build.location}/classes" includes="*"/> </classpath> </javac> <!-- if the project is instrumented, intrument the classes --> <if condition="${build.is.instrumented}"> <then> <echo level="info">Instrumenting classes from ${out.absolute.dir}/classes...</echo> <!-- build the filter to remove R, Manifest, BuildConfig --> <getemmafilter appPackage="${project.app.package}" libraryPackagesRefId="project.library.packages" filterOut="emma.default.filter"/> <!-- define where the .em file is going. This may have been setup already if this is a library --> <property name="emma.coverage.absolute.file" location="${out.absolute.dir}/coverage.em" /> <!-- It only instruments class files, not any external libs --> <emma enabled="true"> <instr verbosity="${verbosity}" mode="overwrite" instrpath="${out.absolute.dir}/classes" outdir="${out.absolute.dir}/classes" metadatafile="${emma.coverage.absolute.file}"> <filter excludes="${emma.default.filter}" /> <filter value="${emma.filter}" /> </instr> </emma> </then> </if> <!-- if the project is a library then we generate a jar file --> <if condition="${project.is.library}"> <then> <echo level="info">Creating library output jar file...</echo> <property name="out.library.jar.file" location="${out.absolute.dir}/classes.jar" /> <if> <condition> <length string="${android.package.excludes}" trim="true" when="greater" length="0" /> </condition> <then> <echo level="info">Custom jar packaging exclusion: ${android.package.excludes}</echo> </then> </if> <propertybyreplace name="project.app.package.path" input="${project.app.package}" replace="." with="/" /> <jar destfile="${out.library.jar.file}"> <fileset dir="${out.classes.absolute.dir}" includes="**/*.class" excludes="${project.app.package.path}/R.class ${project.app.package.path}/R$*.class ${project.app.package.path}/BuildConfig.class"/> <fileset dir="${source.absolute.dir}" excludes="**/*.java ${android.package.excludes}" /> </jar> </then> </if> </do-only-if-manifest-hasCode> </target>
[ "stackoverflow", "0026123740.txt" ]
Q: Is it possible to install aws-cli package without root permission? As title suggested, I haven't been able to find a good way to install aws-cli (https://github.com/aws/aws-cli/) without having the root access (or equivalent of sudo privileges). The way Homebrew setup on Mac is hinting at it may be possible, provided that a few directories and permissions are set in a way to facility future installs. However, I have yet to find any approach in Linux (specially, Red Hat Enterprise Linux or CentOS distroes). I am also aware of SCL from RHEL (https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Developer_Guide/scl-utils.html) But again, it requires sudo. A: There's a bundled installer for that purpose. Install aws command to $HOME/bin $ wget https://s3.amazonaws.com/aws-cli/awscli-bundle.zip $ unzip awscli-bundle.zip $ ./awscli-bundle/install -b ~/bin/aws Set $PATH environment variable $ echo $PATH | grep ~/bin // See if $PATH contains ~/bin (output will be empty if it doesn't) $ export PATH=~/bin:$PATH // Add ~/bin to $PATH if necessary Test the AWS CLI Installation $ aws help See the following link for details: http://docs.aws.amazon.com/cli/latest/userguide/awscli-install-bundle.html#install-bundle-user
[ "math.stackexchange", "0001920002.txt" ]
Q: Construct a homeomorphism between the punctured plane and the annulus How would I go about constructing a homeomorphism between $\Bbb R^2\setminus \{(0,0)\}$ and the annulus $\{\,(r,\theta)\mid 1<r<3\,\}$. I'm thinking we can represent all points in $\Bbb R^2$ as $\frac{e^{i\theta}}{r}$ we can still get to all points in the xy-plane but we can't have a radius of zero which is what we want. As far as $\theta$ goes we really only need $0\leq\theta\leq 2\pi$ and we can have a direct correspondence between the angles of points from each set, that is if I want to map a point from the plane with angle $\theta$ just map it to some point in the annulus with the same angle. The issue I am having is how to construct a function that will shrink $r\in\Bbb R^2\setminus \{(0,0)\} $ so that it lands between 1 and 3 and vice-versa. A: One example for a homeomorphism $(0,\infty)\to (1,3)$ would be $r\mapsto \frac2{r+1}+1=\frac{r+3}{r+1}$. A direct homeomorphism for the punctured plane and the annulus mihgt be $$(x,y)\mapsto\left(\frac{\sqrt{x^2+y^2}+3}{\sqrt{x^2+y^2}+1}\cdot \frac x{\sqrt{x^2+y^2}},\frac{x^2+y^2+3}{x^2+y^2+1}\cdot \frac y{\sqrt{x^2+y^2}}\right) $$ A: Note that $x\mapsto \tan x$ is homeomorphism of the bounded interval $(0,\pi/2)$ with the unbounded interval $(0,\infty)$. With some linear changes the domain can be changed to any open interval (of finite length). That is, the maps of the form $x\mapsto \tan (ax+b)$ for various real numbers $a,b, a\ne0$.
[ "mathoverflow", "0000225182.txt" ]
Q: Diameter of immersed surfaces with bounded from above mean curvature Is the following true? I cannot see a counterexample and it seems very intuitively clear, at least in the embedded case. Claim: Consider the set $S$ of closed immersed Riemann surfaces $\Sigma \subset (X,g)$ (I am particularly interested in spheres), with the magnitude of the mean curvature bounded from above by some $C>0$, where $X$ is also closed. Let $Vol(\Sigma)$ denote the area, and $Diam(\Sigma)$ the diameter. Then for every $\epsilon >0$ there is a $\delta>0$ s.t. if $$Vol (\Sigma) < \delta, \text{ then } Diam (\Sigma)< \epsilon $$ where $\Sigma \in S$. I really just want to say here that diameter of $\Sigma$ can be assured to be arbitrarily small by requiring that its volume is small. edit 1: For more clarity let me add that $\epsilon, \delta$ above are assumed to depend on $\Sigma, X, g$. edit 2: $C$ should be upper bound for magnitude of the mean curvature. A: Assuming I am interpreting your question correctly, this is true when the ambient space is Euclidean and the submanifold is closed (i.e. compact and without boundary). To see this one may invoke a result of Topping that bounds the (intrinsic) diameter of a closed, immersed submanifold of dimension $m$ by the $L^{m-1}$ norm of mean curvature over the immersed submanifold, e.g. for a surface take the $L^1$ norm (this scales correctly). For a general ambient Riemannian manifold, by isometricly embedding the ambient metric in Euclidean space, one should be able to get a related bound as long as the embedding (of the ambient space) has bounded mean curvature. See this answer to a related question for the reference.
[ "stackoverflow", "0045182005.txt" ]
Q: Get date difference for different rows of a id for multiple ids in R I want to get the difference of dates on 2 consecutive rows if the id is the same. A simple code for that would be: for(i in 2:nrow(Data)) { if(id[i]==id[i-1] { dated[i]-dated[i-1] } } But this being in a loop takes ages to execute. Is there any quicker way to run this kind of a code on over 2 million rows? A: We can do this with data.table. Convert the 'data.frame' to 'data.table' (setDT(df1)), grouped by 'id', get the difference (diff) of 'dated' column library(data.table) setDT(df1)[, .(datedifference = diff(dated)), id]
[ "stackoverflow", "0015318816.txt" ]
Q: Redis with Twemproxy vs memcached So referencing this question, the top post states that the biggest concern of Redis is its scalability in terms of robust clustering. I was wondering if using Redis with Twemproxy, an open-source proxy developed my Twitter for memcache and redis, would alleviate that problem to the point where my main cache can just be Redis. A: It depends what you mean by robust clustering. If you need a solution robust enough to support storage (and not caching), or if you consider you cannot afford to loose your cached data, then twemproxy (or any other proxy solution) is not enough. This is true for both Memcached or Redis. For this kind of clustering requirements, you will be better served by things like Couchbase, Infinispan, or even Riak, and Cassandra. Now if you need a caching solution with automatic sharding, consistent hashing, and proper management of server eviction (or black-listing), then twemproxy works fine with both Redis and Memcached. Performance of twemproxy is excellent.
[ "stackoverflow", "0050693695.txt" ]
Q: How to override apply and restore defaults I want to configure some appearance settings for a type of file. So I created a new entry in the General->Appearance->Colors and Fonts. My plugin.xml looks like this: <extension point="org.eclipse.ui.themes"> <themeElementCategory id="com.example.themeElementCategory" label="My specific settings"> <description> Control the appearance of .example files </description> </themeElementCategory> <colorDefinition categoryId="com.example.themeElementCategory" id="com.example.colorDefinition" label="Some Color" value="COLOR_DARK_BLUE"> <description> Your description goes here </description> </colorDefinition> <fontDefinition categoryId="com.example.themeElementCategory" id="com.example.fontDefinition" label="Some Font" value="Lucida Sans-italic-18"> <description> Description for this font </description> </fontDefinition> </extension> Now in the Colors and Fonts I have a new entry were I can set the color and the font. How can I extend the preferences window so I can override the Restore defaults, Apply and Apply and Close buttons? In my <themeElementCategory> I will have to add a class=MyHandlingClasswhich would override the performApply(), but what should that class extend/implement? Same as 1, but add a PropertyChangeEvent, still don't know what should extend/implement Less likely, create a new preference page which extends the PreferencePage and implements IWorkbenchPreferencePage How can I achieve one of the first two options? UPDATE FOR CLARIFICATION Currently the color and the font for a specific file extension are hardcoded in a class( I KNOW). When the file is opened in the editor, the informations are read from that static class and visible in the editor. What I wanted to do: In a static{} block, read the settings configured in the preferences and update the static fields from my class. If the user changes those settings from the preferences, on apply I wanted to update the static fields from the class and "repaint" the editor. A: If you just want to know when theme items change value use the addPropertyChangeListener method of IThemeManager to add a listener for changes: IThemeManager manager = PlatformUI.getWorkbench().getThemeManager(); manager.addPropertyChangeListener(listener); The PropertyChangeEvent passed to the propertyChanged method of IPropertyChangeListener contains the id, old and new value of the changed theme item.
[ "stackoverflow", "0062269920.txt" ]
Q: How to read ID Token using MSAL I successfully acquire an ID Token along with an Access Token from Azure AD using MSAL.js in my Angular application. The ID Token does contain information about the signed-in user. This would include roles and groups. However I do not understand how to read these values from the token stored in local storage. Does MSAL provide utilities to do so ? A: In the more recent versions of the code it looks like there is a getAccount() function. this.authService.getAccount()
[ "stackoverflow", "0025108919.txt" ]
Q: How to re-write Objective C Delegate Method in Swift I'm trying to re-write a cocoapod's Objective-C delegate protocol in Swift. The cocoapod is MZTimerLabel and I'm trying to notify my View Controller when the timer has finished. Xcode tries to layout the correct syntax for me but I cannot quite understand what is is asking for. For example, when I am reading the example method I can't discern when it says timerLabel whether that means to type 'timerLabel' or if `timerLabel' is a placeholder for my instance of the MZTimerLabel. It looks like the protocal is telling me to call on MZTimerLabel and then tell it what instance in my view controller to listen for (my instance is called brewingTimer, but I can't get the Swift Syntax right. Perhaps I should declare brewingTimer.delegate = self in my ViewDidLoad()? -(void)timerLabel:(MZTimerLabel*)timerLabel finshedCountDownTimerWithTime:(NSTimeInterval)countTime { //time is up, what should I do master? } My Swift attempt: MZTimerLabel(timerLabel(brewingTimer, finshedCountDownTimerWithTime: 5)){ //What I want to do when the timer finishes {self.startTimer.setTitle("Ok!", forState: .Normal) } I get the error "use of unresolved identifier 'timerLabel'" I'm learning programming more or less from scratch with Swift as my first language so I'm constantly having to learn to read code "backwards" in Objective C to translate it over to Swift. Also, I don't understand what "countTime" is. I've read through all of the Swift documentation and have looked through guides for method's in Objective C, but seeing an example of an actual Objective C method written in Swift would be very helpful. A: Your delegate function becomes in swift as func timerLabel(timerLabel: AnyObject!, finshedCountDownTimerWithTime countTime: NSTimeInterval){ self.startTimer.setTitle("Ok!", forState: .Normal) var yourTimerLabel = timerLabel as? MZTimerLabel //Downcast to MZTimerLabel //Now you can use yourTimerLabel as instance of MZTimerLabel } Implement this in your viewController where you want to get notified.Also conform to protocol. Here timerLabel is instance of MZTimerLabel Also import your protocol to Swift Bridging Header
[ "stackoverflow", "0008892271.txt" ]
Q: Initializing Wirble from .irbrc produces funny prompt >> When I initialize Wirble (0.1.3) directly in IRB with the following lines, it works well; I get colorized output, auto-complete etc. require 'rubygems' require 'wirble' Wirble.init Wirble.colorize When I put the same lines into .irbrc, I get a prompt that looks like this: >> A: OK, the answer is in the Wirble documentation. You initialize Wirble as follows: Wirble.init({ :skip_prompt => true })
[ "math.stackexchange", "0003389240.txt" ]
Q: Maximum size of minimal generating set for $S_n$ Consider all minimal generating sets for $S_n$. The smallest of them have size 2, that is, $S_n$ can be generated by two permutations. What are the largest ones? As I understand, there should exist minimal generating sets of size $n - 1$. E.g. the Coxeter generating set $(1\;2),\, (2\;3),\, \dots,\, (n - 1\;n)$ appears to be minimal: if we remove any single permutation $(i\;i + 1)$, then $S_i \times S_{n-i}$ will be generated. And also $(1\;2),\, (1\;3),\, \dots,\, (1\;n)$ appears to be minimal: without any single permutation, $S_{n-1}$ will be generated. Is it true that a minimal generating set for $S_n$ cannot have more than $n - 1$ elements? Is it somehow related to Jerrum's filter that is guaranteed to return a generating set of size $\le n - 1$? A: The maximal size of an irredundant generating set of $S_n$ is proved to be $n-1$ in the paper Julius Whiston, Maximal Independent Generating Sets of the Symmetric Group, Journal of Algebra 232, 255-268 (2000). You can find this online by searching for it.
[ "stackoverflow", "0054619080.txt" ]
Q: "didReceiveRegistrationToken" does not give me the fcmToken? I'm building an app with firebase, and trying to save the FCM token for push notifications (which is sent by firebase functions). The way I'm trying to do it is my storing the deviceToken in UserDefault, to use it later on. I need to save the fcmToken when the user signs up (to store it in my database under profile). When the user signs out, I need to delete the fcmToken in the database. Because of this I have my func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) in AppDelegate (maybe this is wrong?), and I store it like this: AppDelegate code: func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { UserDefaults.standard.setValue("fcmToken", forKey: fcmToken) } When I want to call it, for example in the Sign Up viewcontroller, I declare the device token like this: Sign Up ViewController code: let deviceToken = UserDefaults.standard.value(forKey:"fcmToken") as? String ?? "not found" And then i save it in my database like this ["fcmToken": deviceToken] However, this always returns "not found" in Firebase, and does not save the actual device ID. It would be great if you guys could help me out on this one. A: You have your "" backwards when saving to UserDefaults. the way you have it you're saving the string "fcmToken" under the fcmToken String func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print(fcmToken) UserDefaults.standard.set(fcmToken, forKey: "fcmToken") }
[ "superuser", "0001267925.txt" ]
Q: need clarifications on chroot command I am trying to understand chroot. I am trying to run just "ls" command in chroot environment. So i copied "ls" and "bash" and its dependencies(as shown by ldd) to corresponding bin, lib, lib64 directories in new root directory and ran chroot command. But I get following error. root@vig-debian:/home/vignesh# chroot /home/vignesh/my_chroot/ my_chroot/bin/bash chroot: failed to run command ‘my_chroot/bin/bash’: No such file or directory below are logs of what I tried. ========================================================= root@vig-debian:/home/vignesh/my_chroot# mkdir bin root@vig-debian:/home/vignesh/my_chroot# mkdir lib root@vig-debian:/home/vignesh/my_chroot# mkdir lib64 root@vig-debian:/home/vignesh/my_choot# cp /bin/ls bin/ root@vig-debian:/home/vignesh/my_choot# cp /bin/bash bin/ root@vig-debian:/home/vignesh/my_chroot# root@vig-debian:/home/vignesh/my_chroot# root@vig-debian:/home/vignesh/my_chroot# ldd bin/ls linux-vdso.so.1 (0x00007ffd463f2000) libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007fa1e4bf8000) libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007fa1e49ef000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fa1e4644000) libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007fa1e43d6000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fa1e41d2000) /lib64/ld-linux-x86-64.so.2 (0x00007fa1e4e1d000) libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007fa1e3fcd000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fa1e3db0000) root@vig-debian:/home/vignesh/my_chroot# ldd bin/bash root@vig-debian:/home/vignesh/my_chroot# root@vig-debian:/home/vignesh/my_chroot# linux-vdso.so.1 (0x00007fff276dd000) libncurses.so.5 => /lib/x86_64-linux-gnu/libncurses.so.5 (0x00007f5ecbaab000) libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007f5ecb881000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f5ecb67d000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f5ecb2d2000) /lib64/ld-linux-x86-64.so.2 (0x00007f5ecbcd0000) root@vig-debian:/home/vignesh/my_chroot# root@vig-debian:/home/vignesh/my_chroot# root@vig-debian:/home/vignesh/my_chroot# cp /lib/x86_64-linux-gnu/libselinux.so.1 /lib/x86_64-linux-gnu/libacl.so.1 /lib/x86_64-linux-gnu/libc.so.6 /lib/x86_64-linux-gnu/libpcre.so.3 /lib/x86_64-linux-gnu/libdl.so.2 /lib/x86_64-linux-gnu/libattr.so.1 /lib/x86_64-linux-gnu/libpthread.so.0 lib/ root@vig-debian:/home/vignesh/my_chroot# root@vig-debian:/home/vignesh/my_chroot# root@vig-debian:/home/vignesh/my_chroot# cp /lib64/ld-linux-x86-64.so.2 lib64/ root@vig-debian:/home/vignesh/my_chroot# cp /lib/x86_64-linux-gnu/libncurses.so.5 /lib/x86_64-linux-gnu/libtinfo.so.5 /lib/x86_64-linux-gnu/libdl.so.2 /lib/x86_64-linux-gnu/libc.so.6 lib/ root@vig-debian:/home/vignesh/my_chroot# root@vig-debian:/home/vignesh/my_chroot# root@vig-debian:/home/vignesh/my_chroot# ls bin lib lib64 root@vig-debian:/home/vignesh/my_chroot# cd ../ root@vig-debian:/home/vignesh# chroot /home/vignesh/my_chroot/ my_chroot/bin/bash chroot: failed to run command ‘my_chroot/bin/bash’: No such file or directory root@vig-debian:/home/vignesh# I then created debian image using "debootstap" and then could execute "chroot" without any error.. So, is whatever I tried wrong?? A: You should run chroot /home/vignesh/my_chroot/ /bin/bash. The first argument is where to chroot and the second the command. The path of the command is relative to where you chroot.
[ "stackoverflow", "0017857897.txt" ]
Q: Magento, access functions in Mage_Core_Helper_Abstract Im new to Magento Just installed this plugin http://shop.bubblecode.net/magento-attribute-image.html All is going well, so on my product view page I run the following code to get my attribute ids $ids = $_product->getData('headset_features'); Now the above plugin states it comes with this helper http://shop.bubblecode.net/attachment/download/link/id/11/ The function in this class I need to use is public function getAttributeOptionImage($optionId) { $images = $this->getAttributeOptionImages(); $image = array_key_exists($optionId, $images) ? $images[$optionId] : ''; if ($image && (strpos($image, 'http') !== 0)) { $image = Mage::getDesign()->getSkinUrl($image); } return $image; } I am really struggling to make use of this function. I noticed in the helper class Bubble_AttributeOptionPro_Helper_Data extends Mage_Core_Helper_Abstract So here is what I thought should work echo Mage::helper('core')->Bubble_AttributeOptionPro_Helper_Data->getAttributeOptionImage($ids[0]); But its not working for me, it kills the page, can someone please tell me how to access the function. Thanks in advance. UPDATE: Just tried $helper = Mage::helper('AttributeOptionPro'); which also kills the page A: Based on the helper classgroup for this module (bubble_aop, defined in the config), you can instantiate the helper class as follows: $helper = Mage::helper('bubble_aop'); However I do not see anything in the class definition which gets it to pull data from the product entity.
[ "stackoverflow", "0005402841.txt" ]
Q: jquery load if iframe doesn't exist Once i have clicked once on both items of the li(Google & Bing) i have created the iframes and i can do a search. Now how would i do when i click again on the li to check if the iframe is already there so i don't reload the search? Does that make sense? <HTML> <HEAD> <TITLE></TITLE> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js "></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js "></script> <style type="text/css"> iframe {width: 100%;height: 100%;max-width: 850px;min-height: 890px;overflow-x: hidden;overflow-y: auto;} </style> </HEAD> <body> <div id="search_engines" class="tabs"> <ul> <li><a href="#google" onclick="googleLoad();">Google</a></li> <li><a href="#bing" onclick="bingLoad();">Bing</a></li> </ul> <div id="google"> <a href="javascript: void(0)" onclick="googleLoad();" style="text-decoration: none" class="">New search</a> <script type="text/javascript"> function googleLoad() { $("#googleIframe").html('<iframe id="googleLoad" frameborder="0" src="http:www.google.com"></iframe>'); } </script> <div id="googleIframe"> <!--Iframe goes here --> </div> </div> <div id="bing"> <a href="javascript: void(0)" onclick="bingLoad();" style="text-decoration: none" class="">New search</a> <script type="text/javascript"> function bingLoad() { $("#bingIframe").html('<iframe id="bingLoad" frameborder="0" src="http:www.bing.com"></iframe>'); } </script> <div id="bingIframe"> <!--Iframe goes here --> </div> </div> </div> </body> </HTML> A: The cleanest and semantic way to go about it is to attach the click event via the jQuery .one() function (instead of an inline onclick= declaration). That way, your function executes after the click, and subsequent clicks won't trigger the load procedure again. <a id="myGoogleLink">Google</a> then bind that with $('#myGoogleLink').one('click', function(){ $('#googleIFrame').html("BLAH"); }); Now, if you were toggling between the Google and the Bing IFRAMEs, that's a whole different situation altogether.
[ "stackoverflow", "0010032236.txt" ]
Q: rand changes value without changing seed Take the following program: #include <cstdlib> using std::rand; #include <iostream> using std::cout; int main() { cout << rand() << ' ' << rand() << ' ' << rand() << '\n'; } Due to rand producing the same values as long as the seed isn't changed using srand, this should produce three identical numbers. e.g. 567 567 567 However, when I run this program it gives me three different values. e.g. 6334 18467 41 When the program is (compiled and) run again, the same three numbers are generated. Shouldn't I have to use srand to change the seed before I start getting different results from rand? Is this just my compiler/implementation trying to do me a favour? OS: Windows XP Compiler: GCC 4.6.2 Libraries: MinGW EDIT: By trying to use srand, I discovered that this is the result from a seed of 1 (which I guess is made default). A: Calling rand() multiple times intentionally produces a different random number each time you call it. Unless your program calls srand() with a different value for each run, the sequence will be the same for each run. You could use srand() with the time to make the entire sequence different each time. You can also call srand() with a known value to reset the sequence - useful for testing. See the documentation for rand() and srand(). A: Each call to rand() will always generate a different random number. The seed actually determines the sequence of random numbers that's created. Using a different seed will get you another 3 random numbers, but you will always get those 3 numbers for a given seed. If you want to have the same number multiple times just call rand() once and save it in a variable.
[ "stackoverflow", "0032163706.txt" ]
Q: Azure traffic manager performance balancing with nested profiles with different data centers How does the 'performance' option in azure traffic manager work with child profiles, when the child profiles contain data centers in different sub-regions? I understand the performance option sends traffic to the nearest data center which makes sense, but what about when it's choosing between nested-profiles, as those profiles could contain data centers anywhere. SO, if I create several nested profiles 'europe-zone', 'us-zone', 'asia-zone' each with a number of different data centers below it how will the traffic be routed exactly / exactly how will it select a zone. europe-zone 1.1 north-europe 1.2 west-europe us-zone 2.1 east-us 2.2 west-us 2.3 central-us asia-zone 3.1 japan 3.2 east-asia I have not find any detailed info on this scenario, the examples given, for example this one http://azure.microsoft.com/blog/2014/10/29/new-azure-traffic-manager-nested-profiles/ don't explain the behaviour. Remember I could have had profiles like profile 1 1.1 japan 1.2 west-us profile 2 2.1 japan 2.2 west-us so how would it select then? A: Thanks for the question. You're right that Traffic Manager can't easily infer the 'location' of a child profile since it may contain a mixture of endpoints. To resolve this, Traffic Manager requires you to specify the location of each child profile directly. To do this via PowerShell, use the '-location' parameter of Add-AzureTrafficManagerEndpoint when adding the child profile to the parent profile. The location must be specified in this way for any endpoints of type 'Any' (used for external services) or endpoints of type 'TrafficManager' (used for nested Traffic Manager profiles), when the 'Performance' traffic-routing method is used.
[ "stackoverflow", "0016817637.txt" ]
Q: How can you easily compare modified code against a reference implementation? I'm currently in the process of modifying somebody else's R-Tree implementation in order to add additional behaviour. I want to ensure that once I have made my changes the basic structure of the tree remains unchanged. My current approach is to create a copy of the reference code and move it into it's own package (tree_ref). I have then created a unit test which has instances of my modified tree and the original tree (in tree_ref). I am filling the trees with data and then checking that their field values are identical - in which case I assert the test case as having passed. It strikes me that this may not be the best approach and that there may be some recognised methodology that I am unaware of to solve this problem. I haven't been able to find one by searching. Any help is appreciated. Thanks. A: What you're doing makes sense, and is a good practice. Note that whenever you 'clone-and-own' an existing package, you're likely doing it for a reason. Maybe its performance. Maybe it is a behavior change. But whatever the reason, the tests you run against the reference and test subject need to be agnostic to the changes. Usually, this sort of testing works well with randomized testing -- of some sort of collection implementation, for example. Note also that if the reference implementation had solid unit tests, you don't need to cover those cases -- you simply need to target the tests at your implementation. (And for completeness, let me state this no-brainer) you still have to add your own tests to cover the new behavior you've introduced with your changes.
[ "stackoverflow", "0020340503.txt" ]
Q: iTextSharp does not render header/footer when using element generated by XmlWorkerHelper I am trying to add header/footer to a PDF whose content is otherwise generated by XMLWorkerHelper. Not sure if it's a placement issue but I can't see the header/footer. This is in an ASP.NET MVC app using iTextSharp and XmlWorker packages ver 5.4.4 from Nuget. Code to generate PDF is as follows: private byte[] ParseXmlToPdf(string html) { XhtmlToListHelper xhtmlHelper = new XhtmlToListHelper(); Document document = new Document(PageSize.A4, 30, 30, 90, 90); MemoryStream msOutput = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, msOutput); writer.PageEvent = new TextSharpPageEventHelper(); document.Open(); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/themes/mytheme.css"), true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var parser = new XMLParser(); parser.AddListener(worker); using (TextReader sr = new StringReader(html)) { parser.Parse(sr); } //string text = "Some Random Text"; //for (int k = 0; k < 8; ++k) //{ // text += " " + text; // Paragraph p = new Paragraph(text); // p.SpacingBefore = 8f; // document.Add(p); //} worker.Close(); document.Close(); return msOutput.ToArray(); } Now instead of using these three lines using (TextReader sr = new StringReader(html)) { parser.Parse(sr); } if I comment them out and uncomment the code to add a random Paragraph of text (commented in above sample), I see the header/footer along with the random text. What am I doing wrong? The EventHandler is as follows: public class TextSharpPageEventHelper : PdfPageEventHelper { public Image ImageHeader { get; set; } public override void OnEndPage(PdfWriter writer, Document document) { float cellHeight = document.TopMargin; Rectangle page = document.PageSize; PdfPTable head = new PdfPTable(2); head.TotalWidth = page.Width; PdfPCell c = new PdfPCell(ImageHeader, true); c.HorizontalAlignment = Element.ALIGN_RIGHT; c.FixedHeight = cellHeight; c.Border = PdfPCell.NO_BORDER; head.AddCell(c); c = new PdfPCell(new Phrase( DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT", new Font(Font.FontFamily.COURIER, 8) )); c.Border = PdfPCell.TOP_BORDER | PdfPCell.RIGHT_BORDER | PdfPCell.BOTTOM_BORDER | PdfPCell.LEFT_BORDER; c.VerticalAlignment = Element.ALIGN_BOTTOM; c.FixedHeight = cellHeight; head.AddCell(c); head.WriteSelectedRows( 0, -1, // first/last row; -1 flags all write all rows 0, // left offset // ** bottom** yPos of the table page.Height - cellHeight + head.TotalHeight, writer.DirectContent ); } } A: Feeling angry and stupid for having lost more than two hours of my life to Windows 8.1! Apparently the built in PDF Reader app isn't competent enough to show 'Headers'/'Footers'. Installed Foxit Reader and opened the output and it shows the Headers allright! I guess I should try with Adobe Reader too!!! UPDATES: I tried opening the generated PDF in Adobe Acrobat reader and finally saw some errors. This made me look at the HTML that I was sending to the XMLWorkerHelper more closely. The structure of the HTML had <div>s inside <table>s and that was tripping up the generated PDF. I cleaned up the HTML to ensure <table> inside <table> and thereafter the PDF came out clean in all readers. Long story short, the code above is fine, but if you are testing for PDF's correctness, have Adobe Acrobat Reader handy at a minimum. Other readers behave unpredictably as in either not reporting errors or incorrectly rendering the PDF.
[ "stackoverflow", "0060001151.txt" ]
Q: Select data from Datagridview using checkedlistbox I've got a datagridview in my form and also a checkedlistbox. I've written some code so that I can filter the datagridview with whatever is checked in the checkedlistbox. Although, it will only filter one at a time whereas I want to be able to filter any data which is checked. Is there a way around this? Code: if (checkedListBox1.CheckedItems.Count != 0) { string s = ""; int x; for (x = 0; x <= checkedListBox1.CheckedItems.Count - 1; x++) { s = "'" + checkedListBox1.CheckedItems[x].ToString() + "',"; } s = s.Substring(0, s.Length - 1); toolStripDropDownButton7.Text = s; con.Open(); string query = "select * from Leads where Status in (" + s + ")"; SqlCommand cmd = new SqlCommand(query, con); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); dataGridView4.DataSource = dt; con.Close(); } A: Looks like you have an error in your for loop: "s" contains only last checked item from checkListBox. Try to change it like this: s += "'" + checkedListBox1.CheckedItems[x].ToString() + "',";
[ "gis.stackexchange", "0000010078.txt" ]
Q: How stable is WPF in Arcmap? I'm tempted to propose porting some windows forms based arcmap tools to WPF. Before doing that though, I'd like to hear from others who have done something similar, and what sorts of issues were encountered. Compared to Windows Forms, how stable is WPF in Arcmap? A: I've had no issues with WPF in ArcGIS whatsoever. The question of chosing one of these technologies over the other is the same as in any other environment, be it ArcGIS or not. There are things to consider, though. If you want to use WPF as replacement for your forms, then you are definitely OK. If you'd like to use WPF in scenarios like e.g. docking windows, you need to be more careful since WPF/Win32 interoperablity can have subtle issues and performance impact. In my experience though, these arise rarely, and in very corner-case situations. Another thing to consider is whether your applications run in environments like Citrix or are very often accessed via remote desktop. In those cases, the WPF drawing pipeline can easily slow things down, especially (but not only) when you make use of advanced effects. A: The only problem your going to come across is if you use the map control and the toolbar controls. You will have to host the controls inside a winhost control. Which makes it impossible to overlay any WPF controls.
[ "meta.stackexchange", "0000181165.txt" ]
Q: Can flags send a post into the Low Quality Posts review queue? I'm trying to clear the last few TODOs in What are the guidelines for reviewing?, so it can eventually go into the FAQ. The section on the Low Quality Posts queue currently says: Questions appear in the low quality post queue both by algorithm and by flags from users. [TODO remove this todo if you know this information is correct :) ] I couldn't find any meta post stating that flags can take a post into that queue. New Feature: Community Review Tasks - Now in Beta says just that this task targets posts that we've algorithmically determined to be low quality. Should we remove the mention to flags, or does anyone know a post to back that information up? A: As of July 2013, Very Low Quality flags automatically add the flagged post to the Low Quality review queue. As of April 2014, Not An Answer flags do the same. Each review task requires a minimum number of "Looks OK" reviews (2 on SO, 1 everywhere else) to be dequeued; this number increases by one for each pending flag on the post (edits, closing and deletion dequeue the task in the normal fashion). Once reviewed, further flags do not re-add the post to the queue. At this point, a moderator will need to intervene. These flags will continue to appear in the moderator queue for this reason. These changes replace the previous handling of these flags by 10K users. Details can be found here.
[ "stackoverflow", "0040066221.txt" ]
Q: Array List Remove Index I have been working on this for ages now. I have an array list where many strings are in one index. (index 0) Brand is: Nissan Colour is: Black ID is: KL1 Door is: 4 (index 1) Brand is: Ford Colour is: Red ID is: LL0 Door is: 4 I want the user to input only ID and it should remove the whole data in the index. Unfortunately Iterator won't work here. Any ideas how this can be done? A: OOP Use the basic object-oriented approach. Create a class to represent each row of data, with four member fields: brand, color, id, door. Parse each row of text to instantiate an object of that class. Collect the objects in a List. Loop the list and interrogate each object for its id to match your desired id. For speed in adding/deleting items, use a LinkedList rather than an ArrayList as your implementation of List. A: You should create class that will contain those data related tor car. Take the following code as a example. I have used Java 8 feature that internally iterate over the list. public class Main { public static void main(String[] args){ List<Car> list = new ArrayList<>(Arrays.asList(new Car("Nissan", "Black", "KL1", "4"), new Car("Ford", "Red", "LL0", "4"))); String id = "KL1"; list.removeIf(i -> i.getID().equals(id)); list.forEach(System.out::println); // show the list after operation } static class Car { public final String Brand; public final String Colour; public final String ID; public final String Door; public Car(String brand, String colour, String ID, String door) { Brand = brand; Colour = colour; this.ID = ID; Door = door; } public String getBrand() { return Brand; } public String getColour() { return Colour; } public String getID() { return ID; } public String getDoor() { return Door; } } } Update You can also do that by doing this public static void main(String[] args){ List<Car> list = new ArrayList<>(Arrays.asList(new Car("Nissan", "Black", "KL1", "4"), new Car("Ford", "Red", "LL0", "4"))); String id = "KL1"; // Following code will find and remove the match from the list. // this for loop do exactly what it is doing "list.removeIf(i -> i.getID().equals(id));" for (int i = 0; i < list.size(); i++) { if (list.get(i).getID().equals(id)) { list.remove(i); break; } } }
[ "stackoverflow", "0005516914.txt" ]
Q: Invalid attempt to Read when reader is closed I'm working on C# and MySql request. I'm trying to retrieve my datas in my db but I have this error message : Invalid attempt to Read when reader is closed. Thanks for your help guys :) I have this function : public MySqlDataReader GetValueFromTable(string table, ArrayList attribut, ArrayList parameter) { string query = string.Empty; MySqlDataReader rdr = null; try { query = "SELECT * FROM `" + table + "` WHERE "; for (int i = 0; i < attribut.Count; i++) { query += attribut[i] as string; query += " = "; query += parameter[i] as string; if(i != attribut.Count - 1) query += " AND "; } query += ";"; using (mysqlConnection) { using (mysqlCommand = new MySqlCommand(query, mysqlConnection)) { rdr = mysqlCommand.ExecuteReader(); } } } catch (Exception ex) { Debug.Log(ex.ToString()); } finally {} return rdr; } And next somewhere in my code I doing this: ArrayList attribut = new ArrayList(); ArrayList parameter = new ArrayList(); attribut.Add("usern_id"); parameter.Add("1"); MySqlDataReader reader = dataBase.GetValueFromTable("papillon", attribut, parameter); reader.Read(); Debug.Log(reader[0]); reader.Close(); A: The using block closes the connection here (on exit) using (mysqlCommand = new MySqlCommand(query, mysqlConnection))
[ "stackoverflow", "0050545287.txt" ]
Q: Grouping elements in array by multiple properties I have array like this: var arr = [ {"type":"color","pid":"ITEM_1","id":"ITEM_1_1"}, {"type":"color","pid":"ITEM_2","id":"ITEM_2_2"}, {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"}, {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"} ] And I want to make a new array look like this: [ { "type": "color", "relation":[{"pid": "ITEM_1", "id": "ITEM_1_1"}, {"pid": "ITEM_2", "id": "ITEM_2_2"}] }, { "type": "size", "relation":[{"pid": "DEFAULT_0", "id": ["DEFAULT_0_1","DEFAULT_0_2"]}] } ] Thanks. ========================================= Thanks Abrar's answer. I adjust it slightly for grouping the same pid items and get the result I want. But there should be a better way to do this? const arr = [ {"type":"color","pid":"ITEM_1","id":"ITEM_1_1"}, {"type":"color","pid":"ITEM_2","id":"ITEM_2_2"}, {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"}, {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"} ]; const resultArr = []; const groups =[]; arr.forEach((data) => { let type = data.type; let newArr = arr.filter(el => el.type === type); let resObj = { "type": type, "relation": [] }; newArr.forEach(el => { groups.push({"pid": el.pid, "id": el.id}); }); var group_to_values = groups.reduce(function(obj, item) { obj[item.pid] = obj[item.pid] || []; obj[item.pid].push(item.id); return obj; }, {}); resObj.relation.push(group_to_values); if (resultArr.map(e => e.type).indexOf(type) < 0) { resultArr.push(resObj); } }) console.log(resultArr); A: I have refactored your code and now it looks like this - const arr = [ {"type":"color","pid":"ITEM_1","id":"ITEM_1_1"}, {"type":"color","pid":"ITEM_2","id":"ITEM_2_2"}, {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"}, {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"} ]; const resultArr = []; arr.forEach((data) => { let type = data.type; let newArr = arr.filter(el => el.type === type); let resObj = { "type": type, "relation": [] }; newArr.forEach(el => { resObj.relation.push({"pid": el.pid, "id": el.id}); }); if (resultArr.map(e => e.type).indexOf(type) < 0) { resultArr.push(resObj); } }) console.log(resultArr); //resultArr contains your desired output Basically I have filtered out the keys from the array based on the type since that has to be unique (as per your desired output). This should be pretty straightforward and won't require frameworks or even jQuery.
[ "stackoverflow", "0025310066.txt" ]
Q: Getting the last created (modified) file I have a program that created files and fill them with data , it doesn't matter what exactly , it named them based of the actual time (YYYYMMDDHHMMSS). Now I want to always open the last created file , meaning the recent one, is this possible in C ? if yeah, I'll be greatful for any hint ? UPDATE I need to make it clear. say I have a string that I want to use like : .............. FILE* input = NULL; char* fileName = NULL; ...............// in some getting the name of the last modified file and than open it inp = fopen(fileName,"rb"); A: The ftw() function may be useful here. It will call a function (which you need to write) for every file and directory in the directory. Your function will decide if its argument is newer than whatever arguments it's seen before, and if so, records it in a global variable. One caveat is that ftw will look at every file in every subdirectory. That may not be what you want. But if that's OK, using ftw will make your code more concise, because it does the directory scanning and statting for you. Here's an example I wrote that will find the most recently modified file in the current directory: #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <limits.h> #include <string.h> #include <ftw.h> char newest[PATH_MAX]; time_t mtime = 0; int checkifnewer(const char *path, const struct stat *sb, int typeflag) { if (typeflag == FTW_F && sb->st_mtime > mtime) { mtime = sb->st_mtime; strncpy(newest, path, PATH_MAX); } return 0; } main() { ftw(".", checkifnewer, 1); printf("%s\n", newest); }
[ "stackoverflow", "0025144884.txt" ]
Q: iOS Update TableViewCell Contents and REload On didSelectRowAtIndexPath I want to update the tableviewcell and reload it. I am able to reload but not the content is not getting updated. This is the code that I call from didSelectRowAtIndexPath method. self.visitorlistsTv is my tableview -(void) showDetails:(NSIndexPath *)indexPath { if (! [expandedArray containsObject:indexPath]) { [expandedArray addObject:indexPath]; // UPDATE THE IMAGE OF THE BUTTON VisitorsListsCell *vcell = (VisitorsListsCell *) [self.visitorlistsTv cellForRowAtIndexPath:indexPath]; vcell.button.imageView.image = [UIImage imageNamed:@"arrowdown.png"]; // RELOAD [self.visitorlistsTv beginUpdates]; [self.visitorlistsTv reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath ] withRowAnimation:UITableViewRowAnimationAutomatic]; [self.visitorlistsTv endUpdates]; } else { [expandedArray removeObject:indexPath]; // UPDATE THE BUTTOM IMAGE VisitorsListsCell *vcell = (VisitorsListsCell *) [self.visitorlistsTv cellForRowAtIndexPath:indexPath]; vcell.button.imageView.image = [UIImage imageNamed:@"arrowup.png"]; // RELOAD THE DATA [self.visitorlistsTv beginUpdates]; [self.visitorlistsTv reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath ] withRowAnimation:UITableViewRowAnimationAutomatic]; [self.visitorlistsTv endUpdates]; } } A: The simple answer is that your technique for changing a UIButton's image is flawed. Instead use: [vcell.button setImage:[UIImage imageNamed:@"arrowdown.png"] forState:UIControlStateNormal]; But beyond that, the way to go about this is to update your model upon selection, call reload for that row and let your cellForRowAt... datasource do the work. That way, that row will look right even after the cell gets disposed of and reused. In other words, where you do this: vcell.button.imageView.image = [UIImage imageNamed:@"arrowdown.png"]; ... instead, add some state to your model (a string name of the image, or a BOOL that means up vs. down) and set that instead: MyModelObject *modelObject = self.model[indexPath.row]; modelObject.arrowImageName = @"arrowdown.png"; // or the up arrow, depending on the condition // now do your reload code Your cellForRowAt... can now lookup the model and update the dequeued cell with: MyModelObject *modelObject = self.model[indexPath.row]; UIImage *image = [UIImage imageNamed:modelObject.arrowImageName]; [cell.button setImage:image forState:UIControlStateNormal]; One note: your reload code is the same on both branches, so it can be factored out after the conditional.
[ "physics.stackexchange", "0000426322.txt" ]
Q: why is friction acting towards the centre in a level curved road? We all know that friction is a force that opposes motion and is applied in the opposite direction of motion, but in a leveled curved road it becomes the centripetal force and pulls towards the center. Why? A: According to the Newton's first law, in the absence of an external force, a car would move along a straight line. When the front wheels of the car are turned to follow a curved road, the car is blocked from moving straight by the friction, serving as that external force. So, we can say that, if it was not for the friction force, opposing the natural straight movement of the car, the car would not be able to turn or stay on a curved road. The direction of the friction force is normal to the wheels and their trajectory. So, we can say that the friction force acts along the radius of the trajectory curve, pointing to its center, which makes it a centripetal force.
[ "stackoverflow", "0016592215.txt" ]
Q: Connect to remote MongoDB replica set, when replica set connect to each other on local IP addresses We have setup a mongo replica set on a local network interface (i.e. 192.168.1.x). The replica set members are the only ones that know about this interface. The instances are also on an external interface that is addressable from inside our network (10.x.x.x). When trying to connect to the 'master' only with the Java driver[2.10.1] (via gMongo wrapper) we're running into a problem where a connection will not be made because the app cannot determine the other replica nodes. This happens even if I provide all the external interfaces in the sever list. I also need to be able to setup an SSH tunnel from my machine to the replica set. Again, I run into the same issue because the replica set provides hostnames and IP addresses that are not applicable to me. How can I connect to a replica set when the replica knows about each other only over local IP addresses? Here is an example of the code and the errors that result. The example below assume a tunnel has been setup from localhost to the remote server. @Grab(group='com.gmongo', module='gmongo', version='1.1') import com.gmongo.* import com.mongodb.* def hosts= [ [host:'127.0.0.1', port:29017], //[host:'127.0.0.1', port:29018], //have tried with and without the others commented //[host:'127.0.0.1', port:29019], ] List<ServerAddress> addrs = hosts.collect {it.port?new ServerAddress(it.host, it.port):new ServerAddress(it.host)} MongoClientOptions clientOptions = new MongoClientOptions.Builder().build() def mongo = new GMongoClient(addrs, clientOptions) def db = mongo.getDB("mydb") def result = db.tickets.findOne([:]) println result results in this: WARNING: couldn't resolve host [mongo03:27017] May 16, 2013 10:54:59 AM com.mongodb.ReplicaSetStatus$UpdatableReplicaSetNode _addIfNotHere WARNING: couldn't resolve host [mongo03:27017] May 16, 2013 10:55:01 AM com.mongodb.ReplicaSetStatus$UpdatableReplicaSetNode findNode WARNING: couldn't resolve host [mongo02:27017] May 16, 2013 10:55:01 AM com.mongodb.ReplicaSetStatus$UpdatableReplicaSetNode _addIfNotHere WARNING: couldn't resolve host [mongo02:27017] May 16, 2013 10:55:01 AM com.mongodb.ReplicaSetStatus$UpdatableReplicaSetNode findNode com.mongodb.MongoException: can't find a master at com.mongodb.DBTCPConnector.checkMaster(DBTCPConnector.java:518) WARNING: Server seen down: /192.168.1.11:27017 - java.io.IOException - message: couldn't connect to [/192.168.1.11:27017] bc:java.net.SocketTimeoutException: connect timed out I'm not sure why it's trying to resolve based on the servers' local config rather than the list of servers I provide. A: In my experience, replica sets work best when they have DNS names that both the clients and the servers can resolve. I have used both pymongo and php MongoClient, and if the client machine uses the IP Addresses of the replica set, but the replica set was setup using DNS names, the client will fail to connect (probably because when asking the replica set which node is the primary, the replica set probably returns the DNS name). If I use DNS names (I just modify the hosts file on the client) then the connections do not fail. From the documentation on replica sets: Each member of the replica set must be accessible by way of resolvable DNS or hostnames Hope this helps you debug your issue.
[ "stackoverflow", "0057932283.txt" ]
Q: UIFileSharingEnabled key in Info.plist I added the key UIFileSharingEnabled to my app's version info as described here so my users can save files to my apps documents folder. Works great in testing. Tried to upload to apple store with Application Loader and i'm getting an ERROR ITMS-90039: "Type Mismatch. The value for the Info.plist key UIFileSharingEnabled is not of the required type for that key.. I've googled and found where other folks had problems with it but none of their solutions helped. Here are the ways i've tried to show this key in the Info.plist: <key>UIFileSharingEnabled</key> <string>true</string> <key>UIFileSharingEnabled</key> <true/> <key>UIFileSharingEnabled</key> <string>YES</string> <key>UIFileSharingEnabled</key> <YES/> All have the same result, Application Loader barfs out the ERROR ITMS-90039. This key is a boolean key and for other boolean keys in Info.plist they just look like that top one i show. Anyone have a sample Info.plist with this key true that we can compare too? I've built my app in Rad Studio 10.3.2 (C++ Builder). They key works with test builds on the phone. A: Got it working and here is the deal: The Info.plist file in the iOSDevice64\Release folder is just for your info, it is not what gets uploaded to apple in the Application Loader. The Info.plist that gets uploaded is inside the .ipa file that is created when you build a Release version in Rad Studio and it gets signed so you obviously can't modify it. The solution was to edit the info.plist.TemplateiOS.xml that is in my app's project folder. The keys you put in Project->Options-Application->Version Info get added to this info.plist.TemplateiOS.xml when you build. So, I edited this template file and put the correct key representation in between <%ExtraInfoPListKeys%> and the last </dict>: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <%VersionInfoPListKeys%> <%ExtraInfoPListKeys%> <key>UIFileSharingEnabled</key> <true/> </dict> </plist> If you just put the UIFileSharingEnabled key in the Project->Options-Application->Version Info it will end up in the Info.plist like below which is wrong and Application Loader will give that error: <key>UIFileSharingEnabled</key> <string>true</string> The key must be like below to work on Release that you submit to app store: <key>UIFileSharingEnabled</key> <true/>
[ "softwareengineering.stackexchange", "0000277291.txt" ]
Q: Abstract classes and constants I have two classes that share a lot of code and are conceptually variations on a common class. So I want an abstract class that contains all their common code and then they can each inherit from it and fill in the stuff unique to them. However I am running into a problem with constants and static methods. Basically, the relationship I have is like this: Class A and Class B both have some methods that don't depend on an instance of the class, just the value of a set of constant strings. Basically as such: const string onePrefix; const string differentPrefix; static string ConvertMethod(string input) { input.replace(onePrefix, differentPrefix); } The method code is the same between the two classes, so I would like to have it in the abstract class. But the actual values of the two constants are different between the two classes. But abstract constants are not a thing you can do as far as I can tell so I'm not sure how to go about structuring my classes to make this work like I want it to. I've considered just not having the values be constants, but they are used in my constructors before an instanced object is created. A: It's a bit of a code smell to me that you have a constant that you want to share polymorphically between two classes so that they can define it on their own. Constants by design have been made to be unaffected by polymorphism so I would suggest you turn that into an abstract property in your abstract base class. You could either do that or have a concrete class as your supertype. Then inherit all the common functionality from your concrete class while having your constants defined on each subclass which you can access when you new them up.
[ "stackoverflow", "0010504849.txt" ]
Q: Tier Price not displaying Magento I'm new to magento. I have one product having tier prices as follows: a) 500 and above -> $46 b) 1000 and above -> $43 c) 1500 and above -> $39 And the Price(Actual) of product is $46. So on product detail page, It's not showing the first tier price (a). See below: Buy 1000 for $43 each and save 7% Buy 2500 for $39 each and save 16% Though the Actual price and minimum tier price are same, how can I display the minimum tier price in the above list. Please help. Thanks in advance. A: Make sure your base product price is bigger then $46... If your base product price is lower then the tier price, the tier price wont show up.
[ "stackoverflow", "0044847574.txt" ]
Q: Create empty array with a length from a variable I want to read a custom amount of bytes from a TcpStream, but I cannot initialize a new empty array buffer where I can define the length with a variable. It is not possible to use a vector because the TcpStream read function requires an array. let mut buffer = [0; 1024]; // The 1024 should be a variable When I replace the 1024 with a variable: let length = 2000; let mut buffer = [0; length]; I get the message: error[E0435]: attempt to use a non-constant value in a constant --> src/network/mod.rs:26:30 | 26 | let mut buffer = [0; bytes]; | ^^^^^ non-constant used with constant Why can't I do that? A: Use a Vec with with_capacity(): use std::net::TcpStream; fn main() { use std::io::Read; let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap(); let mut v = Vec::with_capacity(128); let _ = stream.read(&mut v); } You confound array and slice. There are different in Rust: a slice is a view on the memory, previously set with an array, a Vec or whatever.
[ "stackoverflow", "0063510146.txt" ]
Q: Replace space with hyphen in links I need like this https://play.google.com/store/apps/details?id=com.abc.abcc%26reffer=M1%26name=ABC-DEF-GHI but now it's Coming https://play.google.com/store/apps/details?id=com.abc.abcc%26reffer=M1%26name=ABC DEF GHI My Code As Follows https://play.google.com/store/apps/details?id=com.abc.abcc%26reffer=M{{$data['shopID']}}%26name={{$datastr_replace['-','name']}} A: Given the following array: $data = [ 'shop_id' => 'M', 'name' => 'ABC DEF GHI' ]; You can use the str_replace() method to replace all of your ' ' with -: <a href="https://play.google.com/store/apps/details?id=com.abc.abcc%26reffer=M{{ $data['shopID'] }}%26name={{ str_replace(' ', '-', $data['name']) }}">Link</a>
[ "es.stackoverflow", "0000251633.txt" ]
Q: Ejecutar PyQt dentro de C++ Quiero ejecutar PyQT dentro de un programa en C++ que estoy haciendo. Hasta ahora todas las pruebas están siendo infructuosas. Pasos que doy. Primero pruebo fuera de C++ 1.- Creo una interfaz con Qt Designer. En este caso un sencillo widget con un QPushButton 2.- Con la herramiento pyuic5 creo el modulo de pyhon referente a ese widget. Sale algo como: ui_widget.py # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'widget.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(400, 300) self.pushButton = QtWidgets.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(140, 130, 85, 27)) self.pushButton.setObjectName("pushButton") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.pushButton.setText(_translate("Form", "PushButton")) Ahora creo otro módulo que hace uso de este: main.py #!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt5 import QtCore, QtGui, QtWidgets from ui_widget import Ui_Form class MiWidget(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) def iniciar(): print ("iniciar ventanas") app = QtWidgets.QApplication(sys.argv) myapp = MiWidget() myapp.show() sys.exit(app.exec_()) Y por último lo llamo desde la consola: usuario@sobremesa ~/programacion/python/PyQt $ python3 Python 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from main import iniciar >>> iniciar() iniciar ventanas Y todo sale correctamente. Ahora toca hacer la llamada desde C++: #include "/usr/include/python3.5m/Python.h" #include <iostream> using namespace std; int main() { PyObject* fExportar = nullptr; PyObject* modulo = nullptr; PyObject* pName = nullptr; const char *scriptDirectoryName = "/home/usuario/programacion/python/PyQt/"; Py_Initialize(); PyObject *sysPath = PySys_GetObject("path"); PyObject *path = PyUnicode_FromString(scriptDirectoryName); int result = PyList_Insert(sysPath, 0, path); if (result == 0 ) { pName = PyUnicode_FromString("main"); modulo = PyImport_Import(pName); std::cout<<"modulo "<<modulo<<std::endl; PyObject *args = PyTuple_New(0); Py_DECREF(path); if (modulo) { fExportar = PyObject_GetAttrString(modulo, "iniciar"); Py_DECREF(modulo); if (fExportar) { std::cout<<"Funcion exportar: "<<" -- "<<fExportar<<std::endl; PyObject_CallObject(fExportar,args); } } } Py_Finalize(); return 0; } Pero hace la llamada a la función correctamente, o al menos imprime "iniciar ventanas", pero no sale ninguna ventana. Bueno, creo que tal vez arranque la ventana pero no se mantiene en el loop por lo que se abre y se cierra de forma que no se vea nada. Eso es mi suposición. En todo caso, ¿Cómo habré de llamar a la función para que se muestre la ventana correctamente y, si es el caso, se quede ejecutando el script de python hasta que se cierre la misma y vuelva el control al programa principal? (puede ser que esté diciendo cosas sin sentido) A: pues parece que he resuelto el problema. Lo primero, es crear un entorno seguro para cargar los módulos, evitando en la medida de los posible los errores de segmentación y así de paso poder ver qué es lo que realmente falla. No hay que inventar nada, sino adaptar el código propuesto en la página oficial a las necesidades. En mi caso lo pongo como una función. Aquí completo: #include "/usr/include/python3.5m/Python.h" int EjecutaFuncionPython(const char* ruta, const char* nombremodulo, const char* nombrefuncion); int main(int argc, char** argv) { putenv((char*)"PYTHONPATH=/home/user/programacion/python/PyQt/"); Py_Initialize(); EjecutaFuncionPython("/home/user/programacion/python/PyQt/","main","iniciar"); Py_Finalize(); return 0; } int EjecutaFuncionPython(const char* ruta, const char* nombremodulo, const char* nombrefuncion) { PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; pName = PyUnicode_DecodeFSDefault(nombremodulo); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, nombrefuncion); /* pFunc is a new reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(1); pValue = PyUnicode_FromString(ruta); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); fprintf(stderr, "Cannot convert argument\n"); return 1; } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, 0, pValue); pValue = PyObject_CallObject(pFunc, NULL); Py_DECREF(pArgs); if (pValue != NULL) { printf("Result of call: %ld\n", PyLong_AsLong(pValue)); Py_DECREF(pValue); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", nombrefuncion); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load \"%s\"\n", nombremodulo); return 1; } } Ahora puedo ver que el error que me arroja es el siguiente: Traceback (most recent call last): File "/home/user/programacion/python/PyQt/main.py", line 19, in iniciar app = QtWidgets.QApplication(sys.argv) AttributeError: module 'sys' has no attribute 'argv' Call failed Y por último, viendo problemas similares, esta solución me funciona Eso quiere decir que a mi script en python le añado esto: if not hasattr(sys, 'argv'): #nuevas lineas sys.argv = [''] #nuevas lineas Y me queda así: #!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt5 import QtCore, QtGui, QtWidgets from ui_widget import Ui_Form class MiWidget(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) def iniciar(): print ("iniciar ventanas python3") if not hasattr(sys, 'argv'): #nuevas lineas sys.argv = [''] #nuevas lineas app = QtWidgets.QApplication(sys.argv) #aqui el error myapp = MiWidget() myapp.show() sys.exit(app.exec_()) Y ya funciona. Por añadir algo más, y siguiendo la documentación oficial, a la hora de compilar es bueno averiguar las opciones adecuadas. Para ello está la utilidad pythonx.y-config (donde x.y es la versión de python) seguido de --cflags y --ldflags En mi caso python3.5-config --cflags --ldflags Con este resultado (cada uno tendrá el suyo): -I/usr/include/python3.5m -I/usr/include/python3.5m -Wno-unused-result -Wsign-compare -g -fstack-protector-strong -Wformat -Werror=format-security -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -L/usr/lib -lpython3.5m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions
[ "superuser", "0000957571.txt" ]
Q: Segoe UI Hebrew/Arabic characters I can enter Hebrew characters in the Google search field and they are displayed correctly. For some reasons, I sometimes switch to Bing search, and now I see that I can enter Hebrew characters, but they are displayed as boxes only. If I remove 'Segoe UI' from font-family css entry, it is displayed correctly, so Segoe UI is missing Hebrew characters on my (German) Windows 10. I can't remember whether this was the case on Windows 7, but I think it wasn't, possibly because Segoe UI wasn't installed on the system. Korean works, Chinese seems to work (I didn't try all symbols), Japanese seems to work as well. In Arabic there are some characters missing as well (while others are displayed correctly). Can I get an extended Segoe UI with the missing characters somewhere? How else could I solve the problem? A: Are you using Chrome? This is a known issue in Chrome on Windows 10; it appears that Segoe UI no longer covers all the scripts that it used to, and Chrome hasn't yet added all the required fallback fonts. As a temporary workaround, find Disable DirectWrite (chrome://flags/#disable-direct-write) in Chrome's flags page and enable the flag (you'll be enabling a negative flag, and hence disabling DirectWrite—confusingly enough.)
[ "stackoverflow", "0015361653.txt" ]
Q: Why are these two JS functions different? When lsEstimator is an array with 2 elements, this function returns true: function got_estimators() { var retval = (typeof lsEstimator != 'undefined' && lsEstimator != null && lsEstimator.length > 0); return retval; } but this function doesn't (it returns undefined, I think, in Chrome and FF): function got_estimators() { return (typeof lsEstimator != 'undefined' && lsEstimator != null && lsEstimator.length > 0); } Why? A: Because of the line break after return in the second example. The code is evaluated as: function got_estimators() { return; // <-- bare return statement always results in `undefined`. (typeof lsEstimator != 'undefined' && lsEstimator != null && lsEstimator.length > 0); } JavaScript is not even evaluating the logical operators. Why does this happen? Because JavaScript has automatic semicolon insertion, i.e. it tries to insert semicolons "where it makes sense" (more information here). Put the return keyword and the return value in the same line: return (typeof lsEstimator != 'undefined' && lsEstimator != null && lsEstimator.length > 0);
[ "stackoverflow", "0060633792.txt" ]
Q: Argument of type 'NgElementConstructor' is not assignable to parameter of type 'CustomElementConstructor' I'm getting a strange warning in VSCode( 1.44.0-insider ) with Angular9 in creating Angular Elements: export class AppModule { constructor(private injector: Injector) { const helloElement = createCustomElement(HelloComponent, {injector}); customElements.define('my-hello', helloElement); } ngDoBootstrap() {} } type of helloElement is not accepted with an error message from typescript: Argument of type 'NgElementConstructor' is not assignable to parameter of type 'CustomElementConstructor' A: It seems it will be fixed with the next release: https://github.com/angular/angular/pull/35864 You can already test it for your project by updating to the next release (9.1.0-next.4). ng update @angular/core --next
[ "superuser", "0000867965.txt" ]
Q: How to increment string like AA to AB? I have strings in Excel like AA or XA. I need to increment them like this: For AA in cell A1, it will be AB in cell B1, AC in cell B2 and so on. For XA in cell A1, it will be XB in cell B1, XC in cell B2 and so on. I tried the popular code =CHAR(CODE(A1)+1) but it does not work after Z. Any hints are welcome. A: Try this: put "AA" into cell A1 and enter the following formula into cell B1 and drag across =IF(RIGHT($A1,1)="Z", CHAR(CODE(LEFT(A1,1))+1),LEFT(A1,1))&CHAR(65+MOD(CODE(RIGHT(A1,1))+1-65,26)) It will increment as follows: AA, AB, AC,..., AZ, BA, BB, BC.... etc You might want to adapt this formula to suit your particular presentation. Please note that this won't work past "ZZ". Update: fixed bug A: We can use the excel spreadsheet itself to help increment the letters - the increment will work from A to XFC First create the cell reference: INDIRECT(A1&"1") Then find the address of the next column over: ADDRESS(1,COLUMN(INDIRECT(A10&"1"))+1) Then from the $??$1 we extract the letters: 2 ways: Look for the second $, and snip the text out between them =MID(ADDRESS(1,COLUMN(INDIRECT(A1&"1"))+1),2,FIND("$",ADDRESS(1,COLUMN(INDIRECT(A1&"1"))+1),2)-2) Replace the 1 and $ with nothing in the string =SUBSTITUTE(SUBSTITUTE(ADDRESS(1,COLUMN(INDIRECT(A1&"1"))+1),"$",""),"1","") Choose which one works best for you
[ "stackoverflow", "0002045791.txt" ]
Q: PHP empty() on __get accessor Using PHP 5.3 I'm experiencing weird / non-intuitive behavior when applying empty() to dynamic object properties fetched via the __get() overload function. Consider the following code snippet: <?php class Test { protected $_data= array( 'id'=> 23, 'name'=> 'my string' ); function __get($k) { return $this->_data[$k]; } } $test= new Test(); var_dump("Accessing directly:"); var_dump($test->name); var_dump($test->id); var_dump(empty($test->name)); var_dump(empty($test->id)); var_dump("Accessing after variable assignment:"); $name= $test->name; $id= $test->id; var_dump($name); var_dump($id); var_dump(empty($name)); var_dump(empty($id)); ?> The output of this function is as follow. Compare the results of the empty() checks on the first and second result sets: Set #1, unexpected result: string(19) "Accessing directly:" string(9) "my string" int(23) bool(true) bool(true) Expecting Set #1 to return the same as Set #2: string(36) "Accessing after variable assignment:" string(9) "my string" int(23) bool(false) bool(false) This is really baffling and non-intuitive. The object properties output non-empty strings but empty() considers them to be empty strings. What's going on here? A: Based on a reading of the empty's manual page and comments (Ctrl-F for isset and/or double underscores), it looks like this is known behavior, and if you want your __set and __get methods and empty to play nice together, there's an implicit assumption that you implement a __isset magic method as well. It is a little bit unintuitive and confusing, but that tends to happen with most meta-programming, particularly in a system like PHP. A: In this example, empty() calls the __isset() overload function, not the __get() overload function. Try this: class Test { protected $_data= array( 'id'=> 23, 'name'=> 'my string' ); function __get($k) { return $this->_data[$k]; } function __isset($k) { return isset($this->_data[$k]); } }
[ "stackoverflow", "0051921794.txt" ]
Q: How to update models.py when I create a new table in my database? I was wondering how to automatically update my models.py in a specific app in django. I created a new table in my database through HeidySQL, when i syncdb, i see the table appears in the directory in the command line, but not in models.py . I also tried migrate and make migrations but still not working. Any idea? Thanks! A: The manage.py migrate and makemigrations commands work in the opposite direction that you are describing here. If you want to generate a starter template of your models based on the current layout of the database, you can try using the inspectdb command. python manage.py inspectdb > temp_models.py This will generate a starter model for every table in the database. You should review and update the generated models so they make sense with your app. Take special note of lines ending with the comment # This field type is a guess. Once you are satisfied with the new models, copy them over to the app's models.py file. Hope that helps!
[ "stackoverflow", "0063590554.txt" ]
Q: Display two pictures in carousel at a time How can I make something like this, up on the picture with flutter? I searched through flutter carousel_slider 2.2.1 library, but it doesn't have features that display two pictures at a time. Widget _buildReport() { return CarouselSlider( options: CarouselOptions( height: 150.0, autoPlay: true, autoPlayInterval: Duration(seconds: 4), autoPlayAnimationDuration: Duration(milliseconds: 800), autoPlayCurve: Curves.fastOutSlowIn, ), items: [1, 2, 3, 4, 5].map((i) { return Builder( builder: (BuildContext context) { return Container( width: MediaQuery.of(context).size.width, margin: EdgeInsets.symmetric(horizontal: 5.0), child: Image( image: AssetImage('assets/dog.jpg'), fit: BoxFit.cover, )); }, ); }).toList(), ); } A: You can do it with carousel use Row widget with MainAxisAlignment.spaceBetween and wrap each image with Expanded like this : Container( width: MediaQuery.of(context).size.width, margin: EdgeInsets.symmetric(horizontal: 5.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: Image.asset( "assets/", fit: BoxFit.cover, ), ), Expanded( child: Image.asset( "assets/", fit: BoxFit.cover, ), ), ], ), ) Running apps :
[ "stackoverflow", "0010149506.txt" ]
Q: Replace character between strings Maybe it's just too late for me to do this, but I'm trying to replace a character between 2 string with regex in PHP. Example string: other | text [tag]text|more text|and more[/tag] end | text My goal is to replace | with <br/> between [tag] and [/tag]. Tried with this, seems it wasn't that easy though: /<td>(\|)<td>/gsi Searched a bit, but couldn't make out an answer with the stuff I found. Hope you can help, thanks A: First, find what's inside [tag]s, then find the pipes. PHP 5.3: $result = preg_replace_callback('/\[tag\](.+?)\[\/tag\]/i', function($match) { return str_replace('|', '<br />', $match[1]); }, $str);
[ "stackoverflow", "0051366103.txt" ]
Q: Issure receiving HTTP POST request in JSON and saving it to MySQL using REST API I'm pretty new to javascript but I have a REST API I'm running on a LAN network. I have a MySQL database I'm trying to save a HTTP POST body to in JSON format. My js code will print the data as "result" for me but will not save it when it is sent from Postman, however if I hard code a fake entry into it as "var result = {JSON format entries}" it will then be able to be saved to MySQL. Here is my code: var http = require('http'); var express = require('express'); var bodyParser = require('body-parser'); const { parse } = require('querystring'); var mysql = require("mysql"); var app = express(); var port = process.env.port || 8080; var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : '*******', database : 'userInfo' }); connection.connect(function(err) { if (err) throw err console.log('You are now connected with mysql database...') }) app.post('/licence', function (req, res) { collectRequestData(req, result => { console.log(result); connection.query('INSERT INTO licence SET ?',result, function (error, results, fields) { if (error) throw error; res.end(JSON.stringify(results)); }); res.end(`Parsed data belonging to ${result.fname}`); }); }); function collectRequestData(request, callback) { const FORM_URLENCODED = 'application/json'; if(request.headers['content-type'] === FORM_URLENCODED) { let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { callback(parse(body)); }); } else { callback(null); } } I'm pretty sure I don't need this line "res.end(Parsed data belonging to ${result.fname});" but what I am trying to figure out here is how to save result to the licence table in mysql. This is what console.log(result) prints: { '{"hash":"TestHaaaash", "size":13, "difficulty":47, "time":null, "timestamp":null, "date":null}': '' } I think this should be slightly different but I'm not sure how it should be or how to change it A: In collectRequestData try chaging request.on('end', () => { callback(parse(body)); }); to request.on('end', () => { callback(JSON.parse(body)); });
[ "stackoverflow", "0036944349.txt" ]
Q: How to make FileUtils appends instead of overwriting text file I am using the following to write StringBuilder into an existing text file. FileUtils.writeStringToFile(file, sb.toString(), StandardCharsets.UTF_8); The problem is that it overwrites the file where I just want to append sb.toString() to the existing content of file. How to workaround this issue? A: It has been implemented in 2.1 version of Apache IO. To append string to the file just pass true as an additional parameter in functions: example: FileUtils.writeStringToFile(file, stringBuilder.toString(), true);
[ "academia.stackexchange", "0000149056.txt" ]
Q: Should I reply to email from institute director congratulating me for being shortlisted for a position? I have received an email from the "director" of a prestigious research institute, sent to me and another candidate, announcing and congratulating that we have been shortlisted for a particular position. He then mentioned that his assistant will contact us to inform us about the interview procedure and the next steps. I wonder if I have to reply to the email, given it is sent by the director with his e-mail and not his assistance, or administration email, or I have to consider it as a kind of public announcement and just wait for his office to contact me? A: A short thank you email would be appropriate. "Thank you for the continued interest. I look forward to the interview and the future". Something along those lines, but you can probably come up with a better statement. It lets them know that you got the message, and, more important, that you are still very interested.
[ "ux.stackexchange", "0000004318.txt" ]
Q: Should Dialogs be avoided in modern applications? I have used a few dialogs on the last system I designed. The application was a business application with many database tables and I used many datagrids to show data. It was common that I placed a button below the datagrid with the text Create new item or Create new group or whatever was listed in the grid. In other words the button was used to create a new row in the table. When the user clicked the button a new (modal) dialog was created with the textfields and at the bottom a submit-button. But is this really the recommended way to do it? or how should I design the application without modal dialogs? If this had been a web-application, I had probably sent the user to a new web page containing the form, but that sounds similar to a modal dialog for me. Should Dialogs be avoided in modern applications? and what are the alternatives? A: As general rule, you should use dialog boxes only when you have to. It’s preferred that you use direct manipulation or input or edit-in-place, where the user works directly on the data objects represented in a primary window. In the case of creating objects, the edit-in-place approach has either: An Insert button that creates the object and adds a blank row to the datagrid for input of the field values, A permanent blank row at the bottom of the datagrid (or elsewhere) –if the user types values into it, then the app creates a new object. I compare these two approaches on SO in answering the question “What’s best when inserting into a table view, an add button or a blank line?” Compared to either edit-in-place approaches, dialog boxes have following disadvantages: Additional learning. It adds a window to the app, with its title bar and buttons (e.g., OK and Cancel) and fields –fields that are often already exist on the parent datagrid, but arranged differently. This incrementally adds to what users have to learn. Attention shifting. Popping up a dialog requires that the user shift attention to something new, which has a certain re-orientation cost, and makes the user feel less in control of the data. Additional clicks. Dialog boxes need to be executed and dismissed. This takes at least one extra button click. In contrast, with edit-in-place the user can create multiple objects before saving (if saving isn’t automatic). Modality. If you have to have a modal dialog box, then you’re removing user flexibility, forcing users to either complete the creation or abandon it. If they need additional info from elsewhere in the app to complete the creation, they are forced to discard whatever work they’ve done. Risk of loss work. One accidental click of the Cancel button reverts any input the user made and dismisses the dialog, forcing the user the start over. One-click loss of multiple inputs is not characteristic of properly designed primary windows, plus primary windows typically support Undo. Dialogs should be used for atomic actions that require parameters; that is, situations where the app must have certain input from the user in order to technically or logically complete the action. For example, if creating an object requires field values that cannot be defaulted, then it’s probably good to use a dialog. Such a Create dialog probably should have only the required fields, not any optional ones. Let the user complete any optional fields back on the datagrid. Because of modality and risk of loss work, dialogs should be as simple as possible. As a rough rule of thumb, the user should be able to complete input in about 20 to 30 seconds –that’s a tolerable amount of work to have to re-do. You are correct that in web apps, a separate input page is pretty much equivalent to a modal dialog box, where the user is forced to either complete or cancel a transaction before doing anything else. This is what gives many web apps a clunky “indirect” feel compared to the fluid feel of a direct manipulation desktop equivalent.
[ "stackoverflow", "0033091410.txt" ]
Q: Setup Jupyter inside Fusion's CentOS 7 I am trying to install Jupyter inside CentOS 7 VM (that I already had) so I can access it via port 8888 at my host Mac laptop. However, I cannot figure out the networking piece. I am changing the IP address to 200.100.x.x for convenience From Host Machine I have 2 adapters for that CentOS VM $ ifconfig gives me this (I believe those are the same): vmnet1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:50:56:c0:00:01 inet 200.100.42.1 netmask 0xffffff00 broadcast 200.100.42.255 vmnet8: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:50:56:c0:00:08 inet 200.100.40.1 netmask 0xffffff00 broadcast 200.100.40.255 From within CentOS [root@localhost ~]# ifconfig eno16777736: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 200.100.40.145 netmask 255.255.255.0 broadcast 200.100.40.255 inet6 fe80::20c:29ff:febf:4878 prefixlen 64 scopeid 0x20<link> ether 00:0c:29:bf:48:78 txqueuelen 1000 (Ethernet) RX packets 645 bytes 97963 (95.6 KiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 215 bytes 24854 (24.2 KiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 eno33554984: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 200.100.42.128 netmask 255.255.255.0 broadcast 200.100.42.255 inet6 fe80::250:56ff:fe3d:7210 prefixlen 64 scopeid 0x20<link> ether 00:50:56:3d:72:10 txqueuelen 1000 (Ethernet) RX packets 18 bytes 1884 (1.8 KiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 45 bytes 6130 (5.9 KiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10<host> loop txqueuelen 0 (Local Loopback) RX packets 220 bytes 50398 (49.2 KiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 220 bytes 50398 (49.2 KiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 My tests I pinged the following IP addresses from my host machine and they all worked: 200.100.42.128 200.100.40.145 200.100.42.1 200.100.40.1 That means there is networking connectivity into the VM. Correct? When I do jupyter notebook, I could access http://localhost:8888/tree inside the VM but I cannot go there using any IP address from my host OS on the Macbook. I have restarted my VM many times. Questions Is it because of port blocking / not forwarding (8888) or something and if so, how to fix it? Did I setup the networking incorrectly? Is there something else I need to do inside CentOS? I read this blog here http://twiki.org/cgi-bin/view/Blog/BlogEntry201310x2 and I don't see eth0 at all. A: The problem is Jupyter picked 127.0.0.0 or localhost by default. If you have the adapter with other IP addresses, it won't work. You need to change the IP of Jupyter inside the VM http://jupyter-notebook.readthedocs.org/en/latest/config.html $ jupyter notebook --generate-config Edit it: vi /root/.jupyter/jupyter_notebook_config.py Then change: c.Notebookapp.ip = '0.0.0.0' Restart jupyter notebook and should be good to go. Make sure firewall is off or open for port 8888 as well.
[ "stackoverflow", "0059988473.txt" ]
Q: Delete all rows after first match of value in first row I'm trying to delete all rows after the first match of the value "##Section" in column A. My spreadsheet looks like this : blah blah blah ##Section blep blep blep ##Section Hi hi ... Here's my current code (not working) : Dim rng As Range Dim lastRow As Long With Sheets("import") 'find Terminations Set rng = .Range("A:A").Find(what:="##Section", after:=.Range("A1")).Row 'if ##Section NOT found - exit from sub If rng Is Nothing Then Exit Sub 'find last row If Application.WorksheetFunction.CountA(.Cells) <> 0 Then lastRow = .Cells.Find(what:="*", _ after:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row Else lastRow = 1 End If 'I use lastRow + 1 to prevent deletion "##Section" when it is on lastrow .Range(rng.Row + 1 & ":" & lastRow + 1).Delete Shift:=xlUp End With A: The problem is with the line Set rng = .Range("A:A").Find(what:="##Section", after:=.Range("A1")).Row You are trying to store a Long Value in a Range variable Try this Sub Sample() Dim rng As Range Dim sRow As Long, lastRow As Long With Sheets("import") 'find Terminations Set rng = .Range("A:A").Find(what:="##Section", after:=.Range("A1")) If Not rng Is Nothing Then '~~> Get the start row sRow = rng.Row + 1 'find last row If Application.WorksheetFunction.CountA(.Cells) <> 0 Then lastRow = .Cells.Find(what:="*", _ after:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row Else lastRow = 1 End If 'I use lastRow + 1 to prevent deletion "##Section" when it is on lastrow .Range(sRow & ":" & lastRow + 1).Delete Shift:=xlUp End If End With End Sub Or a succinct version Sub Sample() Dim ws As Worksheet Dim rng As Range Dim StartRow As Long, LastRow As Long Set ws = Sheets("import") With ws If Application.WorksheetFunction.CountA(.Cells) <> 0 Then '~~> Find last row LastRow = .Cells.Find(what:="*", _ after:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row + 1 '<~~ Added + 1 to last row here '~~> Identify your range and find Set rng = .Range("A1:A" & LastRow).Find(what:="##Section", after:=.Range("A1")) If Not rng Is Nothing Then '~~> Get the start row StartRow = rng.Row + 1 '~~> Delete the range .Range(StartRow & ":" & LastRow).Delete Shift:=xlUp End If End If End With End Sub
[ "stackoverflow", "0059409517.txt" ]
Q: Nuxt how to debug: The client-side rendered virtual DOM tree is not matching server-rendered content So in my Nuxt universal-mode app, I sometimes have an error which rises: vue.runtime.esm.js:620 [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render. Which usually comes along a second one (actually the second one sometimes rises without the first, not the other way round): TypeError: Cannot read property 'toLowerCase' of undefined at emptyNodeAt (vue.runtime.esm.js:5851) at VueComponent.patch [as __patch__] (vue.runtime.esm.js:6492) at VueComponent.Vue._update (vue.runtime.esm.js:3933) at VueComponent.updateComponent (vue.runtime.esm.js:4048) at Watcher.get (vue.runtime.esm.js:4467) at new Watcher (vue.runtime.esm.js:4456) at mountComponent (vue.runtime.esm.js:4061) at VueComponent.Vue.$mount (vue.runtime.esm.js:8399) at init (vue.runtime.esm.js:3115) at hydrate (vue.runtime.esm.js:6362) And then nothing works, since when I click to another page in my app, I get: client.js:134 TypeError: Cannot read property '_transitionClasses' of undefined at Array.updateClass (vue.runtime.esm.js:6799) at patchVnode (vue.runtime.esm.js:6298) at updateChildren (vue.runtime.esm.js:6177) at patchVnode (vue.runtime.esm.js:6303) at updateChildren (vue.runtime.esm.js:6177) at patchVnode (vue.runtime.esm.js:6303) at updateChildren (vue.runtime.esm.js:6177) at patchVnode (vue.runtime.esm.js:6303) at updateChildren (vue.runtime.esm.js:6177) at patchVnode (vue.runtime.esm.js:6303) I mostly understand the why this happens, though when it comes, I have no idea where to start from, since the error message doesn't give a single hint on what actually are the differences between the server-side version and the client one. So when this issue rises, the only thing I can do is to rollback to previous git commits until the issues fixes itself ... which unfortunately doesn't work very well, as sometimes the bug appears on code versions where it was not there previously. Usually the solution is to delete as many things as possible (.nuxt, node_install) and to set up everything from scratch and hopefully it works again. Finally my remarks/questions are: When the client-side version doesn't match the server-side bug appears, why can't we have more detailed informations on what differences? Any idea why this bug happens as a whole in such non-deterministic manner? Why is this breaking everything, while at first this is simply a warning? As for me this is a very big issue for a production app, as being so undeterministically fixable. A: Apparently in my case, the TypeError: Cannot read property 'toLowerCase' of undefined error was rising at error-reporting time. I happened to have the The client-side rendered virtual DOM tree is not matching server-rendered content warning in another context, I did receive useful explanations and it did not block execution so I shall consider the bug-over-the-bug was bad luck and would eventually get naturally fixed, unless it reproduces in the future. If you happen to have the same error, do not despair. First, report the TypeError: Cannot read property 'toLowerCase' of undefined error to the nuxt repo. Then, to debug, I encourage you to comment parts of your templates to find how to remove the error. In my case, it was in the layout, hence it happened all the time, but once I understood that, I found the explanation quite quickly (though it was a mysterious different behavior of date-fns between node environment and browser). Good luck!
[ "math.stackexchange", "0000771343.txt" ]
Q: Proving a function is bounded above. Hi all, while doing this question ,I feel that I understand the concept of the question, but can't seem to formulate it into a viable answer. If the limit as $x \rightarrow \infty$ is the same as $x \rightarrow -\infty$ and equals zero, just by thinking about the graph ,it is clear that there must be a maximum or minimum. Does the first condition imply the function is bounded? Any advice on answering this question would be much appreciated A: Pick some $\epsilon>0$ (for example $\epsilon=1$, why not). From $\lim_{x\to\infty}f(x)=0$ we conclude that there exists some $b\in\mathbb R$ such that $f(x)<\epsilon$ for all $x>b$. Similarly, there exists $a\in\mathbb R$ such that $f(x)<\epsilon$ for $x<a$ because $\lim_{x\to-\infty}f(x)=0$. If $a\ge b$, this shows $\epsilon$ is an upper bound for $f$. And if $a<b$, the continuous function $f$ is bounded on the compact interval $[a,b]$, say $f(x)<M$ for all $x\in[a,b]$. Then $\max\{\epsilon,M\}$ is an upper bound for $f$. Now use condition $(ii)$. Since $f(c)>0$ we can take $\epsilon=\frac12f(c)$ in the argument above. Then any upper bound we find must be $\ge f(c)$, which implies that $a<b$ and $M\ge f(c)$. The maximum of $f|_{[a,b]}$ is attained at some $x_0\in[a,b]$. As this is a global maximum of $f$, it must also be a local maximum, hence $f'(x_0)=0$.
[ "stackoverflow", "0050385043.txt" ]
Q: Post Anonymous object to MVC Action I am creating a MVC application where I need to expose a Action that will take 2 param. The first param will be string type and second will be an object. Based on first param value I will parse the object. I am trying to do something like this Client Side function SaveLookup() { debugger; var userData = {}; userData.lookupType = "Users"; userData.objLookup = { "UserID": 1, "UserCode": "XYZ", "FirstName": "FName", "LastName": "LNAme", "IsActive": "1", "UserRole": "2" }; $.ajax({ url: '/home/SaveLookup', dataType: 'json', type: 'POST', contentType: 'application/json;charset=utf-8', data: JSON.stringify(userData), success: function (result) { debugger; $("#partialviews").html(result); }, error: function (xhr) { debugger; alert(xhr); } }); } Server Side [HttpPost] public JsonResult SaveLookup(string lookupType, object objLookup) { if (lookupType == "Users") User uObject = JsonConvert.DeserializeObject<User>(objLookup); else if (lookupType == "xyz") return Json(""); } I am able to read the first param value but not able to parse the object. I tried the reflection but no luck. A: @Mohd Ansari, it seems like problem in your client side script. Use client side as function SaveLookup() { debugger; var userData = {}; userData.lookupType = "Users"; userData.objLookup = JSON.stringify({ "UserID": 1, "UserCode": "XYZ", "FirstName": "FName", "LastName": "LNAme", "IsActive": "1", "UserRole": "2" }); // console.log(JSON.stringify(userData)); $.ajax({ url: '/home/SaveLookup', dataType: 'json', type: 'POST', contentType: 'application/json;charset=utf-8', data: JSON.stringify(userData), success: function (result) { debugger; }, error: function (xhr) { debugger; alert(xhr); } }); } and your controller code should be [HttpPost] public JsonResult SaveLookup(string lookupType, string objLookup) { User uObject = new User(); if (lookupType == "Users") uObject =JsonConvert.DeserializeObject<User>(objLookup); return Json(""); } Let me know is that logic works for you ?
[ "stackoverflow", "0030713219.txt" ]
Q: iOS: SWRevealViewController opening WebView control without Navigation bar The app has a navigation bar that is included in all the scenes within the app. SWRevealViewController has been used to create a slide out menu, also appearing in all scenes. It contains a tableview that initiates the segues to other scenes. Two of the links in this menu segue to a webview control that loads a webpage. The webview loads the pages correctly, but without the navigation bar To make things more confusing, there are other scenes in the app that link to the webview where the navigation bar is loaded correctly. The navigation bar is not included in the SWRevealViewController. Could this be why it isn't loading correctly? Thanks in advance. A: When you are adding a ViewController you need to add it to a UINavigationController first. [self.revealViewController pushFrontViewController:[[UINavigationController alloc] initWithRootViewController:VC] animated:YES]; [self.revealViewController setFrontViewPosition:FrontViewPositionLeft animated:YES];
[ "magento.stackexchange", "0000311811.txt" ]
Q: How to move Hamburger Menu Magento 2 Does anyone know how to move hamburger menu before minicart in mobile view as shown below A: Please add/edit following css in you less file : Find below code from below file path : app\design\frontend\Orange\Orange-theme\Magento_Theme\web\css\source\_module.less .logo { float: left; margin: 0 0 10px 0px; max-width: 50%; position: relative; z-index: 5; } .nav-toggle { display: inline-block; text-decoration: none; cursor: pointer; display: block; font-size: 0; right: 15px; position: absolute; top: 15px; z-index: 14; } Find below code from below file path : app\design\frontend\Orange\Orange-theme\Magento_Checkout\web\css\source\module\_minicart.less .minicart-wrapper { display: inline-block; position: relative; float: right; margin-right: 40px; } Your expected output
[ "math.stackexchange", "0001789527.txt" ]
Q: Find limits of integration for the interior region of sphere with center $(a,0,0)$ and radius $a$ using spherical coordinates I am asked to find limits of integration for the interior region of sphere with center $(a,0,0)$ and radius $a$ using spherical coordinates. How can one do that? I know that one may use $$ x = r \cos(\theta) \sin(\phi)\\ y = r \sin(\theta) \sin(\phi)\\ z = r \cos(\phi) $$ Is it possible do to the same with cylindrical coordinates? Thank you. A: you have a few choices. rectangular: $(x-a)^2 + y^2 + z^2 = a^2\\ x^2 + y^2 + z$ = 2ax$ Spherical... since x is the "special one", I would suggest. $$x = r \cos(\phi)\\ y = r \sin(\theta) \sin(\phi)\\ z = r \cos(\theta) \sin(\phi)$$ Plug these into your equation for the sphere and, $r^2 = 2a\,r\cos\phi $ $r$ will range from $0$ to $2a\cos\phi, \theta$ from $0$ to $2\pi, \phi$ from $0$ to $\pi/2$ If you went with the traditional. $$x =r \cos(\theta) \sin(\phi)\\ y = r \sin(\theta) \sin(\phi)\\ z = r \cos(\phi)$$ Then $r$ will range from $0$ to $2a\cos\theta\sin\phi, \theta$ from$-\pi/2$ to $\pi/2$ how about...Taking the traditional and translating it. $$x =r \cos(\theta) \sin(\phi) + a\\ y = r \sin(\theta) \sin(\phi)\\ z = r \cos(\phi)$$ And $r$ goes from $0$ to $a.$ Cylindrical. $$x = x+a\\ y = r \sin(\theta)\\ z = r \cos(\theta)$$ x from $-\sqrt {a^2-r^2}$ to $\sqrt {a^2-r^2}$ or, $$x = x\\ y = r \sin(\theta)\\ z = r \cos(\theta)$$ x from $a-\sqrt {a^2-r^2}$ to $a+\sqrt {a^2-r^2}$ etc.
[ "stackoverflow", "0005523831.txt" ]
Q: How do you make Rails route everything under a path to a Rack app? I'm trying to capture all requests to /dav and all paths nested under that to a Rack handler: match "/dav" => RackDAV::Handler.new(:root => 'davdocs') match "/dav/*whatever" => RackDAV::Handler.new(:root => 'davdocs') Do I really have to make two routes for this, or is there a way to express this as one route (one line)? A: I think it should be enough to use match "/dav(/*whatever)" => RackDAV::Handler.new(:root => 'davdocs') Optional parameters are very briefly described in the Rails Routing guide under "Bound parameters"
[ "stackoverflow", "0005047859.txt" ]
Q: Raw Stream Has Data, Deflate Returns Zero Bytes I'm reading data (an adCenter report, as it happens), which is supposed to be zipped. Reading the contents with an ordinary stream, I get a couple thousand bytes of gibberish, so this seems reasonable. So I feed the stream to DeflateStream. First, it reports "Block length does not match with its complement." A brief search suggests that there is a two-byte prefix, and indeed if I call ReadByte() twice before opening DeflateStream, the exception goes away. However, DeflateStream now returns nothing at all. I've spent most of the afternoon chasing leads on this, with no luck. Help me, StackOverflow, you're my only hope! Can anyone tell me what I'm missing? Here's the code. Naturally I only enabled one of the two commented blocks at a time when testing. _results = new List<string[]>(); using (Stream compressed = response.GetResponseStream()) { // Skip the zlib prefix, which conflicts with the deflate specification compressed.ReadByte(); compressed.ReadByte(); // Reports reading 3,000-odd bytes, followed by random characters /*byte[] buffer = new byte[4096]; int bytesRead = compressed.Read(buffer, 0, 4096); Console.WriteLine("Read {0} bytes.", bytesRead.ToString("#,##0")); string content = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine(content);*/ using (DeflateStream decompressed = new DeflateStream(compressed, CompressionMode.Decompress)) { // Reports reading 0 bytes, and no output /*byte[] buffer = new byte[4096]; int bytesRead = decompressed.Read(buffer, 0, 4096); Console.WriteLine("Read {0} bytes.", bytesRead.ToString("#,##0")); string content = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine(content);*/ using (StreamReader reader = new StreamReader(decompressed)) while (reader.EndOfStream == false) _results.Add(reader.ReadLine().Split('\t')); } } As you can probably guess from the last line, the unzipped content should be TDT. Just for fun, I tried decompressing with GZipStream, but it reports that the magic number is not correct. MS' docs just say "The downloaded report is compressed by using zip compression. You must unzip the report before you can use its contents." Here's the code that finally worked. I had to save the content out to a file and read it back in. This does not seem reasonable, but for the small quantities of data I'm working with, it's acceptable, I'll take it! WebRequest request = HttpWebRequest.Create(reportURL); WebResponse response = request.GetResponse(); _results = new List<string[]>(); using (Stream compressed = response.GetResponseStream()) { // Save the content to a temporary location string zipFilePath = @"\\Server\Folder\adCenter\Temp.zip"; using (StreamWriter file = new StreamWriter(zipFilePath)) { compressed.CopyTo(file.BaseStream); file.Flush(); } // Get the first file from the temporary zip ZipFile zipFile = ZipFile.Read(zipFilePath); if (zipFile.Entries.Count > 1) throw new ApplicationException("Found " + zipFile.Entries.Count.ToString("#,##0") + " entries in the report; expected 1."); ZipEntry report = zipFile[0]; // Extract the data using (MemoryStream decompressed = new MemoryStream()) { report.Extract(decompressed); decompressed.Position = 0; // Note that the stream does NOT start at the beginning using (StreamReader reader = new StreamReader(decompressed)) while (reader.EndOfStream == false) _results.Add(reader.ReadLine().Split('\t')); } } A: You will find that DeflateStream is hugely limited in what data it will decompress. In fact if you are expecting entire files it will be of no use at all. There are hundereds of (mostly small) variations of ZIP files and DeflateStream will get along only with two or three of them. Best way is likely to use a dedicated library for reading Zip files/streams like DotNetZip or SharpZipLib (somewhat unmaintained).
[ "stackoverflow", "0056730920.txt" ]
Q: Odd behaviour of `json.dumps` for \u0000 character When I execute json.dumps("\u0000", ensure_ascii=False) in python3, I expect the output to be a 3 character string, specifically, the \u0000 character's representation to be enclosed in double-quotes. Here is what I get instead: print(json.dumps("\u0000", ensure_ascii=False)) "\u0000" Just to avoid any ambiguity related to my terminal len(json.dumps("\u0000", ensure_ascii=False)) 8 Which is quotes (2) + 4 zeros and \u (2) = 8 chars. This seems inconsistent with the treatment of other UTF8 chars: print(json.dumps("\u4e2d", ensure_ascii=False)) "中" len(json.dumps("\u4e2d", ensure_ascii=False)) 3 I am using: $ python3 -V Python 3.7.1 Is there something special about \u0000? A: According to ECMA-404, the following characters have to be escaped in a JSON string (Section 9): quotation mark (U+0022), reverse solidus (U+005C), and the control characters U+0000 to U+001F. There are short escape sequences like \n and \\ for some of them, but there is none for the null character. The standard explicitly states that you need a six-character sequence to represent such a character.
[ "stackoverflow", "0022389988.txt" ]
Q: two output graphs in matplotlib scatterplot animation I have some code to animate a scatterplot in matplotlib, everything runs smoothly, except that I end up with two output graphs at the end. One contains the desired animation, while the other is blank. While it is probably a simple issue someone, I cannot see why, nor figure out why I am getting two graphs. Can anyone see what is giving me the "bogus" empty graph? Cheers. import math, numpy, time, matplotlib, pyvisa from pyvisa import visa from matplotlib import pyplot, animation import os.path class Realtime_measurement_and_scatter_plot: def __init__(......): self.animaiton = animation.FuncAnimation(self.figure, self.take_new_data_and_update_graph, init_func=self.initialise_graph, frames = self.number_of_measurements, interval=100, blit=False) def initialise_graph(self): self.figure = matplotlib.pyplot.figure() self.axes = matplotlib.pyplot.axes() self.axes.set_title("Realtime Plot") self.x_data = [] self.y_data = [] self.scatterplot = matplotlib.pyplot.scatter(self.x_data, self.y_data) return self.scatterplot, def take_new_data_and_update_graph(self, i): ... averaged_voltage = numpy.average(measured_voltages ) new_time = float(i) * float( self.time_between_measurements ) self.x_data = numpy.append( self.x_data, averaged_voltage ) self.y_data = numpy.append( self.y_data , new_time ) self.scatterplot = matplotlib.pyplot.scatter(self.x_data, self.y_data) return self.scatterplot, animation_instance = Realtime_measurement_and_scatter_plot(1000000, 1 , 1, 6, "Super_FUN_TEST.0",22) matplotlib.pyplot.show() A: tcaswell's comment about "init uses attributes you don't create until initialize_graph" prompted me to fix that. Changing this so that init creates the figure, axes ect instead of them being created in intialize_graph removes the two output graphs problem; solving my problem!
[ "unix.stackexchange", "0000294023.txt" ]
Q: FAT32 / NTFS + isofs on USB I have a bootable USB disk: # dd if=/path/to/os_image.iso of=/dev/sdb (...everything OK...) # sudo dumpe2fs /dev/sdb dumpe2fs 1.42.9 (4-Feb-2014) dumpe2fs: Bad magic number in super-block while trying to open /dev/sdb Couldn't find valid filesystem superblock. GParted doesn't recognize any partitions (screenshot), the GUI file manager reports filesystem as isofs. The system boots and everything works fine. The problem is, I want to use the USB disk for a live OS and as a storage with PCs and TVs which only recognize FAT32 and NTFS. I have tried creating two partitions, doing dd on sdb1 and making sdb1 the only bootable partition, but the system didn't boot. So my question is: how to put both FAT32/NTFS and (any) bootable ISO image on an MBR-partitioned disk without using an external bootable-usb-creator program? I would like to simply use dd, as I do now. Presumably this could be solved using the right bootloader with the right configuration, I just don't know which bootloader and what configuration. A: Bootable usb thumb drive with 2 partitions. Windows and others may only see the first partition on a usb device even when there are multiple partitions. Therefore make your first primary partition the fat32 or NTFS partition so windows can see and use it. partition 1 - ntfs or vfat partition 2 - ext4 The second partition is where you will store the bootable iso. Use grub to load and select what live OS you want to use. steps: 1: zero out partition table sudo dd if=/dev/zero of=/dev/sdx bs=512 count=4 2: Create partitions (use cli “fdisk” or gui “gparted”) create partition table "msdos" create 2 partitions p1 = ntfs p2 = ext4 -- tag as bootable. format partitions. 3: Install grub bootloader to usb device sudo grub-install --boot-directory /mnt/usbp2/boot /dev/sdx Verify: If these exist all is well so far... /mnt/usbp2/boot/grub/fonts -- minimum unicode.pf2 /mnt/usbp2/boot/grub/i386-pc -- *.mod modules to load in you grub.cfg /mnt/usbp2/boot/grub/local -- languages /mnt/usbp2/boot/grub/grubenv -- environment variable storage 4: Create a grub.cfg file for the OS's on this pc sudo grub-mkconfig --output=/mnt/usbp2/boot/grub/grub.cfg Test by booting to usb 5: Copy support files to the usb iso files memdisk binary -- get from syslinux grub.cfg -- custom for your usb stick. Overwrite grub.cfg created by grub-mkconfig Note: each live iso may require different grub information. Note: If you only get a grub command line, your grub.cfg probably contains errors. Go minimal to start. 6: Create your custom usb boot installer. Copy the MBR and Partition Table dd if=/dev/sdx of=/custom_boot/cb_mbr.img bs=512 count=1 Copy the bootable partition dd if=/dev/sdx2 of=/custom_boot/cb_ext4.img bs=512 7: Create new bootable usb device Delete all existing partitions and clean MBR fdisk or gparted (delete partitions) dd if=dev/zero of=/dev/sdx bs=512 count=1 restore MBR and Partition Table dd if=/custom_boot/cb_mbr.img of=/dev/sdx bs=512 Restore bootable partition dd if=/custom_boot/cb_ext4.img of=/dev/sdx2 bs=512 Fix the first partition and reformat (fat32 or ntfs) fdisk or gparted My grub.cfg My Notes
[ "ru.stackoverflow", "0000430113.txt" ]
Q: Вызов метода класса со свойствами класса Скажем, есть сласс: class userclass{ public $var1; public $var2; public function myfunc($var1,$var2){ $summ = $var1+$var2; return $summ; } } Теперь нужно вызвать метод myfunc со свойствами var1 и var2 без явного назначения значений. $calc = new userclass; $calc->var1 = 10; $calc->var2 = 120; $var = $calc->myfunc(); /* т.е. что бы строчка выше вызвалась как $var= $calc->myfunc(10,120); */ Реально ли как то так извернуться, избегая глобальных переменных? A: Для того объекты и существуют public function myFunc() { return $this->var1 + $this->var2; } $this повзолит вам достучаться до любого свойтсва или метода в разрешенной области видимости (public, protected и private, объявленные в этом классе). Можно даже так: class Mrjvni { private $a; private $b; public function __construct($a, $b) { $this->a = $a; $this->b = $b; } public function myFunc() { return $this->a + $this->b; } }
[ "bitcoin.stackexchange", "0000003872.txt" ]
Q: Why do small transactions without fees ever get processed? I understand that adding a small transaction fee as incentive ensures block generators will include your transaction. When you have no transaction fee, what is their motivation then? Why do some people include it and some don't? I have read many accounts stating that small transactions are less likely to be included - so is a big (in terms of amount of bitcoin) transaction with no fees more likely to be included, and if so, why? A: 1) There is no motivation, asides your goodwill, or possibly wanting to support some useful Bitcoin tools, like the Bitcoin Faucet (transaction fees could eat up a lot of coins there). 2) It's a matter of how their pools and clients are set up. Some want to support the community by allowing no-fee transactions to be included in a block (as it costs them nothing), while others want to encourage people to pay fees by only including transactions with fees. 3) Technically, it might be less likely to be included if it gets really big in terms of data size (upwards to filling a block), but in most cases it won't matter (at least for now). Amount of Bitcoins sent doesn't really matter at the moment, but transactions on really small amount of coins can be discriminated against in the future should spamming them become more prevelent. All in all, it is encouraged that you pay your dues when sending transactions, as it helps the Bitcoin project grow. If nobody was paying to get their transactions processed, the miners might soon not earn enough to get by (especially with reward halving slowly getting closer), which would result in them stopping their operations and weakening the Bitcoin network. It's not much of a threat yet, but in the future it can become important.
[ "stackoverflow", "0015638658.txt" ]
Q: concatenate values within for loop to use outside the loop I'm building a website which has product details and images stored in 2 different tables. I don't want to join the tables, so I have 2 queries that grab the details. What I have done is passed the product id to grab all the images. The problem is, I want to store all the image urls in $img_block so i can display the product details and all the images, except for the first product. All the other products contain the previous images of the products. product 1 : image p1-1 and image p1-2 product 2 : image p1-1 image p1-2 image p2-1 product 3 : image p1-1 image p1-2 image p2-1 image 3-1 My Code: foreach ($products as $key=>$product): $images = $this->control_model->product_images($product['pid']); foreach ($images as $image): $img_block .='<img src="'.$image['url'].'" height="75px" width="75px">' ; endforeach; $msg .= '<div class="one_half_full"> <div class="listbox"> <div class="list_text"> <h4 style="font-weight:bold"><a href="#">'.$product['title'].'</a></h4> <p> <div class="clearfix" id="images"> '.$img_block.' </div>'; endforeach; Can someone please let me know how can i concatenate the correct image urls? A: Just initilize the $img_block like : (I add the final quote...) foreach ($products as $key=>$product): $images = $this->control_model->product_images($product['pid']); $img_block = ''; foreach ($images as $image): $img_block .='<img src="'.$image['url'].'" height="75px" width="75px">' ; endforeach; $msg .= '<div class="one_half_full"> <div class="listbox"> <div class="list_text"> <h4 style="font-weight:bold"><a href="#">'.$product['title'].'</a></h4> <p> <div class="clearfix" id="images"> '.$img_block.' </div>'; endforeach;
[ "worldbuilding.stackexchange", "0000156982.txt" ]
Q: Simulation or API to get sun light spectrum on earth given the position, time and day of the year Does anyone know a site, software, public API (or formula) to get the solar light spectrum on earth given the time of the day, day of the year, and earth meassurement position (lattitude, longitude)? Basically I need to know sunlight spectrum in realtime, including UltraViolet and InfraRed part of the spectrum. The clouds and other particles don't have to be taken into account, so basically, is there any way for calculating the angular incidence of the sun and thus the received light spectrum after being filtered by the atmosphere with the light incidence at the calculated angle? Thanks in advance! A: There are many models of this. Research keywords would be "Mie scattering," which controls how aerosols in the air scatter light, and "Rayleigh scattering," which is why the sky is blue to begin with. Essentially it boils down to a path integral. You integrate the depth of the atmosphere at any point. You can figure this out by calculating the solar angle from your position and taking the average thickness of a ray along that point to space. Once you know the depth of the atmosphere along the ray, you can calculate the amount of inscatter, absorption, and outscatter for a given frequency of light. Most graphical models do this for a given red, green, and blue wavelength (chosen for a particular color space), but the data is available for UV and infrared wavelengths as well. Above the Earth's atmosphere, the distance to the Sun becomes essentially irrelevant, as space doesn't scatter, and the insolation of the Sun on the Earth is a simple inverse square law calculation, and since the Earth is very small compared to the distance to the Sun, you can take that insolation as being from the center of the Sun to the center of the Earth (i.e. the orbital distance at that time). One of the best available papers on the subject is Eric Bruneton's Atmospheric Scattering model This model precomputes a set of scattering tables as a function of the sun's angle in the sky. It then becomes a trivial problem to determine that angle using standard astronomy calculations and the observer's position. A: Disregarding the Sun's (well characterized) ordinary cyclic and long term variation, all that changes with solar radiation (that you can calculate, anyway) is distance from the Sun and the Sun's apparently angle in the sky (which depends on date and time of day -- i.e. how much air the light must pass through). The lower the Sun's apparent sky position, the more filtering the air gives. Air preferentially filters blue light (by scattering), but doesn't change the fundamental spectrum (number, position, and intensity of emission or absorption lines, for instance). You should be able to find information (for photographers, if no other source) for light intensity and color changes throughout the day -- I recall the correction for exposure by rule ("Sunny f/16" rule) being plus 1 stop before 10 AM or after 2 PM (standard time, correct for DST), 2 stops before 8 and after 4, three stops if the sun is within five degrees of the horizon, and a particular filter (or color sensitivity correction for some panchromatic black and white films) within an hour of sunrise or sunset, the so-called "golden hour". Add one additional stop if more than 45 degrees from the equator, another if within one month of the winter solstice. Each "stop" corrects for a halving of the total light flux, so if you're down three stops, you have 1/8 the light level.
[ "stackoverflow", "0059987460.txt" ]
Q: Customizing PDFTextStripper PDFbox PDFTextStripper has a functionality to extract text from the whole document, is there a way to extract text only after a certain value when the value is recognized, for example : A B C D G 1 line A B C D G 2 line A B C D G 3 line QUANTITY 4 line I would like to start to extract text after it finds Quantity(String) If anyone dealt with PDFBox and have some suggestion, it would be much appreciated Or is it possible to add to the list only when it hits a line after a value that text will contain? A: Easiest solution is to capture whole text and then create a Pattern that says -> "DESCRIPTION\\s*Reference\\s*QUANTITY(.*)" so basically i want to capture everything on a single page from the mentioned above create a function that would take String text as a parameter locate a single matcher.group(1), and return String or Optional<String> create a Pattern and tell that pattern with regex where would you like to start capturing from
[ "graphicdesign.stackexchange", "0000116208.txt" ]
Q: What should a Brand Guideline include? So I'm trying to form a mock business to practice branding, and I stumbled across this useful answer to a post here. If I'm going to have a folder on my pc with all the branding information for that company, what are all the files/information that I need for a full branding guideline, and not just a logo pack? Do I need to include an image with the exact colors in CMYK and RGB? Do I need to have different forms of the logo in different colors? What about logotype? A: Branding guidelines documents can range from a couple of pages up to 50, 100 or even more pages in some cases, depending on the scale of the brand and so on. Better look at some examples and decide what you need and what you don't: Google Facebook Twitter Argento Jamie Oliver For a basic guidelines presentation you should at least include: logo slide (safe area, spacing, variations, etc) typography slide (font families to be used) colors slide (main and secondary colors, where to use each)
[ "stackoverflow", "0047688909.txt" ]
Q: combining two dictionaries after removing some componetnts I have two dictionaries as follows. A= {'photos': {'page': 1, 'pages': 2, 'perpage': 250, 'photo': [{'accuracy': '16', 'context': 0, 'datetaken': '2013-05-03 13:47:02', 'datetakengranularity': '0', 'datetakenunknown': '0', 'farm': 5, 'geo_is_contact': 0, 'geo_is_family': 0, 'geo_is_friend': 0, 'geo_is_public': 1, 'id': '26970758199', 'isfamily': 0, 'isfriend': 0, 'ispublic': 1, 'latitude': '5.944650', 'longitude': '80.459766', 'owner': '61943224@N04', 'place_id': 'kLamY9hTU7IVDlGv', 'secret': '1383a29a3b', 'server': '4563', 'title': 'Mirissa - Ask your Local Tour Dog', 'woeid': '2182931'}, {'accuracy': '14', 'context': 0, 'datetaken': '2017-09-28 18:13:17', 'datetakengranularity': 0, 'datetakenunknown': '1', 'farm': 5, 'geo_is_contact': 0, 'geo_is_family': 0, 'geo_is_friend': 0, 'geo_is_public': 1, 'id': '37343882352', 'isfamily': 0, 'isfriend': 0, 'ispublic': 1, 'latitude': '5.930026', 'longitude': '80.405502', 'owner': '7415626@N04', 'place_id': 'J1bv5NZTU70_mRm8', 'secret': 'c7135b74d2', 'server': '4335', 'title': 'Blue whale tail', 'woeid': '2179328'}], 'total': '2'}, 'stat': 'ok'} and the second dictonary as follows: B={'photos': {'page': 2, 'pages': 2, 'perpage': 250, 'photo': [{'accuracy': '12', 'context': 0, 'datetaken': '2013-02-19 12:02:57', 'datetakengranularity': '0', 'datetakenunknown': 0, 'farm': 9, 'geo_is_contact': 0, 'geo_is_family': 0, 'geo_is_friend': 0, 'geo_is_public': 1, 'id': '8516011398', 'isfamily': 0, 'isfriend': 0, 'ispublic': 1, 'latitude': '5.935533', 'longitude': '80.446357', 'owner': '22857808@N03', 'place_id': 'kLamY9hTU7IVDlGv', 'secret': 'e6c6b8548c', 'server': '8112', 'title': 'Whale & Dolphin Watching Mirissa', 'woeid': '2182931'}, {'accuracy': '12', 'context': 0, 'datetaken': '2013-02-19 11:13:47', 'datetakengranularity': '0', 'datetakenunknown': 0, 'farm': 9, 'geo_is_contact': 0, 'geo_is_family': 0, 'geo_is_friend': 0, 'geo_is_public': 1, 'id': '8514896103', 'isfamily': 0, 'isfriend': 0, 'ispublic': 1, 'latitude': '5.935533', 'longitude': '80.446357', 'owner': '22857808@N03', 'place_id': 'kLamY9hTU7IVDlGv', 'secret': '17df7f97e7', 'server': '8375', 'title': 'Whale & Dolphin Watching Mirissa', 'woeid': '2182931'}], 'total': '2'}, 'stat': 'ok'} I want to merge this dictonaries together after removing the {'photos': {'page': '', 'pages': '', 'perpage': '', and removing the last section of each of A and B dictionaries, 'total': ''}, 'stat': ''} sections in both A and B. So my final output should be like this, C='photo': [{'accuracy': '16', 'context': 0, 'datetaken': '2013-05-03 13:47:02', 'datetakengranularity': '0', 'datetakenunknown': '0', 'farm': 5, 'geo_is_contact': 0, 'geo_is_family': 0, 'geo_is_friend': 0, 'geo_is_public': 1, 'id': '26970758199', 'isfamily': 0, 'isfriend': 0, 'ispublic': 1, 'latitude': '5.944650', 'longitude': '80.459766', 'owner': '61943224@N04', 'place_id': 'kLamY9hTU7IVDlGv', 'secret': '1383a29a3b', 'server': '4563', 'title': 'Mirissa - Ask your Local Tour Dog', 'woeid': '2182931'}, {'accuracy': '14', 'context': 0, 'datetaken': '2017-09-28 18:13:17', 'datetakengranularity': 0, 'datetakenunknown': '1', 'farm': 5, 'geo_is_contact': 0, 'geo_is_family': 0, 'geo_is_friend': 0, 'geo_is_public': 1, 'id': '37343882352', 'isfamily': 0, 'isfriend': 0, 'ispublic': 1, 'latitude': '5.930026', 'longitude': '80.405502', 'owner': '7415626@N04', 'place_id': 'J1bv5NZTU70_mRm8', 'secret': 'c7135b74d2', 'server': '4335', 'title': 'Blue whale tail', 'woeid': '2179328'}, {'accuracy': '12', 'context': 0, 'datetaken': '2013-02-19 12:02:57', 'datetakengranularity': '0', 'datetakenunknown': 0, 'farm': 9, 'geo_is_contact': 0, 'geo_is_family': 0, 'geo_is_friend': 0, 'geo_is_public': 1, 'id': '8516011398', 'isfamily': 0, 'isfriend': 0, 'ispublic': 1, 'latitude': '5.935533', 'longitude': '80.446357', 'owner': '22857808@N03', 'place_id': 'kLamY9hTU7IVDlGv', 'secret': 'e6c6b8548c', 'server': '8112', 'title': 'Whale & Dolphin Watching Mirissa', 'woeid': '2182931'}, {'accuracy': '12', 'context': 0, 'datetaken': '2013-02-19 11:13:47', 'datetakengranularity': '0', 'datetakenunknown': 0, 'farm': 9, 'geo_is_contact': 0, 'geo_is_family': 0, 'geo_is_friend': 0, 'geo_is_public': 1, 'id': '8514896103', 'isfamily': 0, 'isfriend': 0, 'ispublic': 1, 'latitude': '5.935533', 'longitude': '80.446357', 'owner': '22857808@N03', 'place_id': 'kLamY9hTU7IVDlGv', 'secret': '17df7f97e7', 'server': '8375', 'title': 'Whale & Dolphin Watching Mirissa', 'woeid': '2182931'}] I have tried several dictionaries merging methods, and none of those yield results, I'm bit new to python. I would be grateful if someone can help. A: Try this:- C = A['photos']['photo'] C.extend(B['photos']['photo']) D = {'photo': C} print(D) Basically You need item photo from both the dictionaries. Since this Item's value is a list, we can create a new list called C with one list and extend the other list. Reference:- Python List extend()
[ "cs.stackexchange", "0000013451.txt" ]
Q: Few Big O example I am confusing with the following example. $n^{1.001} + n\log n = \Theta ( n^{1.001} )$, why not $n\log n$? $c_1 \le \frac{\log n}{n^{0.001}} \le c_2 $ OR $c_1\le \frac{n^{0.001}}{\log n} \le c_2$ For me both are same. Means both are giving some constant range for $c_1$ and $c_2$. $10 n^3 + 15 n^4 + 100 n^2 2^n = \mathcal O (100n^2 2^n) $ $\frac{6 n^3}{ \log n + 1} = \mathcal O(n^3)$ A: Note that $n^{1.001}+n\log n$ is $n\times(n^{0.001}+\log n)$. Forget about the first factor and focus on $n^{0.001}+\log n$. The key point is that, for $n$ large enough, $n^{0.001}$ is larger than $\log n$ (do you know/see that?). Hence $n^{0.001}+\log n$ is eventually between $n^{0.001}$ and $2 \times n^{0.001}$, i.e., is in $\Theta(n^{0.001})$. Then $n^{1.001}+n\log n$ is in $\Theta(n\times n^{0.001})$, i.e., in $\Theta(n^{1.001})$. On the other hand, for any fixed $c>0$, $\log n$ is always eventually dwarfed by $c\times n^{0.001}$. Hence $n^{1.001}$ is not $O(n\log n)$. A: To add on @phs's great answer: Note that $$ \lim_{n\to \infty} \frac{n^{0.001}}{\log n} = \infty$$ while $$ \lim_{n\to \infty} \frac{\log n}{n^{0.001}} = 0$$ (use L'Hôpital's rule). For (2), it's quite straight-forward: the term that is "most meaningful", that is, the term that grows the fastest is $n^22^n$. Again, $$\lim_{n\to \infty} \frac{n^22^n}{n^3} = \lim_{n\to \infty} \frac{n^22^n}{n^4} = \infty$$ Finally for (3), $O(n^3/\log n)$ would be correct as well, but the "O" notation gives only upper bound, which needs not necessarily be tight. Thus, $$ \frac{6n^3}{\log n+1} \in O(n^3/\log n) \in O(n^3) \in O(n^4) \in O(2^n) \in ...$$
[ "stackoverflow", "0060727789.txt" ]
Q: Turn Object of Nested Objects into an Object of Array Nested Objects I hope the title and this description aren't too confusing. WHAT I HAVE: An object containing two parent-objects (firstGroup and secondGroup). Each contains the children-objects. const dataObject = { firstGroup: { 0: { title: '0-firstGroup', description: '0th item in firstGroup!', added: 2018, }, 1: { title: '1-firstGroup', description: '1st item in firstGroup!', added: 2019, }, 2: { title: '2-firstGroup', description: '2nd item in firstGroup!', added: 2020, }, }, secondGrounp: { 0: { title: '0-secondGroup', description: '0th item in secondGroup!', delicate: true, timestamp: '10:30:25', }, 1: { title: '1-secondGroup', description: '1st item in secondGroup!', delicate: true, timestamp: '14:03:11', }, }, }; DESIRED RESULTS: I'd like the returned object's properties to be parent-arrays, containing the respective children-objects as elements. resultsDesired: { firstGroup: [ { title: '0-firstGroup', description: '0th item in firstGroup!', added: 2018, },{ title: '1-firstGroup', description: '1st item in firstGroup!', added: 2019, },{ title: '2-firstGroup', description: '2nd item in firstGroup!', added: 2020, }, ], secondGrounp: [ { title: '0-secondGroup', description: '0th item in secondGroup!', delicate: true, timestamp: '10:30:25', }, { title: '1-secondGroup', description: '1st item in secondGroup!', delicate: true, timestamp: '14:03:11', }, ], }; BONUS RESULTS: If you'd be willing to try this out as well, I'd also be interested in the returned object's properties to be parent-objects, containing label's of the parent identifiers and group-arrays with the children-objects as elements. resultsBonus: { firstGroup: { label: 'firstGroup', group: [ { title: '0-firstGroup', description: '0th item in firstGroup!', added: 2018, }, { title: '1-firstGroup', description: '1st item in firstGroup!', added: 2019, }, { title: '2-firstGroup', description: '2nd item in firstGroup!', added: 2020, }, ], }, secondGrounp: { label: 'secondGroup', group: [ { title: '0-secondGroup', description: '0th item in secondGroup!', delicate: true, timestamp: '10:30:25', }, { title: '1-secondGroup', description: '1st item in secondGroup!', delicate: true, timestamp: '14:03:11', }, ], }, }; EDIT - MY PREVIOUS ATTEMPT: @RyanWilson made a good point, I should have shown that I actually attempted this. Made lots of attempts, all of which were terrible. Below is the last one before asking... const arr = []; Object.keys(dataObject).forEach((key) => { arr.push(dataObject[key]); }); console.log('arr ', arr); /* LOG [ 0: { 0: { title: "0-firstGroup" description: "0th item in firstGroup!" added: 2018 }, 1: { title: "1-firstGroup" description: "1st item in firstGroup!" added: 2019 }, 2: { title: "2-firstGroup" description: "2nd item in firstGroup!" added: 2020 }, }, 1: { 0: { title: "0-secondGroup", description: "0th item in secondGroup!", delicate: true, timestamp: "10:30:25", }, 1: { title: "1-secondGroup", description: "1st item in secondGroup!", delicate: true, timestamp: "14:03:11", }, }, ] */ A: You could assign the nested objects to an Array. const dataObject = { firstGroup: { 0: { title: '0-firstGroup', description: '0th item in firstGroup!', added: 2018 }, 1: { title: '1-firstGroup', description: '1st item in firstGroup!', added: 2019 }, 2: { title: '2-firstGroup', description: '2nd item in firstGroup!', added: 2020 } },secondGrounp: { 0: { title: '0-secondGroup', description: '0th item in secondGroup!', delicate: true, timestamp: '10:30:25' }, 1: { title: '1-secondGroup', description: '1st item in secondGroup!', delicate: true, timestamp: '14:03:11' } } }, result = Object.fromEntries(Object .entries(dataObject) .map(([k, v]) => [k, Object.assign([], v)]) ); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }
[ "stackoverflow", "0035450741.txt" ]
Q: How to mock private method of another Class other than the Class under test using PowerMock? I have a class which I would like to test with a public method that calls the private method of another class. When I try calling the private method of the same class, everything works perfectly. The problem occours when I try to mock another private method that gets called from the class under test. Following is the code sample of the test class. @RunWith(PowerMockRunner.class) @PrepareForTest({CodeWithPrivateMethod.class,CodeWithAnotherPrivateMethod.class}) public class CodeWithPrivateMethodTest { @Test public void when_gambling_is_true_then_always_explode() throws Exception { CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod()); CodeWithAnotherPrivateMethod codeWithAnotherPrivateMethod = PowerMockito.spy(new CodeWithAnotherPrivateMethod()); /*when(codeWithAnotherPrivateMethod, method(CodeWithAnotherPrivateMethod.class, "doTheGame", String.class)) .withArguments(anyString()) .thenReturn(true);*/ PowerMockito.when(codeWithAnotherPrivateMethod, "doTheGame", anyString()).thenReturn(true); //PowerMockito.doReturn(true).when(codeWithAnotherPrivateMethod, "doTheGamble", anyString(),anyInt()); spy.meaningfulPublicApi(); } } Following is the code sample for the class under test import java.util.Random; public class CodeWithPrivateMethod { CodeWithAnotherPrivateMethod anotherPrivateMethod = new CodeWithAnotherPrivateMethod(); public void meaningfulPublicApi() { if (anotherPrivateMethod.doTheGame("Whatever")) { System.out.println("kaboom"); } } } And Following is the code sample for the class that gets called from the class under test import java.util.Random; public class CodeWithAnotherPrivateMethod { public boolean doTheGame(String string) { return doTheGamble("Whatever", 1 << 3); } private boolean doTheGamble(String whatever, int binary) { Random random = new Random(System.nanoTime()); boolean gamble = random.nextBoolean(); return gamble; } } So My Question is how do i succesfully mock doTheGamble() method of CodeWithAnotherPrivateMethod Class to make it return true always? A: The problem here is although you are creating a spy of CodeWithAnotherPrivateMethod in your test, a new instance of CodeWithAnotherPrivateMethod is created in CodeWithPrivateMethod. So, actually you are not using your mock. CodeWithAnotherPrivateMethod anotherPrivateMethod = new CodeWithAnotherPrivateMethod(); To avoid this, you can force to return your CodeWithAnotherPrivateMethod mock when a new instance is created. You can use PowerMockito whenNew() capability to do this. Example: PowerMockito.whenNew(CodeWithAnotherPrivateMethod.class).withAnyArguments().thenReturn(codeWithAnotherPrivateMethod); Finally, your test should be something like this: @Test public void when_gambling_is_true_then_always_explode() throws Exception { // Spy CodeWithAnotherPrivateMethod and force return true when doTheGamble is called CodeWithAnotherPrivateMethod codeWithAnotherPrivateMethod = PowerMockito.spy(new CodeWithAnotherPrivateMethod()); PowerMockito.doReturn(true).when(codeWithAnotherPrivateMethod, "doTheGamble", Mockito.anyString(), Mockito.anyInt()); // Return your mock when a new instance of CodeWithAnotherPrivateMethod is created. PowerMockito.whenNew(CodeWithAnotherPrivateMethod.class).withAnyArguments().thenReturn(codeWithAnotherPrivateMethod); CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod()); spy.meaningfulPublicApi(); } Hope it helps.
[ "stackoverflow", "0060629297.txt" ]
Q: spark read schema from separate file I have my data in HDFS and it's schema in MySQL. I'm able to fetch the schema to a DataFrame and it is as below : col1,string col2,date col3,int col4,string How to read this schema and assign it to data while reading from HDFS? I will be reading schema from MySql . It will be different for different datasets . I require a dynamic approach , where for any dataset I can fetch schema details from MySQL -> convert it into schema -> and then apply to dataset. A: You can use the built-in pyspark function _parse_datatype_string: from pyspark.sql.types import _parse_datatype_string df = spark.createDataFrame([ ["col1,string"], ["col3,int"], ["col3,int"] ], ["schema"]) str_schema = ",".join(map(lambda c: c["schema"].replace(",", ":") , df.collect())) # col1:string,col3:int,col3:int final_schema = _parse_datatype_string(str_schema) # StructType(List(StructField(col1,StringType,true),StructField(col3,IntegerType,true),StructField(col3,IntegerType,true))) _parse_datatype_string expects a DDL-formatted string i.e: col1:string, col2:int hence we need first to replace , with : then join all together seperated by comma. The function will return an instance of StructType which will be your final schema.
[ "pt.stackoverflow", "0000333612.txt" ]
Q: problema com um grid bootstrap não estou conseguindo tirar essa separação que está ao lado do adicionar carrinho. codigo html: <div class="container"> <div class="row"> <div class="item"> <div class="row"> <div class="col-sm-4 col-md-12 col-lg-3 mt-3 mb-3"> <div class="col-item"> <div class="photo"> <img src="http://placehold.it/350x260" class="img-responsive" alt="a" /> </div> <div class="info"> <div class="row"> <div class="price col-md-12"> <h5 class="text-center mb-2"> Produto 1</h5> <h5 class="price-text-color text-center mb-3"> R$199.99</h5> </div> </div> <div class="separator clear-left"> <p class="btn-add mt-4 ml-5"> <i class="fa fa-shopping-cart"></i><a href="http://www.jquery2dotnet.com" class="hidden-sm">Adicionar ao Carrinho</a></p> </div> <div class="clearfix"> </div> </div> </div> </div> <div class="col-sm-4 col-md-12 col-lg-3 mt-3 mb-3"> <div class="col-item"> <div class="photo"> <img src="http://placehold.it/350x260" class="img-responsive" alt="a" /> </div> <div class="info"> <div class="row"> <div class="price col-md-12"> <h5 class="text-center mb-2"> Produto 1</h5> <h5 class="price-text-color text-center mb-3"> R$199.99</h5> </div> </div> <div class="separator clear-left"> <p class="btn-add mt-4 ml-5"> <i class="fa fa-shopping-cart"></i><a href="http://www.jquery2dotnet.com" class="hidden-sm">Adicionar ao Carrinho</a></p> </div> <div class="clearfix"> </div> </div> </div> </div> <div class="col-sm-4 col-md-12 col-lg-3 mt-3 mb-3"> <div class="col-item"> <div class="photo"> <img src="http://placehold.it/350x260" class="img-responsive" alt="a" /> </div> <div class="info"> <div class="row"> <div class="price col-md-12"> <h5 class="text-center mb-2"> Produto 1</h5> <h5 class="price-text-color text-center mb-3"> R$199.99</h5> </div> </div> <div class="separator clear-left"> <p class="btn-add mt-4 ml-5"> <i class="fa fa-shopping-cart"></i><a href="http://www.jquery2dotnet.com" class="hidden-sm">Adicionar ao Carrinho</a></p> </div> <div class="clearfix"> </div> </div> </div> </div> <div class="col-sm-4 col-md-12 col-lg-3 mt-3 mb-3"> <div class="col-item"> <div class="photo"> <img src="http://placehold.it/350x260" class="img-responsive" alt="a" /> </div> <div class="info"> <div class="row"> <div class="price col-md-12"> <h5 class="text-center mb-2"> Produto 1</h5> <h5 class="price-text-color text-center mb-3"> R$199.99</h5> </div> </div> <div class="separator clear-left"> <p class="btn-add mt-4 ml-5"> <i class="fa fa-shopping-cart"></i><a href="http://www.jquery2dotnet.com" class="hidden-sm">Adicionar ao Carrinho</a></p> </div> <div class="clearfix"> </div> </div> </div> </div> </div> </div> </div> </div> css: .col-item { border: 1px solid #E1E1E1; border-radius: 5px; background: #FFF; } .col-item .photo img { margin: 0 auto; width: 100%; } .col-item .info { padding: 10px; border-radius: 0 0 5px 5px; margin-top: 1px; } .col-item:hover .info { background-color: #F5F5DC; } .col-item .price { /*width: 50%;*/ float: left; margin-top: 5px; } .col-item .price h5 { line-height: 20px; margin: 0; } .price-text-color { color: #219FD1; } .col-item .separator { border-top: 1px solid #E1E1E1; } .clear-left { clear: left; } .col-item .btn-add { width: 50%; float: left; } .col-item .btn-add { border-right: 1px solid #E1E1E1; } .col-item .btn-details { width: 50%; float: left; padding-left: 10px; } .controls { margin-top: 20px; } [data-slide="prev"] { margin-right: 10px; } Estou usando bootstrap 4.1.3 A: Para tira essa linha que faz o separado basta vc remover a class essa classe do elemento. Deixei apenas no último elemento para vc pode visualizar com e sem a borda .col-item .btn-add { border-right: 1px solid #E1E1E1; } Veja como fica depois que remove ela do elemento .col-item { border: 1px solid #E1E1E1; border-radius: 5px; background: #FFF; } .col-item .photo img { margin: 0 auto; width: 100%; } .col-item .info { padding: 10px; border-radius: 0 0 5px 5px; margin-top: 1px; } .col-item:hover .info { background-color: #F5F5DC; } .col-item .price { /*width: 50%;*/ float: left; margin-top: 5px; } .col-item .price h5 { line-height: 20px; margin: 0; } .price-text-color { color: #219FD1; } .col-item .separator { border-top: 1px solid #E1E1E1; } .clear-left { clear: left; } .col-item .btn-add { width: 50%; float: left; } .col-item .btn-add { /* bastar tirar essa borda */ border-right: 1px solid #E1E1E1; } .col-item .btn-details { width: 50%; float: left; padding-left: 10px; } .controls { margin-top: 20px; } [data-slide="prev"] { margin-right: 10px; } <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <div class="container"> <div class="row"> <div class="item"> <div class="row"> <div class="col-sm-4 col-md-12 col-lg-3 mt-3 mb-3"> <div class="col-item"> <div class="photo"> <img src="http://placehold.it/350x260" class="img-responsive" alt="a" /> </div> <div class="info"> <div class="row"> <div class="price col-md-12"> <h5 class="text-center mb-2"> Produto 1</h5> <h5 class="price-text-color text-center mb-3"> R$199.99</h5> </div> </div> <div class="separator clear-left"> <p class=" mt-4 ml-5"> <i class="fa fa-shopping-cart"></i><a href="http://www.jquery2dotnet.com" class="hidden-sm">Adicionar ao Carrinho</a></p> </div> <div class="clearfix"> </div> </div> </div> </div> <div class="col-sm-4 col-md-12 col-lg-3 mt-3 mb-3"> <div class="col-item"> <div class="photo"> <img src="http://placehold.it/350x260" class="img-responsive" alt="a" /> </div> <div class="info"> <div class="row"> <div class="price col-md-12"> <h5 class="text-center mb-2"> Produto 1</h5> <h5 class="price-text-color text-center mb-3"> R$199.99</h5> </div> </div> <div class="separator clear-left"> <p class=" mt-4 ml-5"> <i class="fa fa-shopping-cart"></i><a href="http://www.jquery2dotnet.com" class="hidden-sm">Adicionar ao Carrinho</a></p> </div> <div class="clearfix"> </div> </div> </div> </div> <div class="col-sm-4 col-md-12 col-lg-3 mt-3 mb-3"> <div class="col-item"> <div class="photo"> <img src="http://placehold.it/350x260" class="img-responsive" alt="a" /> </div> <div class="info"> <div class="row"> <div class="price col-md-12"> <h5 class="text-center mb-2"> Produto 1</h5> <h5 class="price-text-color text-center mb-3"> R$199.99</h5> </div> </div> <div class="separator clear-left"> <p class=" mt-4 ml-5"> <i class="fa fa-shopping-cart"></i><a href="http://www.jquery2dotnet.com" class="hidden-sm">Adicionar ao Carrinho</a></p> </div> <div class="clearfix"> </div> </div> </div> </div> <div class="col-sm-4 col-md-12 col-lg-3 mt-3 mb-3"> <div class="col-item"> <div class="photo"> <img src="http://placehold.it/350x260" class="img-responsive" alt="a" /> </div> <div class="info"> <div class="row"> <div class="price col-md-12"> <h5 class="text-center mb-2"> Produto 1</h5> <h5 class="price-text-color text-center mb-3"> R$199.99</h5> </div> </div> <div class="separator clear-left"> <p class="btn-add mt-4 ml-5"> <i class="fa fa-shopping-cart"></i><a href="http://www.jquery2dotnet.com" class="hidden-sm">Adicionar ao Carrinho</a></p> </div> <div class="clearfix"> </div> </div> </div> </div> </div> </div> </div> </div>
[ "stackoverflow", "0026973220.txt" ]
Q: AngularJS / CSS - How to set the width of a select box to a value from $scope? I've got two select boxes. The first one is changing the entires of the second one. The second one always adjusts it's length to the longest of the actual entries. But it looks wuite ugly if the width always changes when i select another item of the first box. Is it possible to set the width of the second box to a fixed value, calculated by the longest element of the whole (non-filtered) second box element list? In the scope I can calculate the number of characters of the longest element. Can I adjust this to the width somehow? I already tried (for testing) <select ... style="width:{{getMaxLength()}}px" > </select> returning the number of characters by the method getMaxLength() in the scope. But it didn't change anything. Did anyone already try this? Setting the size with ng-attr-size worked, but it's the height which does help me nothing. I'd appreciate every hint or idea! jana Addition: My example did not work with the answers because I didn't give the a "name" property. Then the answer from Muhammad Reda worked fine and I'm sure most of the other ideas will work as well. I found out by very thoroughly comparing Muhammads plunker with my code. That was the only difference. A: You can use ngStyle From documentation: The ngStyle directive allows you to set CSS style on an HTML element conditionally. Example: <select ng-style="{'width': getMaxLength() + 'px'}"></select> Plunker
[ "stackoverflow", "0009048088.txt" ]
Q: How to fire an event only when a particular element is visible I have an alert div, which appears when a user clicks on a link. Now what I want to do is to hide that div when somebody clicks outside it. It by default has a fadeoff event attached, but I want the user be able to hide that div by clicking elsewhere. I tried putting $('body').click inside the function call but its does not work. Please help, here is my javascript var messageDiv = $('<div id="cannotDoDiv"></div>'); $('body').append(messageDiv); function appendDiv(this_element,msg) { var pos = this_element.offset(); var width = this_element.width(); messageDiv.css({ left: (pos.left - 20) + 'px', top: pos.top + 30 + 'px' }); $('#cannotDoDiv').fadeOut(); $('#cannotDoDiv').html(msg).show().delay(1000).fadeOut(); $('body').click(function(){ $('#cannotDoDiv').hide(); }); } $("span#selfLike").click(function(){ appendDiv($(this),'You cannot like your own post!'); }); When I remove $('body').click(function(){ $('#cannotDoDiv').hide(); }); from my function $("span#selfLike").click works fine, otherwise it is not being fired. A: Edit: I think, I understood what you are trying.. see updated code below which Uses .one to bind only once and unbinds after it is done.. Used on fadeIn callback so it will be binded only after the div is visible.. //used call back function so it will be called only after it is //completly visible $('#cannotDoDiv').html(msg).fadeIn("slow", function () { // below will be executed once and then unbind $(document).one('click', function(){ $('#cannotDoDiv').fadeOut(); }); }); Below is the complete code.. Updated DEMO here $(document).ready (function () { var messageDiv = $('<div id="cannotDoDiv"></div>'); $('body').append(messageDiv); function appendDiv(this_element,msg) { var pos = this_element.offset(); var width = this_element.width(); messageDiv.css({ left: (pos.left - 20) + 'px', top: pos.top + 30 + 'px' }); $('#cannotDoDiv').hide(); $('#cannotDoDiv').html(msg).fadeIn("slow", function () { $(document).one('click', function(){ $('#cannotDoDiv').fadeOut(); }); }); $('#cannotDoDiv').one('click', function(){ $('#cannotDoDiv').fadeOut(); }); } $("span#selfLike").click(function(event){ appendDiv($(this),'You cannot like your own post!'); event.stopPropagation(); }); }); Note: This also closes when you click on the $('#cannotDoDiv') div. Add an click listener and stopPropogation if you don't want that to happen. Try $(document).click(function(){ instead of body.
[ "stackoverflow", "0005068630.txt" ]
Q: Safari/Webkit processing function too early after ajax:complete i have an ajax call i am doing and its working just fine. thing is, i need the dimensions of an image. i cant declare these dimensions in html, cause they are dynamically resized. now if i call a function during my complete state, for fetching these dimensions, webkit browsers put out 0, while FF puts out the correct dimensions. $.ajax({ url: event.path, cache: false, error: function(XMLHttpRequest, textStatus, errorThrown) { handler(XMLHttpRequest.responseText); }, success: function(data, textStatus, XMLHttpRequest) { handler(data); }, complete: function() { textBoxWidth(); } }); and this is the called function function textBoxWidth() { $("#project .textBox").css("width", $("#project .imgBox:last img").width()); } any suggestions for this? i tried if (jQuery.browser.safari && document.readyState != 'complete') but the document state isnt changing at all, once the DOM is ready.. thanks. A: another example, of how to let jquery wait while loading is jQuery.active. its a variable that spits out 1, if jquery is still loading and 0 if its finished. $.ajax({ url: path, cache: false, error: function(XMLHttpRequest, textStatus, errorThrown) { handler(XMLHttpRequest.responseText); }, success: function(data, textStatus, XMLHttpRequest) { handler(data); }, complete: function() { if (jQuery.active !== 0) { setTimeout( arguments.callee, 100 ); return; } //fancyFunction(); } });
[ "stackoverflow", "0007465470.txt" ]
Q: Simple code confusion about define directive parameter I'm trying to learn C to program this small routine on a Texas Instruments MSP430. Could you help me understand the ((unsigned char *) 0x0023) part? I'm having issues understanding this middle portion of this Define directive. I've tried looking this up but found nothing on the ((unsigned char *) 0x0023) portion. This looks like a type cast but its not casting anything. My major concern is the 0x0023 (decimal 35). Is this just a unsigned char pointer with 35 bits? Code: #define P1IFG_ptr ((unsigned char *) 0x0023) unsigned char result; Any help is really appreciated and thank you in advance. A: ((unsigned char *) 0x0023) Is a pointer to address 0x23 I think there's a missing newline in your code sample... On the MSP430 this is the port P1 interrupt flag register: Each PxIFGx bit is the interrupt flag for its corresponding I/O pin and is set when the selected input signal edge occurs at the pin. All PxIFGx interrupt flags request an interrupt when their corresponding PxIE bit and the GIE bit are set. Each PxIFG flag must be reset with software. Software can also set each PxIFG flag, providing a way to generate a software initiated interrupt. Bit = 0: No interrupt is pending Bit = 1: An interrupt is pending Only transitions, not static levels, cause interrupts. If any PxIFGx flag becomes set during a Px interrupt service routine, or is set after the RETI instruction of a Px interrupt service routine is executed, the set PxIFGx flag generates another interrupt. This ensures that each transition is acknowledged. You can read from this register, e.g.: unsigned char result; result = *P1IFG_ptr; Or write to it, e.g.: *P1IFG_ptr = 1;
[ "math.stackexchange", "0001611723.txt" ]
Q: Angle of Revolution for a truck I am doing a problem out of my textbook, which I don't understand. In my Alg2/Trig class, we are learning about angular speed, and linear speed in terms of angular speed. I can't figure out how to solve this using those. Please note, a full explanation is not required. Even just a hint can help. Lastly, I appreciate any help, but helping me using math that is way beyond me doesn't help me. Problem: A tite on a truck has a diameter of 31.125 in. Through what angle (radians) does the tire turn when traveling 1 mile A: Notice, in general, the angle $\theta$ turned by the wheel $$\theta=2\pi \times \frac{\text{distance traveled by the wheel}\ (D)}{\text{circumference of wheel}\ (\pi d)}=\frac{2 D}d$$ setting the corresponding values of distance, $D=1\ \mathrm{mile}=1609.344\ m$ & diameter, $d=31.125\ in.=31.125\times 0.0254\ m$, the angle turned by the wheel $$\theta=\frac{2\times 1609.344\ m}{31.125\times 0.0254\ m}=\color{red}{4071.325302\ \mathrm{radians}}$$
[ "stackoverflow", "0037458959.txt" ]
Q: Android - Remove shadow between Toolbar and TabLayout I'm trying to make a layout with CollapsingToolbarLayout. But I do not get one thing. I want to remove the shadow between Toolbar and TabLayout. I've tried several ways and I have not managed to remove the shadow. Can anybody help me? Thank you <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white" android:fitsSystemWindows="true"> <android.support.design.widget.CoordinatorLayout android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/adview" android:fitsSystemWindows="true"> <android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="50dp" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="50dp" android:layout_gravity="bottom" android:background="?attr/colorPrimary" android:translationZ="2dp" app:layout_anchor="@+id/appbar" app:layout_anchorGravity="bottom" app:tabGravity="fill" app:tabIndicatorColor="@android:color/white" app:tabIndicatorHeight="3dp" app:tabMode="fixed" app:tabTextColor="@color/tabs_text_selector" /> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="200dp" android:fitsSystemWindows="true" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <net.opacapp.multilinecollapsingtoolbar.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:expandedTitleMarginEnd="20dp" app:expandedTitleMarginStart="20dp" app:expandedTitleTextAppearance="@style/detalle_txt_expanded" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <ImageView android:id="@+id/detalle_img" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:scaleType="centerCrop" android:src="@drawable/img_thumb_m" android:transitionName="@string/transition" app:layout_collapseMode="parallax" tools:targetApi="lollipop" /> <ImageView android:id="@+id/detalle_img_tipo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="15dp" android:layout_gravity="center_horizontal" android:src="@drawable/img_edificio"/> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:minHeight="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/AppTheme"/> </net.opacapp.multilinecollapsingtoolbar.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <android.support.design.widget.FloatingActionButton android:id="@+id/detalle_info_fab_check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:clickable="false" android:src="@drawable/ic_check1" app:fabSize="mini" app:backgroundTint="@android:color/white" app:layout_anchor="@+id/appbar" app:layout_anchorGravity="bottom|right|end" /> </android.support.design.widget.CoordinatorLayout> <include android:id="@+id/adview" layout="@layout/adview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" /> A: Try setting app:elevation="0dp" (not android:elevation) for your AppBarLayout. In case you don't have the app namespace in your xml, add xmlns:app="http://schemas.android.com/apk/res-auto". The difference between these two properties can be found here. After that, check that you're not adding some background/border with any of these properties: <android.support.design.widget.TabLayout android:background="?attr/colorPrimary" android:translationZ="2dp" app:layout_anchor="@+id/appbar" app:layout_anchorGravity="bottom" app:tabGravity="fill" app:tabIndicatorColor="@android:color/white"/> Or the theme you're using for the AppBarLayout. A: <android.support.design.widget.AppBarLayout android:id="@+id/appBar" android:layout_width="match_parent" android:layout_height="wrap_content" app:elevation="0dp"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="56dp" app:titleTextColor="@android:color/white" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_tablayout" /> Use app:elevation="0dp" to remove the shadow. It has always worked for me. Hope it works for you. And also by programatically, appBar.setOutlineProvider(null);
[ "stackoverflow", "0040891515.txt" ]
Q: WebApi Internal Server Error I have 2 projects, a Front-End (AngularJS) and a Back-End (C# Web-Api). The thing is, when the front-end query the api (e.g GET localhost/api/Especialistas?rol=XXXX) I get a 500 error. Here is the code of the API: public IHttpActionResult GetEspecialista(string rol) { Especialista especialista = db.Especialistas.First( e=> e.Rol == rol); if (especialista == null) { return NotFound(); } return Ok(especialista); } The API is working, since I reach the return Ok(especialista). The Front-end is using this Restangular to query the API Restangular.one("Especialistas?rol=XXXX").get() The Network console shows a request 200 OK OPTION, but a 500 Internal Server Error GET. I tried a message handler in the WebApiConfig.cs file to check if the GET request was reaching the Api, and is indeed reaching it, so I don't know what happened, since I didn't change any configuration file. Any clue on how to fix this problem will be appreciated, thanks. A: If your action is called successfully, but still receive a 500 error, I think the error is created by the serializing of especialista object when converted to a HTTP response. Most probably, serialization fails because of some navigation properties which creat cycles in your object graph. It is recommended to return simple objects, not entity framework models. Try the following: var retObj = new { Prop1 = especialista.Prop1, Prop2 = especialista.Prop2 }; return Ok(retObj); If above code works, I suggest creating service models "mirror" objects that should be populated based on your data models. These objects should be returned instead of data models. A good helper to avoid the boilerplate code of property value assignments is Automapper.
[ "stackoverflow", "0019072683.txt" ]
Q: How to display discontinuous line chart I need a javascript library where I can really easily display two dimensional data in the form of a line chart. I need to display discontinuous lines. I've looked at a few libraries, but they do much more than I want. I tried with Rickshaw, but it accepts only a series. Let's say I have this data: long_short_data = [ { key:'round_1_1', color:"#468966", values:[ { label:"user_0", value:31 }, { label:"user_1", value:93 } ] }, { key:'round_1_2', color:"red", values:[ { }, { label:"user_1", value:34 } ] } ]; Here I want that the round_1_2 basically to start from the second tick. I've used this data with nvd3's stackedmultibarcharts, but I need to represent it in the form of line chart/time series. A: I've found an answer here. If anybody else has the same problem you will understand how the data is constructed if you check out the documentation.
[ "stackoverflow", "0044159088.txt" ]
Q: Abort/cancel/abandon a http request in angular js and retry it again I am working on an application in which i have to stop listening to a request if certain time is passed like if there is no response from a request in 60 secs then i have to abort that request and also there are multiple requests are going at a time. I don't know know how to keep track of each request with abort time(60 secs). I mean how would i know which request is to abort. I want to implement this functionality in my AngularJS interceptor. I have tried many blogs and post that claims to achieve this functionality but nothing helps me here is my interceptor code $httpProvider.interceptors.push(['$cookies', '$rootScope', '$q', '$localStorage', '$sessionStorage','$timeout', function ($cookies, $rootScope, $q, $localStorage, $sessionStorage, $timeout) { return { 'request': function (config) { config.headers = config.headers || {}; if (typeof config.data !== 'object') { config.headers['Content-Type'] = 'application/x-www-form-urlencoded'; } config.headers.Accept = 'application/json;odata=verbose'; config.headers['X-Requested-With'] = 'XMLHttpRequest'; var token = $localStorage.authToken || $sessionStorage.authToken; if (token) { config.headers.Authorization = 'Bearer ' + token; } return config; }, 'responseError': function (response) { var status = response.status; var error = ''; if(response.data.error) { error = response.data.error; } if(status === 401) { $rootScope.unauthorizedLogout(); } else if(status === 400 && (error === 'token_invalid' || error === 'token_not_provided')) { $rootScope.unauthorizedLogout(); } return $q.reject(response); } }; }]); I do tried the $q.defer and it's resolve method to cancel request but it's not helping me to achieve the functionality i want in application. Peace out V A: This answer helped me a lot set incremented timeout value to request config.timeout = incrementalTimeout; Your interceptor for handling response error should look like this 'responseError': function (response) { var status = response.status; var error = ''; //functionality to for request aborting and resending if (status === -1 || status >= 500) { if (attempts <= 3) { attempts += 1; return retryRequest(response.config); } } else { // set incrementalTiemout and attempts to default value incrementalTimeout = 4000; attempts = 1; } if(response.data.error) { error = response.data.error; } if(status === 401) { $rootScope.unauthorizedLogout(); } else if(status === 400 && (error === 'token_invalid' || error === 'token_not_provided')) { $rootScope.unauthorizedLogout(); } return $q.reject(response); } code to resend request in your interceptor // default request timeout is of 4 seconds and attempt is 1 var incrementalTimeout = 4000; var attempts = 1; function retryRequest (httpConfig) { var thisTimeout = incrementalTimeout; incrementalTimeout += 1000; return $timeout(function() { var $http = $injector.get('$http'); return $http(httpConfig); }, thisTimeout); }
[ "superuser", "0000264012.txt" ]
Q: How do I get Mail.app to not send mail in offline mode? I want to review my mail before it's sent out using Mail.app 4.4 In order to do that, I take all my accounts offline, but I noticed that my mail is still sent right away because I've got an active internet connection. Is there a way to have my outgoing mail sit in an Outbox so I can take a look at it before I'm ready to blast them all out? This account is using a corporate Google Apps account (Gmail) with the standard IMAP/SMTP setup. (Ideally, I’d like to keep my internet connection on – I know that unplugging my machine is one solution to this, but I need to also be able to access the web to answer mail :) A: If you want to save a draft of a message without sending it, just hit Save, not Send. It'll be saved in your Drafts folder instead of your Outbox. Then you can review your drafts later, and choose to send, continue editing, or delete.
[ "stackoverflow", "0051061583.txt" ]
Q: How to update service proxy aspnet boilerplate I just downloaded the latest version 3.7 of AspNetBoilerplate with Angular 5 and I was trying to use my new service that I created. It was not showing up in the service proxy. How do I update the auto generated code from swagger? A: Go to the angular\nswag> folder. There is a refresh.bat file in there. Execute that file while the project is running in VS 2017 and swagger is showing. It will then update you services so you can call them in your code.
[ "stackoverflow", "0046003522.txt" ]
Q: how can I make a ASCII string in Python3 or 2.7 with unicode_literals I cannot use telnet with Python3 or "from future import unicode_literals" I know what the error is, but how to I make an old fashioned (i think ascii) string Thanks A: how to I make an old fashioned (i think ascii) string Use the backported Python 3 syntax: b'some byte string'. However. Never use from __future__ import unicode_literals. This feature was a mistake.
[ "stackoverflow", "0046029859.txt" ]
Q: Summation of products of a variable I have a dataset like this one: test <- data.frame( variable = c("A","A","B","B","C","D","E","E","E","F","F","G"), confidence = c(1,0.6,0.1,0.15,1,0.3,0.4,0.5,0.2,1,0.4,0.9), freq = c(2,2,2,2,1,1,3,3,3,2,2,1), weight = c(2,2,0,0,1,3,5,5,5,0,0,4) ) > test variable confidence freq weight 1 A 1.00 2 2 2 A 0.60 2 2 3 B 0.10 2 0 4 B 0.15 2 0 5 C 1.00 1 1 6 D 0.30 1 3 7 E 0.40 3 5 8 E 0.50 3 5 9 E 0.20 3 5 10 F 1.00 2 0 11 F 0.40 2 0 12 G 0.90 1 4 I want to calculate the sum of the weight by the confidence of each variable, like this: , where i is the variable (A, B, C…) Developing the formula above : w[1]c[1]+w[1]c[2]=2*1+2*0.6=3.2 w[2]c[1]+w[2]c[2] w[3]c[3]+w[3]c[4] w[4]c[3]+w[4]c[4] w[5]c[5] w[6]c[6] w[7]c[7]+w[7]c[8]+w[7]c[9] w[8]c[7]+w[8]c[8]+w[8]c[9] w[9]c[7]+w[9]c[8]+w[9]c[9] … The result should look like this: > test variable confidence freq weight SWC 1 A 1.00 2 2 3.2 2 A 0.60 2 2 3.2 3 B 0.10 2 0 0.0 4 B 0.15 2 0 0.0 5 C 1.00 1 1 1.0 6 D 0.30 1 3 0.9 7 E 0.40 3 5 5.5 8 E 0.50 3 5 5.5 9 E 0.20 3 5 5.5 10 F 1.00 2 0 0.0 11 F 0.40 2 0 0.0 12 G 0.90 1 4 3.6 Note that the confidence value is different for each observation but each variable has the same weight, so the summation I need is the same for each of the same variable observation. First, I tried to make a loop iterating each variable a number of times with: > table(test$variable) A B C D E F G 2 2 1 1 3 2 1 but I couldn't make it work. So then, I calculated the position where each variable start, to try to make the for loop iterate only in these values: > tpos = cumsum(table(test$variable)) > tpos = tpos+1 > tpos A B C D E F G 3 5 6 7 10 12 13 > tpos = shift(tpos, 1) > tpos [1] NA 3 5 6 7 10 12 > tpos[1]=1 > tpos [1] 1 3 5 6 7 10 12 # tpos is a vector with the positions where each variable (A, B, c...) start > tposn = c(1:nrow(test))[-tpos] > tposn [1] 2 4 8 9 11 > c(1:nrow(test))[-tposn] [1] 1 3 5 6 7 10 12 # then i came up with this loop but it doesn't give the correct result for(i in 1:nrow(test)[-tposn]){ a = test$freq[i]-1 test$SWC[i:i+a] = sum(test$weight[i]*test$confidence[i:i+a]) } Maybe there is an easier way to this? tapply? A: By using dplyr: library(dplyr) test %>% group_by(variable) %>% mutate(SWC=sum(confidence*weight)) # A tibble: 12 x 5 # Groups: variable [7] variable confidence freq weight SWC <fctr> <dbl> <dbl> <dbl> <dbl> 1 A 1.00 2 2 3.2 2 A 0.60 2 2 3.2 3 B 0.10 2 0 0.0 4 B 0.15 2 0 0.0 5 C 1.00 1 1 1.0 6 D 0.30 1 3 0.9 7 E 0.40 3 5 5.5 8 E 0.50 3 5 5.5 9 E 0.20 3 5 5.5 10 F 1.00 2 0 0.0 11 F 0.40 2 0 0.0 12 G 0.90 1 4 3.6
[ "stackoverflow", "0058301523.txt" ]
Q: Issues with music player in Unity So I've been working on a music player in Unity. It gets the audioclips from an array within Unity, and a random number generator picks a clip between 0 and the size set in Unity. However, nothing stops it from picking the same number (and thus same song) twice in a row which is something I do not want. I've been trying a few things but ended up with a NullReferenceException. If you'd like to take a look I'd greatly appreciate it! Code: using System.Collections; using UnityEngine; public class MusicPlayer : MonoBehaviour { #region Variables //Variables needed for this code public AudioClip[] clips; private AudioSource audioSource; string currentTitle = ""; #endregion #region Start Void // Start is called before the first frame update void Start() { //Finds AudioSource in the unity editor and turns off the "loop" function. audioSource = FindObjectOfType<AudioSource>(); audioSource.loop = false; } #endregion #region Private AudioClip //The code below will grab a random audio clip between 0 and the amount set in the Unity Editor. private AudioClip GetRandomClip() { return clips[Random.Range(0, clips.Length)]; } #endregion #region Update Void // Update is called once per frame void Update() { if (audioSource.clip.name.Length >= 0) { currentTitle = audioSource.clip.name; } if (!audioSource.isPlaying) { var nextTitle = currentTitle; ulong index = 0; while (nextTitle == currentTitle) { index = (ulong) Random.Range(0, clips.Length); nextTitle = clips[index].name; } audioSource.Play(index); } } #endregion } Went back into my code to prepare it for future stuff as well like calling audio clips from multiple arrays and with the help of both Silleknarf and derHugo I got it worked out. Thank you all so much. Here is the code I ended up with: /* AudioPlayer.cs RTS Game Created by Robin den Ambtman on 17-06-2019 Copyright © Robinblitz. All rights reserved. */ using System.Collections; using UnityEngine; using System.Linq; public class AudioPlayer : MonoBehaviour { #region Variables //Variables needed for this code [Header("Sound arrays")] public AudioClip[] musicClips; [Space(10)] public AudioClip[] announcerClips; [Space(10)] public AudioClip[] TBDClips; [Header("Effect/Music sources")] public AudioSource effectAudioSource; public AudioSource musicAudioSource; #endregion #region Start Void // Start is called before the first frame update void Start() { //Finds AudioSource in the unity editor and turns off the "loop" function. musicAudioSource.loop = false; Random.InitState((int)System.DateTime.Now.Ticks); } #endregion #region Music RNG //The code below will grab a random audio clip between 0 and the amount of clips set in the Unity Editor. private AudioClip GetRandomMusicClip() { // This returns only those clips that are not the currenty played one var filteredClips = musicClips.Where(c => c != musicAudioSource.clip).ToArray(); return filteredClips[Random.Range(0, filteredClips.Length)]; } #endregion #region Update Void // Update is called once per frame void Update() { //If the audio source is playing it will grab the song that's picked out by GetRandomClip() and plays it. if (!musicAudioSource.isPlaying) { var newTitle = GetRandomMusicClip(); musicAudioSource.clip = newTitle; musicAudioSource.Play(); } //Piece of code as a test to play a specific audio clip on key press. if (Input.GetKeyDown(KeyCode.Space)) { effectAudioSource.PlayOneShot(effectAudioSource.clip, 0.7f); } } #endregion } A: As already mentioed in the other answer the parameter of AudioSource.Play(ulong) is delay Deprecated. Delay in number of samples, assuming a 44100Hz sample rate (meaning that Play(44100) will delay the playing by exactly 1 sec). So what you want to do is audioSource.clip = newClip; audioSource.Play(); Then I would rather suggest using Linq Where and filter the unwanted (= currently playing) clip out beforehand without any while-loop like using System.Linq; ... private AudioClip GetRandomClip() { // This returns only those clips that are not the currenty played one var filteredClips = clips.Where(c => c != audioSource.clip).ToArray(); return filteredClips[Random.Range(0, filteredClips.Length)]; } void Update() { if (!audioSource.isPlaying) { var newTitle = GetRandomClip(); audioSource.clip = newTitle; audioSource.Play(); } }
[ "stackoverflow", "0039056873.txt" ]
Q: Access to private properties of a child class I've been trying to understand how class scope affects access to private and protected properties of different objects. And found something strange when i try to access private properties of a child class in the context of its parent. Here is the code example. You can see the very same behavior if you replace methods with properties. class ParentClass{ public function test($childObj){ $childObj->getProtected(); $childObj::getProtected(); $childObj->getPrivate(); $childObj::getPrivate(); } private function getPrivate(){ echo "ParentClass private"; } protected function getProtected(){ echo "ParentClass protected"; } } class ChildClass extends ParentClass{ private function getPrivate(){ echo "ChildClass private"; } protected function getProtected(){ echo "ChildClass protected"; } } (new ParentClass)->test(new ChildClass()); The outputs: ChildClass protected ChildClass protected (and E_DEPRICATED error) ParentClass private Fatal error: Call to private ChildClass::getPrivate() from context 'ParentClass' Well, im fine with the first two outputs. I think it is mentioned somewhere in docs, that in parent context I can access protected methods/properties of a child class. But what about private? Why does it fall back to ParentClass method in 3rd output, and throws an error in 4th? A: That's an interesting question, so I dug into a small research. Actually some of the calls you make behave according to the documentation, but some others are rare in the real life and not documented, so we can treat them as a PHP implementation detail. First, you should not use the :: operator on the non-static methods, as the PHP notification states, this is deprecated behavior. So let's split your test into two separate tests - one for non-static methods and another one for static methods. Here is non-static methods test: class ParentClass{ public function test($childObj){ $childObj->getProtected(); $childObj->getPrivate(); } private function getPrivate(){ echo "ParentClass private"; } protected function getProtected(){ echo "ParentClass protected"; } } class ChildClass extends ParentClass{ private function getPrivate(){ echo "ChildClass private"; } protected function getProtected(){ echo "ChildClass protected"; } } (new ParentClass)->test(new ChildClass()); It outputs: ChildClass protected ParentClass private And here is the relevant part from the php documentation: Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects. In the frist case, $childObj->getProtected(); - it works, as the $childObj is a sub-type of the ParentClass, so it can be treated as an object of the same type. So here we are: Treating the $childObj variable as being of the ParentClass type Calling the getProtected() method This method is protected, so inheritance rules are applied and we call the child class implementation We get the "ChildClass protected" output When we try to do the same thing with the private method, we are still allowed to call $childObj->getPrivate(), but in this case inheritance rules are not applied, as the private members / methods can not be used through the inheritance. So at this point we are: Treating the $childObj variable as being ParentClass type Calling the getPrivate() method Since it is private, inheritance rules are not applied (although, this the language implementation detail, see below) and we call the ParentClass implementation We get the "ParentClass private" output Now, for the static method method we are calling the class-level method, not the instance-level, so no inheritance rules are applicable here. I think, it is clearer if we write the code for the static calls this way (we don't really need the object instance, we only need a class name): class ParentClass{ public static function test() { ChildClass::getProtected(); ChildClass::getPrivate(); } } class ChildClass extends ParentClass{ private static function getPrivate(){ echo "ChildClass private"; } protected static function getProtected(){ echo "ChildClass protected"; } } (new ParentClass)->test(); It outputs: ChildClass protected PHP Fatal error: Uncaught Error: Call to private method ChildClass::getPrivate() from context 'ParentClass' I think, it's obvious here why the second call raises an error - we are just trying to call the private staic method of another class. It's more interesting why the first call, ChildClass::getProtected(), works, as we are also trying to call a protected method of another class and inheritance rules should not apply here. The only explanation I can find is that's just an implementation detail of the language. I think this protected method call shouldn't really work. I also tried to compare this to C++, here is what I get for the first test: #include <iostream> using namespace std; class ParentClass { public: void test(ParentClass* obj); protected: virtual void getProtected(); private: virtual void getPrivate(); }; class ChildClass: public ParentClass{ protected: virtual void getProtected(); private: virtual void getPrivate(); }; //private virtual void ParentClass::getPrivate(){ cout << "ParentClass private"; } //protected virtual void ParentClass::getProtected(){ cout << "ParentClass protected"; } //public void ParentClass::test(ParentClass* obj) { obj->getProtected(); obj->getPrivate(); }; //private virtual void ChildClass::getPrivate(){ cout << "ChildClass private"; } //protected virtual void ChildClass::getProtected(){ cout << "ChildClass protected"; } int main() { cout << "test"; (new ParentClass)->test(new ChildClass); } And it outputs: test ChildClass protected ChildClass private So it works for the private method differently than in PHP and C++ actually calls the child class implementation even for the private method. The second test for static methods: #include <iostream> using namespace std; class ParentClass { public: static void test(); }; class ChildClass: public ParentClass{ protected: static void getProtected(); private: static void getPrivate(); }; //public static void ParentClass::test() { // error: 'static void ChildClass::getProtected()' is protected //ChildClass::getProtected(); // error: 'static void ChildClass::getPrivate()' is private //ChildClass::getPrivate(); }; //private static void ChildClass::getPrivate(){ cout << "ChildClass private"; } //protected static void ChildClass::getProtected(){ cout << "ChildClass protected"; } int main() { cout << "test"; (new ParentClass)->test(); } Both protected and private calls do not work here. You can't even compile a program with these calls. This is I think more logical than in PHP where you can call the protected static method.
[ "stackoverflow", "0012705342.txt" ]
Q: Refreshing a view inside a fragment I have searched the numerous questions that look like this one, but haven't found my answer in any of them. I have an activity that has 3 tabs accessible through the action bar. I achieved this by adding 3 fragments that inflate a custom view I made extending the view class. At the moment the database changes, I try to refresh the view in my tab by calling invalidate()/postinvalidate(), but this does not work. The same is true for calling onCreateView of the fragment just as many other options I considered. When I go to another tab and go back, however, the change has been made and my view is updated as it should be. How can I simulate the same thing that happens when changing to another tab? What does happen. I tried to look at the Fragment lifecycle (tried to call onCreateView()) to figure it out but it just doesn't want to refresh/redraw as it should. The data is loaded properly, as the data is changed when I change to another tab. I deleted some of the code as it is no longer relevant. I implemented Cursorloaders instead of my own Observer pattern to notify a change. This is my main activity right now. The question is what should I do now if I want to redraw the view inside these fragments. If I apply fragmentObject.getView().invalidate() it does not work. I'm having the same problem as before, but now my Observer to notify a change in the database is properly implemented with loaders. public class ArchitectureActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor> { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ActionBar actionbar = getActionBar(); actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.Tab EditTab = actionbar.newTab().setText("Edit"); ActionBar.Tab VisualizeTab = actionbar.newTab().setText("Visualize"); ActionBar.Tab AnalyseTab = actionbar.newTab().setText("Analyse"); Fragment editFragment = new EditFragment(); Fragment visualizeFragment = new VisualizeFragment(); Fragment analyseFragment = new AnalyseFragment(); EditTab.setTabListener(new MyTabsListener(editFragment)); VisualizeTab.setTabListener(new MyTabsListener(visualizeFragment)); AnalyseTab.setTabListener(new MyTabsListener(analyseFragment)); actionbar.addTab(EditTab); actionbar.addTab(VisualizeTab); actionbar.addTab(AnalyseTab); ArchitectureApplication architectureApplication = (ArchitectureApplication)getApplicationContext(); architectureApplication.initialize(); getLoaderManager().initLoader(0, null, this); getLoaderManager().initLoader(1, null, this); } public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (id == 0){ return new CursorLoader(this, GraphProvider.NODE_URI , null, null, null, null); } else if (id == 1){ return new CursorLoader(this, GraphProvider.ARC_URI , null, null, null, null); } return null; } public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Reloading of data, actually happens because when switching to another tab the new data shows up fine Log.e("Data", "loaded"); } public void onLoaderReset(Loader<Cursor> loader) { } } A: Don't try to call onCreateView() yourself... it's a lifecycle method and should be called only by the framework. Fragments are re-usable UI components. They have their own lifecycle, display their own view, and define their own behavior. You usually don't need to have your Activity mess around with the internal workings of a Fragment, as the Fragment's behavior should be self-contained and independent of any particular Activity. That said, I think the best solution is to have each of your Fragments implement the LoaderManager.LoaderCallbacks<D> interface. Each Fragment will initialize a Loader (i.e. a CursorLoader if you are using a ContentProvider backed by an SQLite database), and that Loader will be in charge of (1) loading the data on a background thread, and (2) listening for content changes that are made to the data source, and delivering new data to onLoadFinished() whenever a content change occurs. This solution is better than your current solution because it is entirely event-driven. You only need to refresh the view when data is delivered to onLoadFinished() (as opposed to having to manually check to see if the data source has been changed each time you click on a new tab). If you are lazy and just want a quick solution, you might be able to get away with refreshing the view in your Fragment's onResume() method too. A: I had a similar (although not identical) problem that I could solve in the following way: In the fragment I added public void invalidate() { myView.post(new Runnable() { @Override public void run() { myView.invalidate(); } }); } and I called this method from the activity when I wanted to refresh the view myView of the fragment. The use of post() ensures that the view is only invalidated when it is ready to be drawn. A: I've found a workaround to refresh the view inside my fragment. I recreated (new CustomView) the view every time the database has been updated. After that I call setContentView(CustomView view). It looks more like a hack, but it works and nothing else that I tried does. Although my problem was not actually solved, I gave the reward to Alex Lockwood. His advice on Loaders made my application better and it caused me to keep looking for a solution that I eventually found.
[ "stackoverflow", "0010291507.txt" ]
Q: Problems creating an iterator for my templated doubly linked list I'm creating a doubly linked list implementation of my own for fun and I've finished writing the list itself but now I'm trying to add an iterator to it, but I'm confused about the syntax rules for this stuff. Here is the error I'm getting: error C2990: 'd_list' : non-class template has already been declared as a class template Here's the header file it's all located in: /****************************/ /* d_list class */ /* with exceptions classes */ /****************************/ class d_list_error{}; class d_list_empty{}; template <class T> class d_list_iter; template <class T> class d_list{ public: d_list(); d_list(const d_list &_dl); d_list &operator=(const d_list &_dl); ~d_list(); void push_back(T item); void push_front(T item); void pop_back(); void pop_front(); bool isEmpty() const; unsigned int size() const; void clear(); private: struct node{ node *prev; node *next; T data; }; node *head; node *tail; unsigned int currSize; d_list_iter<T> *dli; /* Utility Functions */ void initFirstEle(T item, node* first); void copyAll(const d_list<T> &_dl); }; /*************************/ /* d_list iterator class */ /*************************/ class d_iter_already_exists {}; template <class T> class d_list_iter{ public: d_list_iter(const d_list &_dl); ~d_list_iter(); T getNext() const; private: friend class d_list; d_list<T> *dl; node *next; node *prev; bool valid; }; Underneath that is all the member functions defined for d_list. I haven't started writing them for the iterator yet. d_list is working perfectly based on all my testing. I imagine I'm just running into syntax errors, as this is sort of uncharted territory for me. A: you must specify the templated type by specifying the template parameters outside the class declaration. specifically, you should write (something like) d_list<T> instead of simply d_list within template <typename> class d_list_iter's declaration. this includes your use of friend. same applies for the nodes. assume they are public for demonstration: typename d_list<T>::node instead of simply node within template <typename> class d_list_iter's declaration.
[ "stackoverflow", "0036456228.txt" ]
Q: Appcelerator::Titanium::Real device:: Imageview is not showing the updated image from remote url In Real devices, Imageview is not showing the updated image from remote url. I have tried in simulator and emulator where there are no issues. Could you please share your comments? Thank you, Jai. A: You can add a unique parameter to url to make sure it is not cached. example imageView.image: "http://www.google.com/profile/image0001.png" + "?t=" + new Date(); Where "http://www.google.com/profile/image0001.png" is your actual url.
[ "english.stackexchange", "0000114109.txt" ]
Q: Origin of “Homeward ho!” In the English translation of an essay by Leon Trotsky that came out in Foreign Affairs, I read [emphasis added]: Now it turns out that the world exchange is the source of all misfortunes and all dangers. Homeward ho! Back to the national hearth! While its meaning is perfectly clear to me (“let’s go home!”), I cannot determine its origin. Has it something to do with a command to a horse? A: It has more to do with boats or ships. OED has ho interjection 2. a. An exclamation to attract attention. b. After the name of a thing or place to which attention is called: used by boatmen, etc., to call attention to the place for which they are starting; hence, generally, with a sense of destination. 1593 G. Peele Famous Chron. King Edward the First sig. Kv, [stage direct.] Make a noise, Westward how. Queene. ‘Woman what noise is this I hear?’ Potters wife. ‘It is the Watermen that cals for passengers to goe Westward now.’ a1616 Shakespeare Twelfth Night (1623) iii. i. 133 Then Westward-hoe: Grace and good disposition attend your Ladyship. Charles Kingsley wrote a novel Westward Ho! in 1855, which was rather popular and spawned a tourist boom to North Devon. So much so that a new village was built by entrepreneurs to service the visitors, which was called Westward Ho!, complete with the exclamation mark. Even though your article was written in 1934, it's possible that the popularity of the previous eighty years hadn't entirely worn off and was still influencing the translator.
[ "stackoverflow", "0015686254.txt" ]
Q: mysql php updating multiple entries through populated drop down menu I'm having an issue trying to update multiple entries in my database via a php populated drop down menu. Here is the code on my page that populates the table showing me all entries currently in my database: $result = mysqli_query($con,"SELECT * FROM Submissions"); echo "<table border='1'> <tr> <th>First name</th> <th>Last name</th> <th>Email</th> <th>Title</th> <th>Text</th> <th>Public Post OK?</th> <th>Date/Time Submitted</th> <th>Approved?</th> <th>Test Approved</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['fname'] . "</td>"; echo "<td>" . $row['lname'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "<td>" . $row['title'] . "</td>"; echo "<td>" . nl2br($row['text']) . "</td>"; echo "<td>" . $row['publicpost'] . "</td>"; echo "<td>" . $row['time'] . "</td>"; echo "<td><select name=\"approved\"><option value=\"" . $row['approved'] . "\">" . $row['approved'] . "</option><option value=\"yes\">Yes</option><option value=\"no\">No Again</option></select></td>"; echo "<td>" . $row['approved'] . "</td>"; echo "</tr>"; } echo "</table>"; ?> <br><br> <form action="update.php" method="post"> <input type="submit" name="SubmitButton" value="Update" class="submit" style="cursor:pointer;"> </form> <?php mysqli_close($con); ?> This is the php code for "update.php": $approved = $_POST['approved']; mysqli_query($con,"UPDATE Submissions SET approved = $approved"); $update_query= "UPDATE Submissions SET approved = '$approved'"; if(mysqli_query($con,$update_query)){ echo "updated";} else { echo "fail";} ?> <form action="approvesubmissions.php"> <input type="submit" value="Approve Submissions page"> </form> The goal is to have the ability to update the field "approved" with a drop down menu from "NO" to "YES" or vice versa. Instead, what is happening with this query, is that it is erasing the data in the "approved" field instead of updating it. I'm somewhat new to php and i have researched a TON on this and have come up with no solutions. Any help is GREATLY appreciated! A: First, let's assume 'approved' is a TINYINT(1) or something. Your select html should be more like this. It will autofill based on the DB value. $selected = 'selected="selected"'; // pre-selection attribute $isApproved = !!$row['approved']; // is this active? (approved is 1 or 0) echo '<select name="approved"> <option value="1" ' . ($isApproved ? $selected : '') . '>Yes</option> <option value="0" ' . (!$isApproved ? $selected : ''). '>No</option> </select>'; Secondly, your form is at the bottom of the table, but your input that you want is in the table. When you submit your form, there is no $_POST['approved'], because that's technically not in a form. To fix, you'll need to put your opening form tag at the top before the table. Then, you'll want to put your submit button and closing form tag at the end, after you've echoed the table out. Thirdly, your post.php page should NOT ever take user input directly into a query. But, simply do this: // Convert input to boolean answer, then int (for the query). $approved = isset($_POST['approved']) ? (int)!!$_POST['approved'] : 0; mysqli_query($con,"UPDATE Submissions SET approved = '$approved'"); While we're on the topic, this would be a great time to jump into prepared statements for your project. It might sound scary, but it can save you from SQL injection. // Make the prepared statement $query = mysqli_prepare("UPDATE Submissions SET approved = ?"); // Safely bind your params mysqli_stmt_bind_param($query, "i", $approved); // Run it mysqli_stmt_execute($query); // "close" the statement (hint: it's reusable for things like bulk updates, etc) mysqli_stmt_close($query);
[ "stackoverflow", "0050173812.txt" ]
Q: Splitting an update operation into chunks, with commits I am running a process acting on a returned list like this MATCH p=(Item{name:'x'})-[r:RELATED_TO]->(w:item) where r.relatedness > 0.25 [PERFORM CALCS AND UPDATE w] The initial MATCH only brings back about 100 nodes, but the perform calcs step is an n^2 operation, with a reasonably large n. Each [PERFORM...] step can be performed independently. The whole thing might take a day to run. I would like to break this up so that it commits after each [PERFORM... ] step. This way in the event of a failure I can start up from where I left off. In SQL server I might store the results of the initial MATCH to a table, and work through it using a CURSOR, marking off completed rows as I went How can I do something analogous in Neo4J? A: As a concept: 1) Save the result of the first query: WITH 'x' as itemName MERGE (T:SavedQueryResult {name: itemName}) WITH itemName, T MATCH (:item {name: itemName})-[r:RELATED_TO]->(w:item) WHERE r.relatedness > 0.25 MERGE (I:SavedID {id: ID(w), processed: false}) MERGE (T)-[:hasResult]->(I) 2) And execute a sequence of queries: WITH 'x' as itemName MATCH (T:SavedQueryResult {name: itemName})-[:hasResult]->(I:SavedID {processed: false}) MATCH (w:item) WHERE ID(w) = I.id [PERFORM CALCS AND UPDATE w] SET I.processed = true 3) To process the saved results, you can use the apoc.periodic.commit from the APOC library.
[ "math.stackexchange", "0001923390.txt" ]
Q: Given that $\iint_R f(x,y) \, dx \, dy=0$, $f(x,y)=0$ for $f$ continuous in $R$ Suppose we are given $\iint_R f(x,y) \, dx \, dy=0$, with $f$ continuous on every region $R$. I need to show that this implies that $f(x,y)=0$. Unfortunately, I don't know how even to start this proof. I vaguely recall proving something like this in the past, and I'm wondering if it has something to do with an Intermediate Value Theorem for integrals or something... In any case, could somebody please tell me how I should proceed in this proof? Detailed solutions are good - hints are also good, if you are willing to tolerate lots of follow-up questions and frustration from me. I just really need to figure this out! Thank you. A: It will suffice to show that if $f$ is zero on an arbitrary region $R$, it is zero everywhere in $\Bbb R^2$. The simplest way is to use proof by contradiction. That is, assume that for some region $R$, $\iint_R f = 0$ and yet there is a point $t \in R$ such that $f(t) = h \ne 0$. Since $f$ is continuous, put $0\lt \epsilon \lt \vert h\vert$. Then there is some $\delta \gt 0$ such that for points $x$ in the ball of radius $\delta$ centered at $t$, written as $B_\delta t$, we have $\vert f(t) - f(x)\vert = \vert h - f(x)\vert \lt \epsilon \lt \vert h\vert$. As a result, we have that for $x \in B_\delta t$, $\vert f(x)\vert \gt 0 \implies f(x) \ne 0$ and the values of $f(x)$ differ from $f(t)$ by less than $\epsilon \gt 0$. Think of the values of $f(x)$ as lying in an open interval $(h - \epsilon, h + \epsilon),$ and notice that if $h$ is negative, the values of $f(x)$ will be negative. If $h$ is positive, the values of $f(x)$ will be positive. In either case, $\iint_{B_\delta t} f \ne 0$, a contradiction of the fact that $\iint_R f = 0$ for each region $R$. The key here was that we used continuity of $f$ to show by contradiction that $f$ has to be zero on $R$.
[ "stackoverflow", "0028214187.txt" ]
Q: How can I deduce template parameters at the end of the list in c++? I'm trying write a function that is templated on three things: First type. Second type. Function with arguments First and Second type. The code looks like this: #include <iostream> #include <typeinfo> using namespace std; // Assume that this function is in a library. Can't be modified. void bar(int x, int y) { cout << x << endl; cout << y << endl; } // My code is below: template <typename Type1, typename Type2, void (*fn)(Type1, Type2)> void foo(Type1 x1, Type2 x2) { fn(x1,x2); } int main() { foo<int, int, &bar>(1,2); } The code works but I'm unhappy that my template has to include <int, int, &bar>. I hoped that the compiler would figure out that bar has int, int as parameters and figure it out. I tried listing the function first and the types second but in the declaration, Type1 wasn't recognized in the function prototype because it is defined later in the same prototype. Is there an elegant solution? Edit: I definitely don't want to pass a pointer to bar on the stack. I want to be templated on bar. The params should be just (1, 2). Edit2: And by that, I mean that I want to write foo<&bar>(1,2). A: This is my solution for not passing the function as a parameter: void bar(int a, int b) { cout << a << " " << b << endl; } template <class F, F *fn> struct Foo { template <class... Args> static decltype(auto) foo(Args &&... args) { return fn(std::forward<Args>(args)...); } }; int main() { Foo<decltype(bar), bar>::foo(1, 2); return 0; } As you can see you have to write bar twice, once for it's type, once for it's value, but I think it is a small inconvenience. Or the simple version (if you can't use c++11) template <class F, F* fn> struct Foo { template <class T1, class T2> static void foo(T1 t1, T2 t2) { fn(t1, t2); } }; For those who don't mind passing the function obj as a parameter: Option 1: template <class T1, class T2> void foo(T1 x1, T2 x2, void (*fn)(T1, T2)) { fn(x1, x2); } foo(1, 2, bar); Option 2: template <class T1, class T2, class F = void(*)(T1, T2)> void foo(T1 x1, T2 x2, F fn)) { fn(x1, x2); } foo(1, 2, bar); Option 3: template <class T1, class T2, class F> void foo(T1 x1, T2 x2, F fn)) { fn(x1, x2); } foo(1, 2, bar); Option 3b (the real deal): template <class T1, class T2, class F> void foo(T1 &&x1, T2 &&x2, F &&fn)) { std::forward<F>(fn)(std::forward(x1), std::forward(x2)); } foo(1, 2, bar); Option 4 (the real real deal) (well.. depends on what you need) template <class F, class... Args> decltype(auto) foo(F &&fn, Args &&... args) { return std::forward<F>(fn)(std::forward<Args>(args)...); }
[ "english.stackexchange", "0000349218.txt" ]
Q: What do you call a child for whom you act as a guardian / custodian? What is the term for this, if there is such a term? For example, if you're a parent, you refer to your offspring as a 'child' and the child refers to you as their 'parent'. I am asking because I need to have a term for the relationship of a guardian to the child. For a child, they can refer to this person as their 'guardian' but the other way around (guardian to child) doesn't seem to have a term. What should I call it? A: I believe the usual term is 'ward'. In law, a ward is someone placed under the protection of a legal guardian. - Wikipedia A: The old-fashioned word was charge - i.e. my charge has now come of age. From OED sense 14. a. A thing or person entrusted to the care or management of any one. spec. The people or district committed to the care of a minister of religion. 1609 Shakespeare Troilus & Cressida v. ii. 7 Dio. How now my charge. Cres. Now my sweet gardian. Edit. Having submitted this answer earlier, I am now persuaded that ward is the better word and have up-voted @Kate Bunting's answer. I no longer think foster son/daughter is correct, since, in the UK anyway, a foster-parent is not the same thing as a guardian. Though one must have regard to the OP's question which refers to guardian/custodian. A foster-parent is more of the nature of a custodian, with day to day control of the child's welfare, but usually under the supervision of a Local Authority, who hold the care order from the Court. It is the Authority who have legal guardianship. A: The legal terms is "ward". Young Dick Grayson was Bruce Wayne's Ward on the Batman series.
[ "stackoverflow", "0033571920.txt" ]
Q: Spring Data Rest / Spring Hateoas Custom Controller - PersistentEntityResourceAssembler I'm attempting to add some additional business logic to the auto-generated endpoints from the RepositoryRestResource. Please see the code below: Resource: @RepositoryRestResource(collectionResourceRel="event", path="event") public interface EventRepository extends PagingAndSortingRepository<Event, Long> { } Controller: @RepositoryRestController @RequestMapping(value = "/event") public class EventController { @Autowired private EventRepository eventRepository; @Autowired private PagedResourcesAssembler<Event> pagedResourcesAssembler; @RequestMapping(method = RequestMethod.GET, value = "") @ResponseBody public PagedResources<PersistentEntityResource> getEvents(Pageable pageable, PersistentEntityResourceAssembler persistentEntityResourceAssembler) { Page<Event> events = eventRepository.findAll(pageable); return pagedResourcesAssembler.toResource(events, persistentEntityResourceAssembler); } } I've looked at the following two stackoverflow articles: Can I make a custom controller mirror the formatting of Spring-Data-Rest / Spring-Hateoas generated classes? Enable HAL serialization in Spring Boot for custom controller method I feel like I am close, but the problem that I am facing is that: return pagedResourcesAssembler.toResource(events, persistentEntityResourceAssembler); returns an error saying: "The method toResource(Page<Event>, Link) in the type PagedResourcesAssembler<Event> is not applicable for the arguments (Page<Event>, PersistentEntityResourceAssembler)". The toResource method has a method signature that accepts a ResourceAssembler, but I'm not sure how to properly implement this and I can't find any documentation on the matter. Thanks in advance, - Brian Edit My issue was that I thought I could override the controller methods that are auto-created from @RepositoryRestResource annotation without having to create my own resource and resource assembler. After creating the resource and resource assembler I was able to add my business logic to the endpoint. Resource: public class EventResource extends ResourceSupport { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } Resource Assembler: @Component public class EventResourceAssembler extends ResourceAssemblerSupport<Event, EventResource> { public EventResourceAssembler() { super(EventController.class, EventResource.class); } @Override public EventResource toResource(Event entity) { EventResource eventResource = createResourceWithId(entity.getId(), entity); eventResource.setName(entity.getName()); return eventResource; } } Updated Controller: @RepositoryRestController @RequestMapping(value = "/event") public class EventController { @Autowired private EventRepository eventRepository; @Autowired private EventResourceAssembler eventResourceAssembler; @Autowired private PagedResourcesAssembler<Event> pageAssembler; @RequestMapping(method = RequestMethod.GET, value = "") @ResponseBody public PagedResources<EventResource> getEvents(Pageable pageable) { Page<Event> events = eventRepository.findAll(pageable); // business logic return pageAssembler.toResource(events, eventResourceAssembler); } } The thing I don't like about this is that it seems to defeat the purpose of having a RepositoryRestResource. The other approach would be to use event handlers that would get called before and/or after the create, save, delete operations. @RepositoryEventHandler(Event.class) public class EventRepositoryEventHandler { @HandleBeforeCreate private void handleEventCreate(Event event) { System.out.println("1"); } } There doesn't seem to be any events for the findAll or findOne operations. Anyways, both these approaches seem to solve my problem of extending the auto generated controller methods from RepositoryRestResource. A: It requires a PagedResourcesAssembler, Spring will inject one for you if you ask. public PagedResources<Foo> get(Pageable page, PagedResourcesAssembler<Foo> assembler) { // ... } In this case the resource is Foo. It seems in your case the resource you're trying to return is an Event. If that's so, I would expect your code to look something like: private ResourceAssembler<Event> eventAssembler = ...; public PagedResources<Event> get(Pageable page, PagedResourcesAssembler<Event> pageAssembler) { Event event = ...; return eventAssembler.toResource(event, pageAssembler); } You provide the ResourceAssembler<Event> that tells Spring how to turn Event into a Resource. Spring injects the PagedResourcesAssembler<Event> into your controller method to handle the pagination links. Combine them by calling toResource and passing in the injected pageAssembler. The final result can be returned simply as a body as above. You could also use things like HttpEntity to gain more control over status codes and headers. Note: The ResourceAssembler you provide can literally be something as simple as wrapping the resource, such as Event, with a Resource object. Generally you'll want to add any relevant links though.
[ "stackoverflow", "0053836806.txt" ]
Q: How can I use IO::Async with an array as input? I have this loop: foreach my $element ( @array ) { my $result = doSomething($element); } Since it doesn't matter that the array is processed in order, and the script runs long, I'd like run doSomething() asynchronously. I am looking at IO::Async for this, but I can't seem to find an example where the input to the loop is a simple array as above. The example seem to focus on open sockets, STDIN, etc. Here is the example given, showing feeding data to the loop via STDIN: $loop->add( IO::Async::Stream->new_for_stdin( on_read => sub { my ( $self, $buffref, $eof ) = @_; while( $$buffref =~ s/^(.*)\n// ) { print "You typed a line $1\n"; } return 0; }, ) ); How can I feed it the array elements instead? A: As commented by @StefanBecker, the simplest way to handle this with IO::Async is by using an IO::Async::Function. From the docs : This subclass of IO::Async::Notifier wraps a function body in a collection of worker processes, to allow it to execute independently of the main process. In the IO::Async framework, the typical use case for IO::Async::Function is when a blocking process needs to be executed asynchronously. Disclaimer : please note that, as commented also by @zdim, IO::Async might not be the best fit for your use case. A pure process parallelizer such as Parallel::ForkManager would probably be your best option here, as it basically implements the same functionality (forking and executing in parallel), yet in a much more straight-forward fashion. One of the main differentiating factor of IO::Async comes with its I/O multiplexing capabilities, that you are seemingly not using here. But since you namely asked for IO::Async, here is an example of such implementation : I turned doSomething into a dummy method that just waits the amount of time given as argument. This allows you to observe the effect of asynchronous execution. use strict; use warnings; use IO::Async::Function; use IO::Async::Loop; use Future; # dummy sub sub doSomething { my ( $delay ) = @_; print "start waiting $delay second(s)\n"; sleep $delay; print "done sleeping $delay second(s)\n"; return $delay; } # prepare the function for execution my $loop = IO::Async::Loop->new; my $function = IO::Async::Function->new( code => sub { return doSomething($_[0]) } ); $loop->add($function); # trigger asynchronous processing my @array = qw/5 2 4 0/; my @futures = map { $function->call( args => [ $_ ] ) } @array; # safely wait for all ops to complete Future->wait_all(@futures)->await; print "all done !\n"; This yields : start waiting 5 second(s) start waiting 2 second(s) start waiting 4 second(s) start waiting 0 second(s) done sleeping 0 second(s) done sleeping 2 second(s) done sleeping 4 second(s) done sleeping 5 second(s) all done ! NB1 : Future->wait_all(@futures)->await could also be written $_->get for @futures, however the first expression, that uses convergent Futures, has the advantages that it will never fail, even if an underlying call actually dies. NB2 : many options are available in IO::Async::Function and Future to handle errors, manage the number of workers and their behavior, and so on. Check out the docs for more details...
[ "stackoverflow", "0020356306.txt" ]
Q: Rollback a single file in git on a remote repository Another developer and I are sharing a repository. The problem is that he's using VS2005 and I'm using VS2013 so to prevent my updates from screwing up his environment, I've made it a point not to commit csproj/sln files. Unfortunately, in my most recent commit/sync, I accidentally pushed the csproj file. There are two versions now: the original commit one and the current one. Is there a way to roll it back to the original commit version without impacting other files? A: You can checkout the desired version of the file with: git checkout <commit-id> -- path/to/file Then commit the changes.