text
stringlengths
14
21.4M
Q: Creating new View in Eclipse I would like to have two views. One for arithmetic series with unique layout and the same for geometric. I would like to have a button in each fragment allowing to change to either arithmetic or geometric. I have two errors: coma after layout inflater inflater is underlined and it reads: Syntax error on token ",", ; expected Bundle is underlined and error is: Syntax error, insert ";" to complete LocalVariableDeclarationStatement public class Sequences_n_series extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View ssView = inflater.inflate(R.layout.fragment_ss, container, false); Button calc = (Button)ssView.findViewById(R.id.aritmetic); //main button calc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_probability, container, false); return rootView; } } }); return ssView; } } A: You can use the Wizard from Eclipse to create a Plug-in and add Views to existing plug-ins. A: You've put a method declaration for onCreateView directly into another method declaration, onClick.
Q: Azure stream analytics anomaly function returning Exception We have an IOT application. Application has to detect any sudden changes(anomaly) in the device battery voltage. We were planing on using anomaly function built into stream analytics in azure for accomplishing this task. When I'm running anomaly function in stream analytics query as follows SELECT ANOMALYDETECTION(BATTERYVOLTAGE) OVER( LIMIT DURATION(hour, 1)) as anomaly FROM [IotTelemetryStream] it is returning the following error message: unexpected error has occurred. Please open a support ticket to investigate and provide the following client request id:_______ But when running the same query after removing anomaly function works fine. SELECT BATTERYVOLTAGE as anomaly FROM [IotTelemetryStream] I cannot find any reference for this issue any where on web so any help would be much appreciated and thanks in advance. A: Can you please send your email address in a direct message to https://twitter.com/azurestreaming ? We will reach out to you with details after that.
Q: Vim copy and paste using the mouse The copy and paste (using the mouse, highlight then right click) doesn't work in my VIM. Is there any option settable in the vimrc file to achieve this behaviour ? Thanks ! A: You need to enable mouse behavior. This can be done using set mouse=a here is the doc
Q: XCode 4 and Titanium: TARGET_BUILD_DIR is incorrectly set Hi there i am just starting with Appcelerator Titanium an run into this problem The Situation I changed the SYMROOT/TARGET_BUILD_DIR in XCode 3 to a global directory. Today i installed XCode4 (and didn't even changed any default property). The Problem I just want to buld the KitchenSink Demo using Titanium 1.2.2. If i build/launch for iOS I get this message [ERROR] Your TARGET_BUILD_DIR is incorrectly set. Most likely you have configured in Xcode a customized build location. Titanium does not currently support this configuration. [ERROR] Expected dir /Users/fabian/Development/Workspaces/2011/titanium/appcelerator-KitchenSink-c17b77f/build/iphone/build/Debug-iphonesimulator, was: /Users/fabian/Development/Workspaces/iphone_experiments/xcode_build/Debug-iphonesimulator XCode4 is still using the old global TARGET_BUILD_DIR. How do I change/delete this? A: I think this was the solution: Delete the TARGET_BUILD_DIR property in username/Library/Preferences/com.apple.dt.Xcode.plist and restart XCode 4
Q: Как передать данные в родительский компонент react-native Столкнулся с проблемой "пинга" при проброске данных наверх (далее скрины) Мой компонент имеет такой путь вызова SetupNotificationsScreen.js->SetupNotificationsField.js->SetupPickDaysComponent.js SetupNotificationsScreen.js: class SetupNotificationsScreen extends React.Component { constructor(props) { super(props); } componentDidMount() { this.props.navigation.setOptions(this.navigationOptions); } state = { currentNotificationSettings: { days: [], time: "13:00", cityId: this.props.route.params.cityId, }, valid: false, }; validation = () => { const data = this.state.currentNotificationSettings; let valid = true; valid = data.days.length !== 0 && valid; valid = data.time !== "" && valid; valid = data.cityId !== null && valid; return valid; }; onPressHandler = (data) => { const valid = this.validation(); this.setState((oldState) => ({ ...oldState, currentNotificationSettings: { ...data }, valid, })); console.log("SetupNotificationsScreen state:"); console.log(this.state); }; onDonePressHandler() {} navigationOptions = { title: "Setup notifications", headerRight: () => ( <TouchableOpacity activeOpacity={APP_THEME.ON_TOUCH_OPACITY_CHANGE} disabled={!this.state.valid} onPress={this.onDonePressHandler} > <Text style={ this.state.valid ? styles.headerText : { ...styles.headerText, ...styles.disabled } } > Done </Text> </TouchableOpacity> ), }; render() { const { cityId } = this.props.route.params; return ( <View style={styles.container}> <View style={styles.wrapper}> <SetupNotificationsField cityId={cityId} onPress={this.onPressHandler} /> </View> </View> ); } } SetupNotificationsField.js export const SetupNotificationsField = ({ cityId, onPress}) => { //TODO: change error with ping const initialState = { days: [], time: "13:00", cityId: cityId, }; const [state, setState] = useState(initialState); const onChangeTimeHandler = (time) => {}; const onChangeDaysHandler = (index) => { if (state.days.find((d) => d === index)) { setState((oldState) => ({ ...oldState, days: state.days.filter((d) => d !== index), })); } else { setState((oldState) => ({ ...oldState, days: [...state.days, index], })); } console.log("SetupNotificationsField state:"); console.log(state); onPress(state); }; return ( <View style={styles.wrapContent}> <Text style={styles.Label}>ENTER TIME</Text> <View style={styles.blockWrapper}> <SetupEnterTimeComponent onPress={onChangeTimeHandler} /> </View> <View style={styles.blockWrapper}> <Text style={styles.Label}>PICK DAY(S)</Text> <SetupPickDaysComponent onPress={onChangeDaysHandler} /> </View> <View style={styles.blockWrapper}> <Text style={styles.Label}>CHOOSE CITY</Text> <SetupChooseCityComponent /> </View> </View> ); }; SetupPickDaysComponent.js export const SetupPickDaysComponent = ({ onPress }) => { let arrDays = { 1: { value: "M", marked: false }, 2: { value: "T", marked: false }, 3: { value: "W", marked: false }, 4: { value: "TH", marked: false }, 5: { value: "F", marked: false }, 6: { value: "SA", marked: false }, 7: { value: "S", marked: false }, }; const [state, setState] = useState(arrDays); const renderDayButtons = (arr) => { console.log("SetupPickDaysComponent state:"); console.log(state); return Object.keys(arr).map((key, index) => { const el = arr[key]; let style = index < 5 ? styles.Button : styles.ButtonWeekends; return ( <TouchableOpacity key={el.value} activeOpacity={APP_THEME.ON_TOUCH_OPACITY_CHANGE} onPress={() => { setState({ ...state, [key]: { ...el, marked: !el.marked } }); onPress(key); }} style={ el.marked ? { ...style, borderWidth: 2 } : { ...style, borderWidth: 0 } } > <Text style={styles.Text}>{el.value}</Text> </TouchableOpacity> ); }); }; return ( <View style={styles.Wrapper}> <View style={styles.WrapperButtons}>{renderDayButtons(state)}</View> </View> ); }; Скрины логов и работы программы: Как видно из логов проброска наверх происходит с пингом в 2 рендера. Как это исправить?
Q: Java SOAP - Product Advertising API - Response Empty I've created a Search-Request to the amazon product API but it's response is empty. Can you give me a hint what's wrong with my code? Code: String awsAccessKeyID = "<AWS-KEY>"; String test = "<ASSOCIATE-TAG>"; AWSECommerceService service = new AWSECommerceService(); service.setHandlerResolver(new AwsHandlerResolver("<SECRET-KEY>")); AWSECommerceServicePortType port = service.getAWSECommerceServicePort(); ItemSearch ItemSearch = new ItemSearch(); ItemSearch.setAWSAccessKeyId(awsAccessKeyID); ItemSearch.setAssociateTag(test); ItemSearchRequest SearchRequest = new ItemSearchRequest(); java.util.List<ItemSearchRequest> list = ItemSearch.getRequest(); list.add(SearchRequest); SearchRequest.setSearchIndex("All"); SearchRequest.setKeywords("nas"); ItemSearch.getRequest().add(SearchRequest); ItemSearch.setMarketplaceDomain("https://ecs.amazonaws.de/onca/xml?Service=AWSECommerceService"); SearchRequest.getResponseGroup().add("Large"); Holder<OperationRequest> operationrequest = new Holder<OperationRequest>(); Holder<java.util.List<Items>> items = new Holder<java.util.List<Items>>(); port.itemSearch(ItemSearch.getMarketplaceDomain(), ItemSearch.getAWSAccessKeyId(), ItemSearch.getAssociateTag(), ItemSearch.getXMLEscaping(), "True", ItemSearch.getShared(), ItemSearch.getRequest(), operationrequest, items); java.util.List<Items> result = items.value; System.out.println(result); The ResultSet is still empty but no errors occured.... A: I found the mistake I made. I created the sources without the binding-conditions for JAXB required by the amazon wsdl. You need an binding.xml file containing the following restriction <jaxws:bindings wsdlLocation="http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl" xmlns:jaxws="http://java.sun.com/xml/ns/jaxws"> <jaxws:enableWrapperStyle>false</jaxws:enableWrapperStyle> </jaxws:bindings> In the pom.xml I created the following part for the build-process <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxws-maven-plugin</artifactId> <version>1.10</version> <executions> <execution> <goals> <goal>wsimport</goal> </goals> <configuration> <wsdlUrls> <wsdlUrl>http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl</wsdlUrl> </wsdlUrls> <sourceDestDir>target/generated-sources/apt</sourceDestDir> <bindingFiles> <bindingFile>../../conf/binding.xml</bindingFile> </bindingFiles> </configuration> <id>wsimport-generate-AWSECommerceService</id> <phase>generate-sources</phase> </execution> </executions> <dependencies> <dependency> <groupId>javax.xml</groupId> <artifactId>webservices-api</artifactId> <version>1.4</version> </dependency> </dependencies> </plugin> After recreation of the sources I changed the request to the following: String awsAccessKeyID = "<AWS-ACCESS-KEY>"; String test = "<ASSOCIATE-TAG>"; AWSECommerceService service = new AWSECommerceService(); service.setHandlerResolver(new AwsHandlerResolver("<SECRET-KEY>")); AWSECommerceServicePortType port = service.getAWSECommerceServicePort(); ItemSearchRequest itemRequest = new ItemSearchRequest(); // Fill in the request object: itemRequest.setSearchIndex("Electronics"); itemRequest.setKeywords("NAS"); itemRequest.getResponseGroup().add("ItemAttributes"); itemRequest.setItemPage(BigInteger.valueOf(1L)); ItemSearch ItemElement = new ItemSearch(); ItemElement.setAWSAccessKeyId(awsAccessKeyID); ItemElement.setAssociateTag(test); ItemElement.getRequest().add(itemRequest); ItemSearchResponse response = port.itemSearch(ItemElement); for (Items itemList : response.getItems()) { for (Item itemObj : itemList.getItem()) { System.out.println(itemObj.getItemAttributes().getBrand()); System.out.println(itemObj.getItemAttributes().getEAN()); } }
Q: eclipse cdt relative path to (resource) file Eclipse CDT (Juno), Windows 7 (x64), OpenCV 2.4.5 File: haarcascade_frontalface_alt.xml is placed in eclipse project directory (where cpp code is). This piece of code string face_cascade_name = "../haarcascade_frontalface_alt.xml"; when build, if executed from cmd or double clicked from file explorer will execute properly. But it won't execute if started from eclipse (Run). If and absolute path is given, such as: string face_cascade_name = "C:/Users/Nenad/eclipseCDT/PanonIT/Segmentation01e/haarcascade_frontalface_alt.xml"; Then project can be executed from eclipse (and from CMD and double explorer as well). How should I setup relative path to allow execution from eclipse?
Q: How to define a polyvariadic arrow? This question is somewhat related to this earlier one: I am trying to define a couple of semi-dependent types, which allow you to track the 'monotonicity' of functions (as described in the Monotonicity Types paper), so that the programmer does not have to do this manually (and fail at compile-time when a non-monotonic operation is passed to something that requires one). More generally: I'd like to keep track of some 'qualifiers' of a function Based on answers to this earlier question, I have been able to define an 'indexed category' and 'indexed arrow' where the qualifiers of h in h = f >>> g depend on the qualifiers of f and g. This works well, as long as you only work with single-argument functions. However, (and normal arrows also have this problem), when you try to create an arrow with multiple arguments, you have the following options. (Using (+) :: Int -> Int -> Int as example): * *Plain arr (+). The result type of this will be Arrow x => x Int (Int -> Int), since the function is curried. This means that only the first parameter is lifted into the arrow context, since the arrow 'returns a function with one parameter less'. In other words: The arrow context is not used for the rest of the arguments, so that's not what we want. *arr (uncurry (+)). The result type of this will be Arrow x => x (Int, Int) Int. Now both parameters have become part of the arrow, but we lose the ability to e.g. partially apply it. It also is not clear to me how to do uncurrying in an arity-independent way: What if we want three, four, five, ...-parameter functions? I know it is possible to define a 'recursive typeclass' to create a polyvariadic function, such as for instance described on Rosettacode here. I have tried to define a more general function-wrapping type that might work that way, but I have not managed to do so far. I have no idea how to properly discern in the typeclass instance for a -> b whether b is the final result or another function (b' -> c), and how to extract and use the qualifier of b' if it turns out to be the second case. Is this possible? Am I missing something here? Or am I completely on the wrong track and is there another way to lift an n-argument function into an arrow, regardless of the value of n? A: Here's how you can define arrowfy to turn a function a -> b -> ... into an arrow a `r` b `r` ... (where r :: Type -> Type -> Type is your arrow type), and a function uncurry_ to turn a function into one with a single tuple argument (a, (b, ...)) -> z (which can then be lifted to an arbitrary arrow with arr :: (u -> v) -> r u v). {-# LANGUAGE AllowAmbiguousTypes, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, UndecidableInstances, TypeApplications #-} import Control.Category hiding ((.), id) import Control.Arrow import Data.Kind (Type) Both approaches use a multiparameter type class with overlapping instances. One instance for functions, which will be selected as long as the initial type is a function type, and one instance for the base case, which will be selected as soon as it's not a function type. -- Turn (a -> (b -> (c -> ...))) into (a `r` (b `r` (c `r` ...))) class Arrowfy (r :: Type -> Type -> Type) x y where arrowfy :: x -> y instance {-# OVERLAPPING #-} (Arrow r, Arrowfy r b z, y ~ r a z) => Arrowfy r (a -> b) y where arrowfy f = arr (arrowfy @r @b @z . f) instance (x ~ y) => Arrowfy r x y where arrowfy = id Side note about arrowfy @r @b @z syntax This is TypeApplications syntax, available since GHC 8.0. The type of arrowfy is: arrowfy :: forall r x y. Arrowfy r x y => x -> y The problem is that r is ambiguous: in an expression, the context can only determine x and y, and this doesn't necessarily restrict r. The @r annotation allows us to explicitly specialize arrowfy. Note that the type arguments of arrowfy must occur in a fixed order: arrowfy :: forall r x y. ... arrowfy @r1 @b @z -- r = r1, x = b, y = z (GHC user guide on TypeApplications) Now, for example, if you have an arrow (:->), you can write this to turn it into an arrow: test :: Int :-> (Int :-> Int) test = arrowfy (+) For uncurry_, there is a small additional trick so that n-argument functions are turned into functions on n-tuple, rather than (n+1)-tuples capped by a unit which you would get naively. Both instances are now indexed by function types, and what is actually being tested is whether the result type is a function. -- Turn (a -> (b -> (c -> ... (... -> z) ...))) into ((a, (b, (c, ...))) -> z) class Uncurry x y z where uncurry_ :: x -> y -> z instance {-# OVERLAPPING #-} (Uncurry (b -> c) yb z, y ~ (a, yb)) => Uncurry (a -> b -> c) y z where uncurry_ f (a, yb) = uncurry_ (f a) yb instance (a ~ y, b ~ z) => Uncurry (a -> b) y z where uncurry_ = id Some examples: testUncurry :: (Int, Int) -> Int testUncurry = uncurry_ (+) -- combined with arr testUncurry2 :: (Int, (Int, (Int, Int))) :-> Int testUncurry2 = arr (uncurry_ (\a b c d -> a + b + c + d)) Full gist: https://gist.github.com/Lysxia/c754f2fd6a514d66559b92469e373352
Q: OpenGL ES stencil operations In reference to the problem diskussed in article OpenGL clipping a new question arises. I am implementing the clipping for a node based 2D scene graph. Whenever the clipping boxes are axis aligned I am using the glScissor like proposed in OpenGL clipping. I have sucessfully implemented node clipping of boxes that are axis aligned. It turns out that each node has to intersect it's clipping rectangle with the ones of it's ancestors that use clipping. (That is necessary in case of siblings that are overlapping with the clipping box of an ancestor). The mechanism of intersecting non axis aligned rectangles has to be implemented using the stencil buffer. I started implementing the proposed solution in OpenGL clipping but am having problems with chidrens having clip rects overlaping with theyr ancestors ones. Right now stencil clipping works perfect with only one clipping box. But in case of a child or grand child that intersects with an ancestor the algorith fails, because the intersection of the 2 involved rectangles would be needed here (like in the axis aligned version) as mask and not the full rectangle of the child. I have thought out the following algorithm: The topmost node writes starts with a counter value of 1 and draws it's clipping rectangle filled with 1s into the stencil buffer and renders it's children stencil-testing against 1. Each sibling that also has clipping turned on draws it's bounding rectangle by adding 1 to the stencil buffer and then testing against 2 and so on. Now when a siblings clipping rect overlaps with an ancestors one,the region where they overlap will be filled with 2s, giving perfect clipping when testing against 2. This algorithm can be extended to a maximum of 255 nested clipping nodes. Here comes my questions: How do I perform rendering to the stencil buffer in a way that instead of 1s being writing,1s are added to the current stencil buffer value, whenever rendering is performed. This is my code I use to prepare for rendering to the stencil buffer: glEnable(GL_STENCIL_TEST); glStencilFunc(GL_ALWAYS, ref, mask); glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); I am looking for a setup that will increase the stencil buffers current value by the value of ref instead of writing ref into the buffer. Can someone help me out? A: glStencilFunc(GL_ALWAYS, ref, mask); says that: * *the first argument says that the stencil comparison test always succeeds *the second and third are hence ignored, but in principle would set a constant to compare the value coming from the stencil buffer to and which of the bits are used for comparison glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); has the effect that: * *when the stencil test fails, the new value replaces the old (per the first argument) *when the depth test fails but the stencil test passes, the new value replaces the old (per the second argument) *when the stencil and depth test both pass, the new value replaces the old (per the third argument) So you're setting things up so that everything you try to draw will pass the stencil test, and in any case its value will be copied into the stencil buffer whether it passes the test or not. Probably what you want to do is to change your arguments to glStencilOp so that you perform a GL_INCR on pixels that pass. So in your stencil buffer you'll end up with a '1' anywhere touched by a single polygon, a '2' anywhere that you drew two successive polygons, a '3' anywhere you drew 3, etc. When drawing the user-visible stuff you can then use something like glStencilFunc set to GL_GEQUAL and to compare incoming values to '1', '2', '3' or whatever. If you prefer not to keep track of how many levels deep you are, supposing you have one clip area drawn into the stencil, you can modify it to the next clip area by: * *drawing all new geometry with GL_INCR; this'll result in a stencil buffer where all pixels that were in both areas have a value of '2' and all pixels that were in only one area have a value of '1' *draw a full screen polygon, to pass only with stencil fund GL_GREATER and reference value 0, with GL_DECR. Result is '0' everywhere that was never painted or was painted only once, '1' everywhere that was painted twice.
Q: How to init DB connection for ewery member of multiprocessing Pool? I use multiporcessing.Pool class for submitting tasks to workers, I want to each worker, when starts (or gets replaced thanks to maxtasksperchild parameter) to open its own DB connection. now code looks similar to this: conn = None def init(dsn): global conn conn = connect(dsn) def f(x): global conn <do the work with conn> p = multiprocessing.Pool(initializer=init, initargs=('dsn',), maxtasksperchild=100) p.map(f, ....) this works, but that global keyword looks extremely ugly, can it be done more gently? A: After a while with this problem... Simple answer is, you can't do this kind of things with current implementation of Pool
Q: How to find the location of an object with respect to another object in an image? We are doing a project in which we are detecting (using YOLOv4) runway debris using a fixed camera mounted at a pole on the side of the runway. We want to find out the position of the object with respect to the runway surface. How can we find out the distance of the object from the runway sides? A: I would recommend using reliable sensors such as "light curtains" to make sure there is no debris on a runway. AI can fail, especially if things are hard to see. As for mapping image coordinates to world coordinates on a plane, look into "homography". OpenCV has getPerspectiveTransform. it's easiest if you pick a big rectangle of known dimensions in your scene (runway), mark the corners, find them in your picture, note those points too, and those four pairs you give to getPerspectiveTransform. now you have a homography matrix that will transform coordinates back and forth (you can invert it). check out the tutorials section in OpenCV's documentation for more on homographies.
Q: Bash Script will not recognize function I'm trying to create a bash script that will allow you to specify an AWS account that you want to perform some actions in. I have a variable I need to pass that refers to a file that the script will cycle through. But the function that performs the actions isn't recognized by the script. This is the error I get : ./delete_snapshots.sh What AWS Account: 12345678910 Delete Snapshots in account: AWS Lab ./delete_snapshots.sh: line 14: delete_snapshots: command not found This is the script : #!/bin/bash echo "What AWS Account: "; read accountnumber declare -a arr=("12345678910" "109876543212") for i in "${arr[@]}" do if [ "$i" -eq 12345678910 ]; then aws_account="AWS Lab" aws_key="lab" aws_file="aws_lab_snapshots.txt" echo "Delete Snapshots in account: $aws_account" delete_snapshots break elif [ "$i" -eq 109876543212 ]; then aws_account="AWS Billing" aws_key="bill" aws_file="aws_bill_snapshots.txt" echo "You are currently in account: $aws_account" delete_snapshots break else echo "Unkown account" fi done delete_snapshots(){ for i in $(cat $aws_file) do echo "*****************************************************************" echo "deleting snapshot: $i" aws ec2 delete-snapshot --snapshot-id=$i --profile=lab 2>&1 | sed -e 's/^An error occurred.*when calling the DeleteSnapshot operation: //' echo "*****************************************************************" echo; echo; echo; echo; echo sleep 5 echo "*****************************************************************" echo "Verify that snapshot: $i is gone:" aws ec2 describe-snapshots --snapshot-ids=$i --profile=lab 2>&1 | sed -e 's/^An error occurred.*when calling the DescribeSnapshots operation: //g' echo "*****************************************************************" echo; echo; echo; echo; echo done } The script works now thanks for some helpful suggestions. Here's the working form of the script: #!/bin/bash delete_snapshots(){ for i in $(cat $aws_file) do echo "*****************************************************************" echo "deleting snapshot: $i" aws ec2 delete-snapshot --snapshot-id=$i --profile=$aws_key 2>&1 | sed -e 's/^An error occurred.*when calling the DeleteSnapshot operation: //' echo "*****************************************************************" echo; echo; echo; echo; echo sleep 5 echo "*****************************************************************" echo "Verify that snapshot: $i is gone:" aws ec2 describe-snapshots --snapshot-ids=$i --profile=$aws_key 2>&1 | sed -e 's/^An error occurred.*when calling the DescribeSnapshots operation: //g' echo "*****************************************************************" echo; echo; echo; echo; echo done } echo "What AWS Account: "; read accountnumber declare -a arr=("123456789101" "109876543212") for i in "${arr[@]}" do if [ "$i" -eq 123456789101 ]; then aws_account="AWS Lab" aws_key="lab" aws_file="source_files/aws_lab_snapshots.txt" echo "Delete Snapshots in account: $aws_account" delete_snapshots break elif [ "$i" -eq 109876543212 ]; then aws_account="AWS Billing" aws_key="bill" aws_file="source_files/aws_bill_snapshots.txt" echo "You are currently in account: $aws_account" delete_snapshots break else echo "Unkown account" fi done
Q: URL localization in Lenya I am trying to localize Lenya publication URLs. I store URL translation in the Document metadata and rewrite urls with URLRewriter transformator. e.g. I build /lenya/default/authoring/en/home from /lenya/default/authoring/index.html But I can't find a simple way to force Lenya to tranlate incoming request URI back to the original path: /lenya/default/authoring/index.html Really I want to process the request via pipelines using the original URL, not translated. Is it possible at all? I had tried to add a servlet filter and use dispatcher, but filter can't access documents metadata because Environment object isn't in the processing stack yet at this stage... (At this moment I see only one way - to update CocoonServlet and Cocoon classes) Thanks! A: I was able to do this via a RequestListener. In the public void onRequestStart(Environment environment) method I create RequestWrapper with a new real URL and put it into objectModel. Also I change Environment context with a real URL: env.setContext("", realUrl, env.getContext()) This works fine!
Q: Windows IP to IP proxy I'm trying to make a proxy (in python) that would capture request from an app, print them and then send the request to the original destination. I've got the python part ready, but I ran into an issue. The app I want to proxy connects directly via IP address (so hosts file doesn't help me for redirecting it to my proxy), I found I solution using netsh int ip add addr 1 IP/32 st=ac sk=tr. The problem is, this will also redirect traffic from my python proxy, thus making it impossible to deliver the request to the original destination. What I need is a solution that would allow me to only redirect traffic from a single app or somehow bypass the netsh rule in the proxy. What can I do to achieve that? Edit: One solution which came to my mind is using another device to host the proxy, that way it would still have the correct route to the original destination, but this is not ideal.
Q: Return the value of each element in a form using javascript Is there a way to do this only using javascript? thank you! A: Basic JavaScript... var arr = document.forms[0].elements; for (var i = 0; i < arr.length; i++) { var el = arr[i]; // do something with it. console.log(el.value) // or similar } A: You might take a look at jQuery.serialize() It gives back a standard URL-encoded string. However the nice thing is that it encapsulates getting the values of all of the different types of form elements. A: Have a look at this. These guys built something that only uses pure JS and serializes a form. A: This function returns all form elements as in an associative array. It also returns all values for multiple input elements that are selected. function getFormVals(form) { var values = []; for(var i = 0, len = form.elements.length; i < len; i++) { var input = form.elements[i]; switch (input.type.toLowerCase()) { case "checkbox": values[input.name] = values[input.name] || []; if (input.checked) { values[input.name].push(input.value); } break; case "radio": values[input.name] = values[input.name] || ""; if (input.checked) { values[input.name] = input.value; } break; case "select-multiple": values[input.name] = values[input.name] || []; for (var i = 0, len = input.length; i < len; i++) { if (input[i].selected) { values[input.name].push(input[i].value); } } break; default: values[input.name] = input.value; break; } } return values; } usage could be: <form onsubmit="var vals = getFormVals(this); alert(vals['myinput']);" > <input type="checkbox" name="myinput" value="ckbx1" /> <input type="checkbox" name="myinput" value="ckbx2" /> <input type="submit" /> </form>
Q: What is the best way to encourage communication in a team? I work in a medium sized team (20+ developers) where I believe communication amongst team members is not as good as it could be. Like most teams, I suppose, we have several systems that we build and maintain. We also use dozens of varied tools in our work such as Visual Studio 2008, Subversion, Resharper, Tibco, TeamCity etc. We also develop using an "Agile" methodology...and I put that in quotes since it seems more like "Rush to get this feature in asap...we'll have the spec for you in about a week...just start working on it now but be sure to unit test it and have it code reviewed by someone". Because of this, we have systems that are poorly designed and thus become difficult to maintain....so we end up with a handful of people as "gurus" who are intimately familiar with the systems they created. Additionally, because of the pace of the IT industry in general we are often required to use new technologies and the latest versions of the tools we develop in. My point is not to complain and say "oh woe is me things are difficult"....rather my concern is that unless our team starts communicating better we're going to stay stuck in this rut. Let me try to explain what I mean by communicating a little better.... Recently we just upgraded from VS2005 to VS2008...which is awesome in my eyes cause I like working with the latest technology. And we also moved from CruiseControl.Net to TeamCity...which is all well and good. ...but....we never really got any training on VS2008 or the new features of C# 3.0...and not even a memo about TeamCity... As IT people we seem to be expected to adapt and learn as we go. Now obviously I can find that info out myself by reading blogs and following the latest news about the tools I use...which I do....but the practice of continuous learning isn't really practiced by everyone on the team so you end up with people using new features without really understanding them... Additionally, our team has recently been instructed to start conducting code reviews...but without any guidance as to what that really means....at the moment it just means give your code to someone..anyone...on the team and have them look at your code...whether for two seconds or two hours its not really well established or uniform across the team....if they are even being done at all... The same is true for writing Unit Tests...we've been encouraged to write them...but its not really been communicated team wide what the best way to write them is...so some developers try to write them, find it difficult, and either write poor unit tests or give up and decide unit testing is a bad idea... The idea I've come up with to help improve the situation is to organize a series of meetings as a Developer's Forum...in these meetings a different topic would be presented by a team member with the remaining time being devoted to discussion amongst the developers. One week the topic might be an advanced new feature of C# and the recommended best practices around it....and the next might be about Code Reviews and what to look for...while the next could be an introduction to an obscure legacy system.....the discussions could then be used by the developers to share their experiences and problems. Ultimately the aim would be to have a place where ideas and information can be freely shared amongst the developers. I have got the buy-in from my managers and several of my fellow developers to get something going...but I have been told that such an idea has been tried before and eventually died out. I want this idea to succeed and not be something that I'll push all by myself only to have it die when I eventually move on from this company. How then can I encourage my team to communicate better? Does my idea of a developer's forum sound like a good idea? What can I do to prevent it from dieing out? Is there something better that I can do instead that I'm not thinking about? More than just starting a series of meetings....How do I encourage and influence my team to start performing as a team? I really enjoy my job and believe I'm working with an excellent group of developers...but I also really want to add value to the team in an area that I see is a bit lacking at the moment. How do I do this effectively? A: Team spirit is hard to force. Most attempts to get people to work together better backfire. It needs to be nurtured and grown. Rather than a series of meetings, how about a team lunch (on the company) once a month or so. Something informal which won't impinge on none work time. Nothing formal but a chance for people to talk to one another and 'bond'. If people are able to, a few drinks or a game of cards in the evening can help. It is important that it is voluntary and non formal. Pair programming can help transfer knowledge, and help people to know and understand each other, so may be worth thinking about. However the management style at your company seems to work against things. "Rush to get this feature in asap...we'll have the spec for you in about a week...just start working on it now but be sure to unit test it and have it code reviewed by someone". This leaves things very much up in the air. Someone has read about things that dev teams should do but is not willing to put the time (aka money) into doing things properly. This will leave developers disenfranchised and de motivated, which harms a team. A: Its hard to give a definitive answer.. apart from trying out somethings and hope that some of them stick Avoid local islands of knowledge - PairProgramming might work. If A signs up for a Task in an area where X has some expertise or clock-time, he could ask X to pair with him. The process of implementing the task spreads things in X's head, is a real-time code review and helps raise average team skill/expertise/code familiarity. It also encourages people to talk to each other instead of holing up.. Dynamic pace of tech evolution - Fact of Life... need to get used to it. Using Developer Forums, Lunchbox forums, Brown Bag Sessions, Wikis, Book Clubs, Online forums, etc could work. Depends on what the individuals in your team pick as their preferred means of ingestion. Work on feedback... if the team feels that they are benefiting from the developer forums, they will sustain it. If it dies out, think about why it didn't stick.. try something else with lessons learned.. Slack - an often missed aspect. Ensure that people have time to help someone out.. not perenially running behind a deadline. Create an environment that encourages and facilitates people speaking out.. helping out others.. and then leave it to the individuals to gel together. Good Luck. A: It sounds to me like your team is missing a technical lead. This person would take guidance from management, and convert it into practical steps that the rest of the team can use. For example: * *You mention you use numerous products in your team, and sometimes update these with no notes or training being given to the team. The technical lead would document the products and how to use them, ideally on a wiki, so others can contribute, and would have experience in the new product, so they can help anyone as and when they need to. The technical lead would also provide guidance, be it an email, document, wiki article etc, on how to use the new product. *This person would produce guidance on how to do code reviews, after meeting with management, senior developers etc. *For any new developments, or major feature requests the technical lead would be involved with designing it, thus a peer review would take place, and knowledge would be spread amongst the team. The key to all of this, is making everyone's job easier, and more productive. It's probably quite clear who this person is, as they'll be the most respected member, who everyone goes when they hit a wall. That person needs to be given some time to perform this role. Unfortunately if that isn't you, then you probably won't have much luck in convincing people to change the way they work. In addition it helps enormously to have a informal lunch once a month, football, or whatever where team members can bond informally. A: Perhaps your concern is less about communication and more about the motivation of your team-mates. In an intellectual field like programming, motivation must come from within the practitioner. Without that, it's hard to get too far. If that's the case, you need to move on to another place. A: The first thing is to break down all physical walls by moving the team to the same location, prefable seating everyone in the same room. Second, start using release planning meetings. That is, your team in concert with the customer, estimates each story that needs to be developed for the coming release. I will improve communication between team members because they are discussion technical issues and problem solving together. They are estimating and, if done correctly, leads to consensus regarding estimates and design approach. Follow up the release planning with kicking of each iteration (one-week iteration is best) with an iteration planning meeting. This is where the team breaks down each story into a number of small tasks scheduled for implementation this iteration. Third, start using pair programming. Dont force it, but encourage it strongly. Also, make sure that pairs are only pairing for a day or so. Ie rotate pairs. This builds collective code ownership and team spirit since it is "our code" not "his code". Oh, and finally: Learn to always talk about "us" and the "team". Never point fingers. A: How can you encourage your colleagues to communicate better? Lead by example. In my company we often you the term 'to drive something'. Somebody needs to drive a project, needs to drive the testing etc. That means to take on the responsibility for this task and persue it actively. Do not just expect your colleagues to share information, show them what to do and how to do it. When you find out some nice new detail about VS2008, share it with them. But be professional about it. Do not just tell it to the two guys you are having a coffee with later today, prepare a small presentation or word document describing your findings and communicate it to all team members. I definitely would prefer to give a short presentation instead of just sending them an email, but that may not be possible. You can fit this in to regular informatione exchange meetings, but I think it is vital that you keep the same attitude in your day to day work. Don't just do it, live it. (Oh my, I sound like one of those stupidly overpayed motivation coaches! Well, maybe they are right and deserve all the money ;-) A: * *Colocate. Everybody in the same room encourages self-organization (via overheard conversation. You will have to factor the disturbance into your estimates however. *Ban Instant Messaging/IRC for anything but the smallest thing. Or all together. You're not going to be popular (I don't like it either), but it will force people to start communicating in the open, and breaking up cliques. *Have regular, quick, focussed, technical meetings. The daily standup is a good example of this. A: There will always be people who will share your passion and join you. There will also always be developers who are the 9 to 5'ers. Nothing can be done about it. If you have managment buy in, then run with it. Management buy in is what I would have figured to be the hardest. Hopefully as other come on board with you, the rest will fall into line. Good luck!
Q: an answer of a test data is different from my answer on my code Here is the problem, http://judgegirl.csie.org/problem/0/202. When I scan a test data: -2 1 3 3 -1 3 7 The answer is: 1 19 30 But my answer on my code is: 1 -19 30 Moreover, I add the condition of the absolute value, but in vain. #include <stdio.h> #include <stdlib.h> int gcd(int,int); main () { int a,b,c,d,e,f,g,h, i,j,x,y,z,GCD,abs; scanf ("%d\n", &a); scanf ("%d\n", &b); scanf ("%d\n", &c); scanf ("%d\n", &d); scanf ("%d\n", &e); scanf ("%d\n", &f); scanf ("%d\n", &g); if ((a != 0 )&&(e!=0)&&(a>=-100)&&(a<=100)&&(e>=-100)&&(e<=100)&&(b>=0)&&(f>=0)&&(b<=100)&&(f<=100)&&(c>0)&&(g>0)&&(c<=100)&&(g<=100)){ switch ( d ){ case 0 : if (a>0 && e>0){ x = a + e +(b*g + f*c)/(c*g); y = (b*g + f*c)%(c*g); z = c*g ; break ; } if (a>0 && e<0){ x = a + e +(b*g - f*c)/(c*g); y = (b*g - f*c)%(c*g); z = c*g ; break ; } if (a<0 && e>0){ x = a + e +((-b)*g + f*c )/(c*g); y = ((-b)*g + f*c)%(c*g); z = c*g ; break ; } if (a<0 && e<0){ x = a + e +((-b)*g - f*c)/(c*g); y = ((-b)*g - f*c)%(c*g); z = c*g ; break ; } case 1 : if (a>0 && e>0){ x = a - e + (b*g - f*c)/(c*g); y = (b*g - f*c)% (c*g); z = c*g; break ; } if (a>0 && e<0){ x = a - e+(b*g + f*c)/(c*g) ; y = (b*g + f*c )%(c*g); z = c*g ; break ; } if (a<0 && e>0){ x = a - e+((-b*g )- f*c)/(c*g) ; y = ((-b)*g - f*c)%(c*g) ; z = c*g ; break ; } if (a<0 && e<0){ x = a - e +((-b)*g + f*c)/(c*g) ; y = ((-b)*g + f*c )%(c*g); z = c*g ; break ; } case 2 : if (a>0 && e>0){ x = (c*a + b)*(e*g + f)/(c*g); y = (c*a + b)*(e*g + f)%(c*g); z = c*g; break ; } if (a>0 && e<0){ x = (c*a + b)*(e*g - f)/(c*g); y = (c*a + b)*(e*g - f)%(c*g); z = c*g; break ; } if (a<0 && e>0){ x = (c*a - b)*(e*g + f)/(c*g); y = (c*a - b)*(e*g + f)%(c*g); z = c*g; break ; } if (a<0 && e<0){ x = (c*a - b)*(e*g - f)/(c*g); y = (c*a - b)*(e*g - f)%(c*g); z = c*g; break ; } case 3 : if (a>0 && e>0){ x = ((c*a+b)*g)/(c*(e*g+f)); y = ((c*a+b)*g)%(c*(e*g+f)); z = c*(e*g+f); break ; } if (a>0 && e<0){ x = ((c*a+b)*g)/(c*(e*g-f)); y = ((c*a+b)*g)%(c*(e*g-f)); z = c*(e*g-f); break ; } if (a<0 && e>0){ x = ((c*a-b)*g)/(c*(e*g+f)); y = ((c*a-b)*g)%(c*(e*g+f)); z = c*(e*g+f); break ; } if (a<0 && e<0){ x = ((c*a-b)*g)/(c*(e*g-f)); y = ((c*a-b)*g)%(c*(e*g-f)); z = c*(e*g-f); break ; } } if (y>0){ abs = y; } else { abs = -y; } GCD=gcd(abs,z); abs = abs/GCD; z = z/GCD; printf ("%d\n",x); printf ("%d\n",abs); printf ("%d\n",z); } } int gcd(int abs , int z) { if (!z) return (abs); return gcd(z, abs % z); }
Q: When I tried running my python program, I encountered a Django importing module Error When I tried running a python program on my local machine, I encountered this error: Traceback (most recent call last): File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 50, in get_internal_wsgi_application ) from err django.core.exceptions.ImproperlyConfigured: WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module. There are also similar posts online, and I tried the suggested solution from each post, but none of them could solve my error. Here is the content of my setting.py My python version: Python 3.7.3 My Django verison: 2.2 """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import django_heroku import dj_database_url config = dj_database_url.config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! DEBUG = False # Experimenting here ALLOWED_HOSTS = ["localhost", "https://stormy-stream-43261.herokuapp.com/"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # WSGI_APPLICATION = 'mysite.wsgi.application' # from django.core.exceptions import ImproperlyConfigured # def get_env_variable(var_name): # try: # return os.environ[var_name] # except KeyError: # error_msg = "Set the %s environment variable" % var_name # raise ImproperlyConfigured(error_msg) # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases # one for development (maybe move that to local postgres) and another for running and development DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql', # 'NAME': 'xsboediz', # 'USER': 'xsboediz', # 'PASSWORD': '****************', # 'HOST': 'baasu.db.elephantsql.com', # 'PORT': '5432' # } # # 'default': dj_database_url.config( # default=config('DATABASE_URL') # ) # 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase', } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ #STATIC_URL = './blog/staticfiles/' STATIC_URL = '/static/' # STATICFILES_DIRS = ( # #'/Diversity_Policy_Site/blog/static', # os.path.join(BASE_DIR, '/static/'), # ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' django_heroku.settings(locals()) I have posted a similar post before, but no one is viewing that post anymore, so here I created another post and see if anyone could help. Any help or suggestion is appreciated. A: Ok, I finally found the solution online: first do: pip uninstall whitenoise then do: pip install "whitenoise<4" Also, appreciate everyone who posted suggestion on this post.
Q: What is the right way to redirect in PHP I am trying to make an MVC php framework. I am trying to write testable code. I know exit or die() is not a good solution after header("Location: http://example.com");. That's how I am currently doing redirect: Here is simpler version of my code. <?php // create a RedirectException class class RedirectException extends \Exception {} <?php // it is index.php try { include 'view.php' } catch (RedirectException $e) { header(sprintf("Location: %s", $e->getMessage()); header('HTTP/1.1 302 Found', true, 302); } catch (Exception $exception) { // print exception here or, do something else } <?php // it is view.php $url = 'http://example.com'; throw new RedirectException($url); This flow should works fine when I run index.php It looks to me like, I am doing it right way. The problem is not with response code. The question is, I need to know: Managing redirect with Exception is a good idea? or I should try it in some other way? A: As mentioned, a redirect as an action taken when an exception is throw is not really accurate from a semantic viewpoint. Typically, a redirect is implemented in the layer that deals with providing a response to the client, because the redirect is from a technical perspective actually implemented here as a header (Location). A very rough example of how this would more cleanly work is when a controller in your MVC architecture is able to provide a "response", that as part of its state could signal a redirect, e.g. class SomeController { public function home(Request $request, Response $response) { return $response->redirect('/somewhere'); } } Which in its implementation would simply attach a Location: /somewhere header to the response that your web application provides to the client.
Q: Gauss-Bonnet correction to Carnot's efficiency Could anyone tell explicitly, how did the author get the $T_c$ vs. $\alpha$ plot given in Figure 3 in Gauss-Bonnet Black Holes and Holographic Heat Engines Beyond Large N.
Q: Datatable.net data indexOf vs data missmatch I'm trying to find the index of a row that match with a column data value. From the found index I would like to get the corresponding TR element. Here is how I'm doing it : // A table with many people [name, position, office, age, etc...] var table = $('#example').DataTable(); // Finding the row index of the person having 46 year old var pos = table.column(3).data().indexOf("46"); // Getting position 7 (Cara Stevens) console.log(`pos : ${pos}`); // Getting data of the row at index 7 var dt = table.row(pos).data(); // We are getting Rhona Davidson instead of Cara Stevens, what's that ? // Even if I try to get the TR html element by calling table.row(pos).node(), // obviously this will not be the TR having (Cara Stevens) but the one // with (Rhona Davidson) console.log(`dt : ${dt}`); Did I miss something about the Datatable.net and the internal index behavior or there a bg ? Here is the complete working example of the problem, read the console result : https://jsfiddle.net/fzvsvfs2/ Best regards, A: For get the correct row you should use: var dt = table.rows().data()[pos]; because the row(pos), is selecting the row of index pos from the original rows model, but not the display order, you can hava a look using console.log(table.data()). For get the tr, just: table.rows().nodes()[pos]
Q: The following code works in my IDE but fails to work in the online editor provided at hackerrank.com Input Format Every line of input will contain a String followed by an integer. Each String will have a maximum of 10 alphabetic characters, and each integer will be in the inclusive range from 0 to 999. Output Format In each line of output there should be two columns: The first column contains the String and is left justified using exactly 15 characters. The second column contains the integer, expressed in exactly 3 digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes. Sample Input java 100 cpp 65 python 50 Sample Output ================================ java 100 cpp 065 python 050 ================================ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); StringBuilder sb=new StringBuilder(); int x=0,len=0; System.out.println("================================"); for(int i=0;i<3;i++) { boolean bool = true; while(bool){ sb=sb.append(sc.next()); len=sb.toString().length(); if(len>10) { sb.delete(0,len); System.out.println("Enter zero - ten character string"); } else bool = false; } bool= true; while(bool){ x=Integer.parseInt(sc.next()); sc.nextLine(); int l= Integer.toString(x).length(); if(l>3) { System.out.println("Enter zero - three digit number"); } else bool = false; } System.out.printf("%1$-16s %2$03d\n",sb,x); sb=sb.delete(0,len); } System.out.println("================================"); } } A: You printed two extra space characters between each strings and numbers. Try Replacing System.out.printf("%1$-16s %2$03d\n",sb,x); with System.out.printf("%1$-15s%2$03d \n",sb,x); Also you should remove the line sc.nextLine(); to avoid extra reading and causing an exceition.
Q: ResourceAwareScheduler is not found in Storm 2.1.0 I am using Storm 2.1.0 and would like to use the Resource Aware Scheduler. I followed instructions from the documentation and added the following line to my conf/storm.yaml: storm.scheduler: "org.apache.storm.scheduler.resource.ResourceAwareScheduler" But when I execute ./bin/storm nimbus it crashes and I can see the following log in logs/nimbus.log: 2020-06-25 16:02:09.962 o.a.s.d.n.Nimbus main [INFO] Using custom scheduler: "org.apache.storm.scheduler.resource.ResourceAwareScheduler" 2020-06-25 16:02:09.963 o.a.s.u.Utils main [ERROR] Received error in thread main.. terminating server... java.lang.Error: java.lang.RuntimeException: java.lang.ClassNotFoundException: "org.apache.storm.scheduler.resource.ResourceAwareScheduler" at org.apache.storm.utils.Utils.handleUncaughtException(Utils.java:653) ~[storm-client-2.1.0.jar:2.1.0] at org.apache.storm.utils.Utils.handleUncaughtException(Utils.java:632) ~[storm-client-2.1.0.jar:2.1.0] at org.apache.storm.utils.Utils.lambda$createDefaultUncaughtExceptionHandler$2(Utils.java:1014) ~[storm-client-2.1.0.jar:2.1.0] at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1057) [?:1.8.0_252] at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) [?:1.8.0_252] at java.lang.Thread.dispatchUncaughtException(Thread.java:1959) [?:1.8.0_252] Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: "org.apache.storm.scheduler.resource.ResourceAwareScheduler" at org.apache.storm.utils.ReflectionUtils.newInstance(ReflectionUtils.java:48) ~[storm-client-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.makeScheduler(Nimbus.java:658) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.<init>(Nimbus.java:569) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.<init>(Nimbus.java:474) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.<init>(Nimbus.java:468) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.launchServer(Nimbus.java:1307) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.launch(Nimbus.java:1332) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.main(Nimbus.java:1337) ~[storm-server-2.1.0.jar:2.1.0] Caused by: java.lang.ClassNotFoundException: "org.apache.storm.scheduler.resource.ResourceAwareScheduler" at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[?:1.8.0_252] at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[?:1.8.0_252] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352) ~[?:1.8.0_252] at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[?:1.8.0_252] at java.lang.Class.forName0(Native Method) ~[?:1.8.0_252] at java.lang.Class.forName(Class.java:264) ~[?:1.8.0_252] at org.apache.storm.utils.ReflectionUtils.newInstance(ReflectionUtils.java:46) ~[storm-client-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.makeScheduler(Nimbus.java:658) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.<init>(Nimbus.java:569) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.<init>(Nimbus.java:474) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.<init>(Nimbus.java:468) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.launchServer(Nimbus.java:1307) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.launch(Nimbus.java:1332) ~[storm-server-2.1.0.jar:2.1.0] at org.apache.storm.daemon.nimbus.Nimbus.main(Nimbus.java:1337) ~[storm-server-2.1.0.jar:2.1.0] I understand that the class is not found but wasn't expecting this. I just downloaded the latest version of Storm from their official website (binary version), I checked on the source code if the class exists (it does), Zookeeper is up and running, and I followed the given instruction to enable this scheduler. I probably forgot something but I totally don't know what. But anyway, let's continue this investigation. In Nimbus.java it initializes the scheduler: private static IScheduler makeScheduler(Map<String, Object> conf, INimbus inimbus) { String schedClass = (String) conf.get(DaemonConfig.STORM_SCHEDULER); IScheduler scheduler = inimbus == null ? null : inimbus.getForcedScheduler(); if (scheduler != null) { LOG.info("Using forced scheduler from INimbus {} {}", scheduler.getClass(), scheduler); } else if (schedClass != null) { LOG.info("Using custom scheduler: {}", schedClass); scheduler = ReflectionUtils.newInstance(schedClass); } else { LOG.info("Using default scheduler"); scheduler = new DefaultScheduler(); } return scheduler; } The following log tells me that it's trying to get the correct scheduler: ... Nimbus main [INFO] Using custom scheduler: "org.apache.storm.scheduler.resource.ResourceAwareScheduler" An then, it calls ReflectionUtils.newInstance() which is implemented in ReflectionUtils.java: public static <T> T newInstance(String klass) { try { return newInstance((Class<T>) Class.forName(klass)); } catch (Exception e) { throw new RuntimeException(e); } } Exception seems to be raised from here because it is not able to find the class ResourceAwareScheduler. I double checked and the class exist at the given location. At this stage I got to admit that it reaches my knowledge of Java. Am I suppose to manually import this class in ReflectionUtils.java? It has the full path to the class, so I suppose it is not necessary. How should I configure this Maven project to include this class? Any help with this will be gladly appreciated. A: I finally found the problem. There is a difference between: storm.scheduler: "org.apache.storm.scheduler.resource.ResourceAwareScheduler" and storm.scheduler: "org.apache.storm.scheduler.resource.ResourceAwareScheduler" Even the highlighting for code from StackOverflow should have helped me. I feel stupid. It's a gentle reminder that copy-pasting, even from official documentation, is bad! Hope this will help other bros.
Q: Trying to convert a number prefixed with a non-numeric character into the number itself in MIPS I have the following string, "Q123" and would like to convert it to the number 123 in MIPS, but I am not sure how to do so. I have loaded the string into the register t0, li $v0, 8 #read a string into a0 la $a0, input1 la $t0, $a0 syscall But I am not sure how to remove the first character from a string and then save it to one of the t registers in qtSPIM.
Q: Unable to reach callback URL I've been using the Instagram RealTime API for some time now without problems. However, I switched hosting server for my website a couple of days ago, and since then I've been having problems registering subscriptions. To debug the problem I've been using powershell to invoke the POST command to add new subscriptions like this: $postParams = @{callback_url='http://example.com/callback';object='tag';aspect='media';object_id='sometag';client_id='CLIENT_ID';client_secret='CLIENT_SECRET'} Invoke-WebRequest -Uri https://api.instagram.com/v1/subscriptions/ -Method POST -Body $postParams If I invoke that on my developer machine, I get a 200 in response and I see that the subscription is listed if I call: https://api.instagram.com/v1/subscriptions?client_secret=CLIENT_SECRET&client_id=CLIENT_ID However, If I invoke that exact command in powershell on my webserver where my site is hosted I get a 400 with error message 'Unable to reach callback URL "http://example.com/callback"' What could be the source of this problem? I've tried to register a new application, but I got the same error there. At first I thought it had something to do with DNS issues, but since Instagram are able to reach http://example.com/callback when I issue the command from my developer machine, shouldn't they be able to reach that same URL even if my request comes from another server? A: The error Unable to reach callback URL might be misleading. I had the same issue, same command, different IP and in one case it works, in the other it does not. I suspect it is an Instagram issue rejecting subscriptions from some IPs while others not.
Q: Select Material UI, wrong position when i have one item on my list. REACTJS i have that select and menuItem from @material-ui/core. When I only have one item in my list, the position of that item is wrong. How can I raise the position of this item? <Select MenuProps={{ anchorOrigin: { vertical: "bottom", horizontal: "left", }, transformOrigin: { vertical: "top", horizontal: "left", }, getContentAnchorEl: null, }} value={value} onChange={chavearAccordionsSetarParametro} labelId="remedio-label" id="remedio" name="remedio" className={classes.containerSelect} > {list.map((element) => ( <MenuItem value={element.Description} key={element.RemedyId} className={classes.MenuItem} > {element.Description} </MenuItem> ))} </Select>;
Q: How to send HTTP request with authentication basic? I'm using SOCKET (WINSOCK2.H) to connect to IP camera. After connect, I want to send the command "GET /nphMotionJpeg?Resolution=640x480&Quality=Standard HTTP/1.1\r\n\r\n" to get video stream. But this command is not successful because the camera is protected by authentication basic. Now, I want to insert into request command username and password but i don't know the syntax to do it. A: the syntax is explained in the related wikipedia article: https://en.wikipedia.org/wiki/Basic_access_authentication
Q: Could light bounce infinitely? If you were to construct a box with perfect mirrors on all sides, and would emit some photons in to that, would the light bounce infinitely? Sorry of this is a stupid queston, i'm not a physicist ;) A: The answer is if there would be a box like that, even with a photon in it, when the photon interacts with the atoms in the mirror, three things could happen to the photon: * *elastic scattering, the photon keeps its energy and changes angle *inelastic scattering, the photon gives part of its energy to the atom and changes angle *absorption, the atom gives all of its energy to the atom and the valence electron that absorbs it moves to a higher energy level as per QM Now if the photon bounces a lot, all three will happen, and since the absorption too, in that case the photon might be re-emitted or not. If it is re-emitted it might be re-emitted in another direction, outside the box (quantum tunneling). So for your question, it will not bounce forever, either because absorption, or because as per QM, the wavefunction of the photon will describe the photons position in space, and after a while it will be outside the box (quantum tunneling). And as per the comment, you cannot make perfect mirrors, that would just elastically scatter, there will be inelastic scattering and absorption too.
Q: matplotlib get numpy array index location on click I have a numpy array which I plot with plt.imshow(img_right, cmap = plt.cm.gray,picker=True) I then attache an on-pick handler to it win.canvas.mpl_connect('pick_event',onclick) I then click on the image location. My reuirment is to get the array index of the numpy 2-D array which was used to plot the data originally I tried the following the the onpick even handler print dir(event_pick) event=event_pick.mouseevent print dir(temp) I see that none of these contain a ind attribute. How do I get the array index from the clicked location?(I dont need the xydata, I need the closest array index)
Q: Sending cookies using HttpCookieCollection and CookieContainer I want to tunnel through an HTTP request from my server to a remote server, passing through all the cookies. So I create a new HttpWebRequest object and want to set cookies on it. HttpWebRequest.CookieContainer is type System.Net.CookieContainer which holds System.Net.Cookies. On my incoming request object: HttpRequest.Cookies is type System.Web.HttpCookieCollection which holds System.Web.HttpCookies. Basically I want to be able to assign them to each other, but the differing types makes it impossible. Do I have to convert them by copying their values, or is there a better way? A: Here's the code I've used to transfer the cookie objects from the incoming request to the new HttpWebRequest... ("myRequest" is the name of my HttpWebRequest object.) HttpCookieCollection oCookies = Request.Cookies; for ( int j = 0; j < oCookies.Count; j++ ) { HttpCookie oCookie = oCookies.Get( j ); Cookie oC = new Cookie(); // Convert between the System.Net.Cookie to a System.Web.HttpCookie... oC.Domain = myRequest.RequestUri.Host; oC.Expires = oCookie.Expires; oC.Name = oCookie.Name; oC.Path = oCookie.Path; oC.Secure = oCookie.Secure; oC.Value = oCookie.Value; myRequest.CookieContainer.Add( oC ); } A: I had a need to do this today for a SharePoint site which uses Forms Based Authentication (FBA). If you try and call an application page without cloning the cookies and assigning a CookieContainer object then the request will fail. I chose to abstract the job to this handy extension method: public static CookieContainer GetCookieContainer(this System.Web.HttpRequest SourceHttpRequest, System.Net.HttpWebRequest TargetHttpWebRequest) { System.Web.HttpCookieCollection sourceCookies = SourceHttpRequest.Cookies; if (sourceCookies.Count == 0) return null; else { CookieContainer cookieContainer = new CookieContainer(); for (int i = 0; i < sourceCookies.Count; i++) { System.Web.HttpCookie cSource = sourceCookies[i]; Cookie cookieTarget = new Cookie() { Domain = TargetHttpWebRequest.RequestUri.Host, Name = cSource.Name, Path = cSource.Path, Secure = cSource.Secure, Value = cSource.Value }; cookieContainer.Add(cookieTarget); } return cookieContainer; } } You can then just call it from any HttpRequest object with a target HttpWebRequest object as a parameter, for example: HttpWebRequest request; request = (HttpWebRequest)WebRequest.Create(TargetUrl); request.Method = "GET"; request.Credentials = CredentialCache.DefaultCredentials; request.CookieContainer = SourceRequest.GetCookieContainer(request); request.BeginGetResponse(null, null); where TargetUrl is the Url of the page I am after and SourceRequest is the HttpRequest of the page I am on currently, retrieved via Page.Request. A: The suggested from David is the right one. You need to copy. Just simply create function to copy repeatedly. HttpCookie and Cookie object is created to make sure we can differentiate both in its functionality and where it come. HttpCookie used between user and your proxy Cookie is used between your proxy and remote web server. HttpCookie has less functionality since the cookie is originated from you and you know how to handle it. Cookie provide you to manage cookie received from web server. Like CookieContainer, it can be used to manage domain, path and expiry. So user side and web server side is different and to connect it, sure you need to convert it. In your case, it just simply direct assignment. Notice that CookieContainer has a bug on .Add(Cookie) and .GetCookies(uri) method. See the details and fix here: http://dot-net-expertise.blogspot.com/2009/10/cookiecontainer-domain-handling-bug-fix.html CallMeLaNN
Q: Sending image from flash to XML file I am using Asp.net/C# for my project. I have a requirement where the user will K from webcam which is incorporated in my webpage. This is happening well for me. The user is able to click the image from webcam. The issue is now that the user has captured the image , i need to save it. My question is can i save that image from .swf file to an XML file which resides in my project. Is it possible so that i can retrieve it later..I do not want the user to save the image on their machine ....
Q: how long does it take to get an rss feed after content has been published? I recently installed an RSS feed on our company forum. I did some tests and it appears that if I subscribe to a feed it takes at least 45 minutes before I receive the rss for published material. Is this usual? Is there a faster way to receive updates? A: you can configure the time but it always depend in the client to accept it or use a fixed value http://cyber.law.harvard.edu/rss/rss.html#ltttlgtSubelementOfLtchannelgt
Q: What does "they only know their own side of the question" mean? Look at this quote by John Stuart Mill: It is better to be a human being dissatisfied than a pig satisfied; better to be Socrates dissatisfied than a fool satisfied. And if the fool, or the pig, is of a different opinion, it is only because they only know their own side of the question. I have a problem with finding out the meaning of the sentence after because, that is they only know their own side of the question. I know the meaning of each word but I am not sure what it means. How would you paraphrase it? A: It means that that the pig doesn't know what it's like to be human, and a fool doesn't know what it's like to be Socrates. The word "question" might be what's throwing you off. It approximately means "situation" in this context.
Q: WP8.1 C# Binding Contact Image Information Quite simply, I'm attempting to create an app that would display the contacts for a user. I'm also a self-taught programmer, so I have experience with programming in some aspects, but I am relatively new to data-binding in general. To begin, I have a ListView control that has an image binding within it. <ListView x:Name="ContactsView" ItemsSource="{Binding}"> <ListView.ItemTemplate> <DataTemplate> <Image x:Name="ContactImage" Source="{Binding Converter={StaticResource ContactPictureConverter}, Mode=OneWay}" Height="100" Width="100" Margin="0,0,0,0"/> </DataTemplate> </ListView.ItemTemplate> </ListView> I also have a converter that gets an IRandomAccessStream of the Contact Image and returns it as a BitmapImage. If no image is found (null exception), then the converter will return back a default picture for contacts. public class ContactPictureConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string culture) { Contact c = value as Contact; try { return GetImage(c).Result; } catch (Exception ex) { Debug.WriteLine(ex.Message); } return @"Images/default.jpg"; } async Task<BitmapImage> GetImage(Contact con) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.DecodePixelHeight = 100; bitmapImage.DecodePixelWidth = 100; using (IRandomAccessStream fileStream = await con.Thumbnail.OpenReadAsync()) { await bitmapImage.SetSourceAsync(fileStream); } return bitmapImage; } public object ConvertBack(object value, Type targetType, object parameter, string culture) { throw new NotImplementedException(); } } Additional Information The app is set for Windows Phone 8.1 WinRT. To get the contacts, I use a ContactStore. IReadOnlyList<Contact> contacts; //Global Declaration ContactStore store = await ContactManager.RequestStoreAsync(); contacts = await store.FindContactsAsync(); ContactsView.ItemsSource = contacts; Problem Every contact is returning the default contact image (meaning some exception occurred when trying to get the contact image). This shouldn't occur since majority of my contacts have images associated with them. Question How should I get the image of a contact and bind that to an image control within a ListView for Windows Phone 8.1? A: Thanks to Romasz and Murven, I was able to get a solution for my problem. XAML: <ListView x:Name="ContactsView" Grid.Row="1" Background="White" ItemsSource="{Binding}"> <ListView.ItemTemplate> <DataTemplate> <Image x:Name="ContactImage" DataContext="{Binding Converter={StaticResource ContactPictureConverter}}" Source="{Binding Result}" Height="100" Width="100" Margin="0,0,0,0"/> </DataTemplate> </ListView.ItemTemplate> </ListView> Converter: using Nito.AsyncEx; public class ContactPictureConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { try { Contact c = value as Contact; return NotifyTaskCompletion.Create<BitmapImage>(GetImage(c)); } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; } } private async Task<BitmapImage> GetImage(Contact con) { using (var stream = await con.Thumbnail.OpenReadAsync()) { BitmapImage image = new BitmapImage(); image.DecodePixelHeight = 100; image.DecodePixelWidth = 100; image.SetSource(stream); return image; } } public object ConvertBack(object value, Type targetType, object parameter, string culture) { throw new NotImplementedException(); } } Packages: Nito.AsyncEx from Nuget A: public static BitmapImage GetImage(Contact con) { if (con == null || con.Thumbnail == null) { return null; } var bitmapImage = new BitmapImage(); bitmapImage.DecodePixelHeight = 256; bitmapImage.DecodePixelWidth = 256; Action load = async () => { using (IRandomAccessStream fileStream = await con.Thumbnail.OpenReadAsync()) { await bitmapImage.SetSourceAsync(fileStream); } }; load(); return bitmapImage; } A: The problem is that the GetImage method is asynchronous, so you need to wait for the result to complete: Task<BitmapImage> getImageTask = GetImage(c); getImageTask.RunSynchronously(); return getImageTask.Result; A: you can do one thing .. you can retrieve all the images from the contacts class and store them in an array or stack or List of BitmapImages .. (*** i think list would be an better option ) Contact c = value as Contact; foreach(var p in c) { q.Add(p.Thumbnail); } here q is an list of bitmapmages
Q: How can I snap to grid a value between 0 and 1 let's say I have a value that is between 0 and 1. I have a grid size and would like the value to snap to grid. so if grid size is equal to two I would like to switch from 0 to 1 if grid size equal to three this would switch from 0, 0.5 to 1 if it's four 0, 0.33, 0.66, 1 and so on... A: Assuming the language you use has a round function that rounds to the nearest integer, and calling v the value and n the grid size: round(v * (n-1)) / (n-1)
Q: Referrer header not included in stylesheet request inside iframe I'm trying to load in an external font (using the font provider's hosted CSS) from inside a sandboxed iframe. The font provider seems to be authorizing whether the font can load or not based on the contents of the Referrer header. However, when the request is made from inside the iframe, that header is not present (according to Chrome's devtools). Setting referrerpolicy="origin" on the <iframe> element doesn't seem to change anything. Tested in Chrome and Firefox. Do I need to add a special attribute to my <link> tag, too? Is there something else I'm missing?
Q: How to set prefetch count to 1 for amqplib for nodejs How do i set the prefetch count to one for amqplib in nodejs? link to Lib on git The desired result is that the consumer is only taking one message from the queue process it and when done take a new message. I have a setup where some messages takes long time to process and others take very short time. Hence i do not just want to share the messages equally on all consumers. A: I used ch.prefetch(1); after asserting the queue with a task and before binding the queue to an exchange. A: channel.prefetch(1); You can view the docs here for reference
Q: Filter and update embedded Array in mongodb mongoose The MongoDb model looks like this : { "_id": { "$oid": "5ee269c949c9d58970528d1e" }, "parent": [ { "_id": { "$oid": "5ee269c949c9d58970528d1d" }, "uType": "parent", "fName": "p1", "lName": "p1", "num": "123" } ], "child": [ { "_id": { "$oid": "5ee269c949c9d58970528d1c" }, "uType": "child", "fName": "c1", "lName": "c1", "num": "8963", "email": "[email protected]", "gender": "male" } ] } I have an incoming object that looks like this - { "uType":"child", "fName": "c2", "lName": "c2", "num": "98733", "email": "[email protected]", "invite": { "uType": "parent", "fName": "p1", "lName": "p1", "num": "123" } } I have to filter for the incoming object such that I get the response like below- which means for the incoming object, there is a matching parent but there is not a matching child. Tried using $or and provided multiple conditions but every time ended up getting a record in child array. I gave it a shot using aggregate as well but could not find a possible solution. Can someone tell me what is the best way to do this? { "_id": { "$oid": "5ee269c949c9d58970528d1e" }, "parent": [ { "isActive": false, "_id": { "$oid": "5ee269c949c9d58970528d1d" }, "uType": "parent", "fName": "p1", "lName": "p1", "num": "123" } ], "child": [ ] } UPDATE: Tried using projection, but still no luck - Model.aggregate([ { $project: { child: { $filter: { input: "$child", as: "ch", cond: { $eq: ["$ch.num", this.num] } } } } } ]) A: Actually, you are so close to the solution, if you use "$$ch.num" instead of "$ch.num" it should work. const match = { "uType":"child", "fName": "c2", "lName": "c2", "num": "98733", "email": "[email protected]", "invite": { "uType": "parent", "fName": "p1", "lName": "p1", "num": "123" } } Model.aggregate([ { $match: { $or: [ { "parent.num": match.invite.num }, { "child.num": match.num } ] } }, { $project: { parent: { $filter: { input: "$parent", as: "p", cond: { $eq: [ "$$p.num", match.invite.num ] } } }, child: { $filter: { input: "$child", as: "ch", cond: { $eq: [ "$$ch.num", match.num ] } } } } } ]) But you can do something similar without aggregation, but you will not get an empty array when there is no match, you will just don't get the key. Model.find({ $or: [ { "parent.num": match.invite.num }, { "child.num": match.num } ] }, { parent: { $elemMatch: { num: match.invite.num }, }, child: { $elemMatch: { num: match.num } } })
Q: My Session Value is Not Changing Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If IsPostBack = True Then Session("x") = "ABC" End If End Sub Protected Sub btnABC_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnABC.Click Session("x") = "ABC" End Sub Protected Sub btnCBA_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCBA.Click Session("x") = "CBA" End Sub Protected Sub btnShow_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShow.Click TextBox1.Text = Session("x") End Sub End Class Three buttons-ABC,CBA and Show. if you click on ABC and then Click on Show button The textbox shows "ABC" but when I Clicking on CBA button And then Click on Show button The textbox shows again "ABC". IsPostback property will true on each time the page is posted to the server. So the session reset the value. how to overcome this issue ???? A: If you set the value in page_load(), this assignment occurs every time you load the page. Maybe you want to set this value only at the first call of the page: If IsPostback = False Then Session("x") = "Something" End If The second load of the page will not overwrite the value you set in button1_click. A: When you press the show button it causes a postback to the server. The Page_Load method fires first, and you assign "ABC" into Session("x"). Then you're putting Session("x") into into the textbox. What you'd probably want is this instead: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then Session("x") = "ABC" End If End Sub A: Besides what other people wrote above, I also recommend you to assign Session values during Page_InitComplete event. Because mostly developers work in Page_Load stage and some times assigning Session values as well may throw errors because of it. It is like which one is happening before or after. You can make mistakes and so on.
Q: Resizing UIImageView based on UITableViewCell content height using autolayout constraints I have a UITableViewCell xib with below view: As shown it has below components: * *UILabel - dateLabel *UILabel - addressLabel *UILabel - criteriaLabel *UIImageView - separatorImageView Since I want to increase the height of cell based on contents in the labels, I added below constraints to each: So dateLabel constraints are: addressLabel constraints are: criteriaLabel constraints are: Without adding constraints for separatorImageView, cells appear like this: ie. cells are resizing based on content which is perfect :) Now problem is - if I add below constraints to separatorImageView: Cells start appearing like this: Please suggest which constraints shall I add to separatorImageView so that it resizes as per the height of cell without affecting proper resizing of cell. A: Maybe this is not the best answer but for special cases I do this: * *create a UIView named resizingVIEW, pin it to top, bottom, trailing, leading of super view (contentView) *remove separatorImageView Bottom Space Constraint *ctrl+click from separatorImageView to resizingVIEW, select equal height (NOTE set resizingVIEW background color to clear color/ or hide it)
Q: Rendering MongoDB documents with Meteor The question is: how to display complex documents returned from Mongodb. Suppose I have two projects in my Projects collection and each project has 2 People embedded by their IDs from the People collection. Project.find() returns this CURSOR which I'm presenting as JSON for readability: { "_id" : "5ed5ade8-c140-46f7-8d9e-2344fc53df8e", "name" : "Project1", "personnel" : [ "b4690c4b-d126-4737-8f40-921234567890", "977a6335-a1be-4af5-8b3f-4abcdefghijk" ] } { "_id" : "23f073c7-a713-4713-86a7-7d6600433146", "name" : "Project2", "personnel" : [ "b4690c4b-d126-4737-8f40-92b43072d7a1", "977a6335-a1be-4af5-8b3f-48cd5f8328db" ]} My template in .html file: <template name="theProjects"> {{#each theTitles}} Name: {{name}} Personnel: {{personnel}} {{/each}} </template> renders this in the browser: Name: Project1 Personnel: b4690c4b-d126-4737-8f40-921234567890,977a6335-a1be-4af5-8b3f-4abcdefghijk Name: Project2 Personnel:b4690c4b-d126-4737-8f40-92b43072d7a1,977a6335-a1be-4af5-8b3f-48cd5f8328db Questions: * *The {{personnel}} field is simply being filled in by the contents of the personnel array in the Projects collect. I want to list these separately on their own line. Can't figure that out. Just slicing won't do because... *The greater need clearly is to be able to manipulate and edit the Personnel data so the template has to be properly Meteor reactive. *Now the hard one: the personnel ID's from the People collection are embedded in the Project documents. How would I use Meteor to replace the ID's with the appropriate names from the Personnel collection and still keep their data reactivity? I know this is a lot to ask but these kind of things seem like they are foundational to bigger and more complex web site. Thanks everyone. A: https://gist.github.com/3220991 This is a gist I made to show you use the of Handlebars helpers. This will stay reactive and is very easy to use. I hope you can use it. If you need more help or comments , just mention me.
Q: Chalice AWS Eventbridge How do i create handler functions (lambdas) that trigger on custom events in a EventBridge event when using AWS Chalice ? https://aws.github.io/chalice/index.html Docs say they support Cloudwatch events. AWS docs say cloudwatch events is kinda the same as eventbridge. https://aws.github.io/chalice/topics/events.html?highlight=cloudwatch#cloudwatch-events But how do i create a handler for events in my eventbus ? A: Not sure if you have custom events or scheduled events. If scheduled events then @me2resh provided the following samples on his great website: https://www.me2resh.com/posts/2020/05/05/aws-chalice-event-triggers.html app = chalice.Chalice(app_name='chalice-scheduled-event-demo') @app.schedule('cron(15 10 ? * 6L 2002-2005)') def cron_handler(event): pass @app.schedule('rate(5 minutes)') def rate_handler(event): pass @app.schedule(Rate(5, unit=Rate.MINUTES)) def rate_obj_handler(event): pass @app.schedule(Cron(15, 10, '?', '*', '6L', '2002-2005')) def cron_obj_handler(event): pass
Q: More efficient way for this? I am wondering if there is a more efficient way to run this program? It runs fine for lower numbers, but as you increase, so does the time - exponentially. So a number like 1000000 takes forever import java.util.*; public class SumOfPrimes { public static void main(String args[]) { Scanner in = new Scanner(System.in); long number = 0; System.out.println("This program outputs the sum of the primes of a given number."); System.out.print("Please enter a number: "); number = in.nextLong(); System.out.println("The sum of the primes below "+number+" is: "+sumOfPrimes(number)); } public static long sumOfPrimes(long n){ long currentNum = 2; long sum = 0; if (n > 2){ sum = sum + 2; } while (currentNum <= n) { if (currentNum % 2 != 0 && isPrime(currentNum)) { sum = sum + currentNum; } currentNum++; } return sum; } public static boolean isPrime(long currentNum){ boolean primeNumber = true; for (long test = 2; test < currentNum; test++) { if ((currentNum % test) == 0){ primeNumber = false; } } return primeNumber; } } A: There are better prime-finding algorithms, but as a quick fix, you only need to test factors up through the square root of the current number, because if you find a factor above the square root, then you should have found a factor below the square root. long stop = (long) Math.sqrt(currentNum); for (long test = 2; test <= stop ; test++) { Additionally, break out of the loop and return false if you have found a factor and thus proven the number composite. If more efficiency is desired, you can implement the Sieve of Eratosthenes so that you only check possible factors that are themselves prime. A: You really should store a set of prime numbers every time you find one, so you avoid dividing by all the numbers every time. This thing: currentNum % 2 != 0 could be written as currentNum & 1. Also your algorithm is wrong, try giving 3 as input. A: Use Eratosthenes Sievie: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes You will find all primes below given number in O(n log n log n) and you will need to go once over whole table. A: i had written one.i can not make sure all is right.i have tested 1000000 in my machine,it just taken 31 ms. the memory require:1000000*1bytes=1mb public class FindPrime { /** * @param args */ public static void main(String[] args) { long begin=System.currentTimeMillis(); System.out.println(findPrime(1000000)); System.out.println("cost time="+(System.currentTimeMillis()-begin)+"ms"); } public static long findPrime(int max){ boolean data[]=new boolean[max+1]; long sum=0; int stop=(int) Math.sqrt(max); for(int i=2;i<=stop;i++){ if(data[i]==false){ sum+=i; int index=i+i; while(index<=max){ data[index]=true; index=index+i; } //System.out.println(i); } } stop=stop+1; for(;stop<=max;stop++){ if(data[stop]==false){ sum+=stop; //System.out.println(stop); } } return sum; } }
Q: JSON to Python List Context: Using Visual Studio Code, trying to convert my JSON response into a Python list, so I can add it to a Google Sheet. I'd like to convert my response into a List of JSON Lists (like the "working example" below) Working Example RandomJson = [ ['hello',2], ["hi",3] ] bla = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID, range='sheet1!A1', valueInputOption="USER_ENTERED", body={"values":RandomJson}).execute() I've tried a number of ways, but I cannot get "My Data Set" into the "Desired Format" Can anybody help please? My Data Set { "data": { "tokens": [ { "name": "FMX Token", "symbol": "FMXT" }, { "name": "HeavensGate", "symbol": "HATE" }, { "name": "Shrimp Swap", "symbol": "Shrimp" } ] } } Desired Format RandomJson = [ ["FMX Token","FMXT"], ["HeavensGate","HATE"], ["Shrimp Swap","Shrimp"] ] Edit - Full Code I have made a change suggested in the comments, and also added "j = json.loads(JsonData)" I'm now getting an error: "googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets//values/sheet1%21A1?valueInputOption=USER_ENTERED&alt=json returned "Invalid JSON payload received. Unknown name "FMX Token" at 'data.values': Cannot find field." import requests import gspread import json import os.path import pprint from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2 import service_account SERVICE_ACCOUNT_FILE = 'CredEDs.json' SCOPES = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"] creds = None creds = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) SAMPLE_SPREADSHEET_ID = '' service = build('sheets','v4',credentials=creds) sheet = service.spreadsheets() headers = { 'authority': 'api.thegraph.com', 'accept': '*/*', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36', 'content-type': 'application/json', 'origin': 'https://info.uniswap.org', 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'https://info.uniswap.org', 'accept-language': 'en-GB,en;q=0.9,es-419;q=0.8,es;q=0.7,en-US;q=0.6', } data = rb'{"operationName":"tokens","variables":{"skip":500},"query":"query tokens($skip: Int\u0021) {\n tokens(first: 500, skip: $skip) {\n name\n symbol\n}\n}\n"}' response = requests.post('https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2', headers=headers, data=data) JsonData = response.text j = json.loads(JsonData) result = {token['name']: token['symbol'] for token in j['data']['tokens']} bla = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID, range='sheet1!A1', valueInputOption="USER_ENTERED", body={"values":result}).execute() A: It's as simple as: result = [[token['name'], token['symbol']] for token in data['data']['tokens']]
Q: How do I plant flowers in the beginning of the game? In various guides I see the same advice: The [Gardening] store opens five days after the player has created their town. The player must also pull weeds and plant flowers a combined total of 30 times. But the gardening store is where I buy flower seeds so... how can I plant flowers before it opens? A: You can plant flowers simply by picking up flowers that have grown on their own with the Y button, moving to a new location, and going into the inventory and planting them from there. A: As another suggestion in addition to the current answers, a perhaps more productive method to achieve this goal is to complete the requirements to unlock the island. This can be achieved as early as day four (source) and will allow you access to several mini-games that generate temporary locations with flowers already planted. You can pick up these flowers and they will remain in your inventory after the mini-game has ended. You can store the flowers in the box near Leilani, which holds up to 40 items. When you leave the island, you will be able to collect any items in the box located on the dock. Collecting flowers from the island will allow you to plant new flowers instead of tricking the game counter by planting existing flowers, and to begin any landscaping goals (or progress towards particular badges) earlier. It is a useful source of flowers even after the gardening shop opens, as you can collect many more flowers on the island than you can each day in the shop. A: I was able to purchase flowers at a friend's gardening store, so that's a second way if you have friends further along than you.
Q: How to assign the table value to stored procedure parameter using entityframeworkextra Im sending Html table values to mvc controller action method using angular. This is my angular code. var feedbackdata = { SpeakerRatings: $scope.SpeakerTable // This scope contains two rows of table data }; FeedBackFormfac.InsertFeedback(feedbackdata).then(function (data) { alert(data.data) }) fac.InsertFeedback = function (d) { return $http({ url: '/Feedback/Insert', method: 'POST', data: JSON.stringify(d), headers: {'content-type': 'application/json'} }); }; And im receiving this json data in my controller action method. And im trying to insert this data into my database using entityframeworkextra. But im not able to bind the table values to parameter SpeakerRatings. public JsonResult Insert(FeedBackFormVM F) { var procedure = new InsertFeedbackSP() { SpeakerRatings = new List<SpeakerRatingsUDT> { new SpeakerRatingsUDT() } } } In above code im trying to bind the data coming from angular i.e (object F contains Html table values) to Userdefined table type class which is created using entityframeworkextra and my userdefined table class will be like this [UserDefinedTableType("SpeakerRatingsType")] public class SpeakerRatingsUDT { [UserDefinedTableTypeColumn(1)] public int SpeakerId { get; set; } [UserDefinedTableTypeColumn(2)] public string SpeakerName { get; set; } [UserDefinedTableTypeColumn(3)] public int Rating { get; set; } } A: Im receiving Html table values into List with type of UserdefinedType class public JsonResult Insert(FeedBackFormVM F) { List<SpeakerRatingsVM> newdata = F.SpeakerRatings; var procedure = new InsertFeedbackSP() { SpeakerRatings = newdata.Select(x => new SpeakerRatingsUDT { SpeakerId=x.SpeakerId,SpeakerName=x.SpeakerName,Rating=x.Rating}).ToList() } }
Q: I want to redirect each, old URLs to its corresponding new rewritten URLs using htaccess After much research, I have come to the conclusion that I am stuck and need help. Here is my htaccess: ErrorDocument 404 http://website.com/404.php <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule . http://%1%{REQUEST_URI} [R=301,L] RewriteRule contact contact.php [NC,L] RewriteRule about display.php?id=2 [NC,L] RewriteRule services display.php?id=4 [NC,L] RewriteRule rss.xml?$ rss.php [L] </IfModule> This successfully created a rewritten URL for each display.php?id= query. Now that I have both URLs, how can I permanently redirect display.php?id=2 to about? Thanks so much for your help! A: First off, clear your browser cache. We don't want any cached permanent redirects which you already tried messing with our new logic: #remove www RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L] #Use 302 redirects for debugging (the default if no redirect code is provided): RewriteRule ^/?contact/?$ contact.php [NC,L,R] RewriteRule ^/?about/?$ display.php?id=2 [NC,L,R] RewriteRule ^/?services/?$ display.php?id=4 [NC,L,R] RewriteRule ^/?rss.xml/?$ rss.php [NC,L,R] If you're using google chrome, you can press ctrl+shift+j to open the developer tools. Then click the "network" tab and check the "disable cache" checkbox. Then try your requests again to see if it's working. Notice my code uses 302 redirects, this is the best practice for debugging. Once you can verify it's working as expected, you change change the 302 redirects to 301 redirects for production. Edit: To redirect everything the other way around, use this one instead: #remove www RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L] #Use 302 redirects for debugging (the default if no redirect code is provided): RewriteRule ^/?contact.php/?$ contact [NC,L,R] RewriteCond %{QUERY_STRING} (^|&)id=2(&|$) RewriteRule ^/?display\.php/?$ about? [NC,L,R] RewriteCond %{QUERY_STRING} (^|&)id=4(&|$) RewriteRule ^/?display\.php/?$ services? [NC,L,R] RewriteRule ^/?rss.php/?$ rss.xml [NC,L,R] Edit2: #remove www RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L] #handle silent rewrites first: RewriteCond %{THE_REQUEST} ^\w+\s+/?about RewriteRule ^/?about/?$ /display.php?id=2&r=%1 [NC,L] RewriteCond %{THE_REQUEST} ^\w+\s+/?contact RewriteRule ^/?contact/?$ contact.php [NC,L] RewriteCond %{THE_REQUEST} ^\w+\s+/?services RewriteRule ^/?services/?$ display.php?id=4 [NC,L] RewriteCond %{THE_REQUEST} ^\w+\s+/?rss\.xml RewriteRule ^/?rss.xml/?$ rss.php [NC,L] #handle redirects: RewriteCond %{THE_REQUEST} ^\w+\s+/?display.php RewriteCond %{QUERY_STRING} (^|&)id=2(&|$) RewriteRule ^/?display\.php/?$ about? [NC,L,R] RewriteCond %{THE_REQUEST} ^\w+\s+/?contact\.php RewriteRule ^/?contact.php/?$ contact [NC,L,R] RewriteCond %{THE_REQUEST} ^\w+\s+/?display\.php RewriteCond %{QUERY_STRING} (^|&)id=4(&|$) RewriteRule ^/?display\.php/?$ services? [NC,L,R] RewriteCond %{THE_REQUEST} ^\w+\s+/?rss\.php RewriteRule ^/?rss.php/?$ rss.xml [NC,L,R] Edit3: Actually, we can make use of the END flag here for slightly cleaner code: #remove www RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L] #handle silent rewrites first: RewriteRule ^/?about/?$ /display.php?id=2&r=%1 [NC,L,NS,END] RewriteRule ^/?contact/?$ contact.php [NC,L,NS,END] RewriteRule ^/?services/?$ display.php?id=4 [NC,L,NS,END] RewriteRule ^/?rss.xml/?$ rss.php [NC,L,NS,END] #handle redirects: RewriteCond %{QUERY_STRING} (^|&)id=2(&|$) RewriteRule ^/?display\.php/?$ about? [NC,L,R,END] RewriteRule ^/?contact.php/?$ contact [NC,L,R,END] RewriteCond %{QUERY_STRING} (^|&)id=4(&|$) RewriteRule ^/?display\.php/?$ services? [NC,L,R,END] RewriteRule ^/?rss.php/?$ rss.xml [NC,L,R,END]
Q: Why don't some query results have graph representation in Neo4j? In the Neo4j Browser, I performed one query as follows: match (subject:User {name:{name}}) match (subject)-[:works_for]->(company:Company)<-[:works_for]-(person:User), (subject)-[:interested_in]->(interest)<-[:interested_in]-(person) return person.name as name, count(interest) as score, collect(interest.name) as interests order by score DESC The result only has the "table" and "text" views, without the "graph". Normally, a query can generate a subgraph. Right? A: If you look at your return, you're not returning any actual nodes or relationships. You're returning property values (strings), counts (longs), and collections of strings. If you returned person instead you would probably be able to see a graphical result, as the return would include data (id, labels, properties) that could be used to display graph elements.
Q: Environment variables in database vs application settings in Azure I have a boss that is a bit old school (still uses Hungarian notation, e.g. oDatabaseContext) and insists that environment variables (not connection strings) should be pulled from the database instead of application settings in Azure. Little more background: * *.NET Core 5 *Services are hosted on Azure Getting current settings is done in the following way *Makes a database call to a separate database that holds all application settings where applicationId = x o Loops through the returned records, with an expected number of settings. o If the number of settings that comes back doesn't come back with the expected value, an exception is thrown o Uses case statement with string literals to match the name of the setting o Sets the value to a global variable My opinion would be to set these variables in the Application Settings in for the app service in Azure. Here's what I see, but not limited to, the pros and cons of each approach: Database for settings: Pros: * *Easier to find settings for all applications *Can change application settings much faster *Can be more easily create a UI to see the settings Cons: * *Code bloat *Tied to the database and not easily portable *Since variables for all applications in there, easier to make a mistake and change a wrong setting *Doesn't all for Options Patter *There may be dozens of applications with their own settings Application setting Pros: * *Easily portable *Specific to each service *Better security *Allows for Options Pattern Cons: * *More difficult to navigate to each services settings Looking for other options on the database settings approach.
Q: what is the fastest way to get the mode of a numpy array I have to find the mode of a NumPy array that I read from an hdf5 file. The NumPy array is 1d and contains floating point values. my_array=f1[ds_name].value mod_value=scipy.stats.mode(my_array) My array is 1d and contains around 1M values. It takes about 15 min for my script to return the mode value. Is there any way to make this faster? Another question is why scipy.stats.median(my_array) does not work while mode works? AttributeError: module 'scipy.stats' has no attribute 'median' A: The implementation of scipy.stats.mode has a Python loop for handling the axis argument with multidimensional arrays. The following simple implementation, for one-dimensional arrays only, is faster: def mode1(x): values, counts = np.unique(x, return_counts=True) m = counts.argmax() return values[m], counts[m] Here's an example. First, make an array of integers with length 1000000. In [40]: x = np.random.randint(0, 1000, size=(2, 1000000)).sum(axis=0) In [41]: x.shape Out[41]: (1000000,) Check that scipy.stats.mode and mode1 give the same result. In [42]: from scipy.stats import mode In [43]: mode(x) Out[43]: ModeResult(mode=array([1009]), count=array([1066])) In [44]: mode1(x) Out[44]: (1009, 1066) Now check the performance. In [45]: %timeit mode(x) 2.91 s ± 18 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [46]: %timeit mode1(x) 39.6 ms ± 83.8 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 2.91 seconds for mode(x) and only 39.6 milliseconds for mode1(x). A: Here's one approach based on sorting - def mode1d(ar_sorted): ar_sorted.sort() idx = np.flatnonzero(ar_sorted[1:] != ar_sorted[:-1]) count = np.empty(idx.size+1,dtype=int) count[1:-1] = idx[1:] - idx[:-1] count[0] = idx[0] + 1 count[-1] = ar_sorted.size - idx[-1] - 1 argmax_idx = count.argmax() if argmax_idx==len(idx): modeval = ar_sorted[-1] else: modeval = ar_sorted[idx[argmax_idx]] modecount = count[argmax_idx] return modeval, modecount Note that this mutates/changes the input array as it sorts it. So, if you want to keep the input array un-mutated or do mind the input array being sorted, pass a copy. Sample run on 1M elements - In [65]: x = np.random.randint(0, 1000, size=(1000000)).astype(float) In [66]: from scipy.stats import mode In [67]: mode(x) Out[67]: ModeResult(mode=array([ 295.]), count=array([1098])) In [68]: mode1d(x) Out[68]: (295.0, 1098) Runtime test In [75]: x = np.random.randint(0, 1000, size=(1000000)).astype(float) # Scipy's mode In [76]: %timeit mode(x) 1 loop, best of 3: 1.64 s per loop # @Warren Weckesser's soln In [77]: %timeit mode1(x) 10 loops, best of 3: 52.7 ms per loop # Proposed in this post In [78]: %timeit mode1d(x) 100 loops, best of 3: 12.8 ms per loop With a copy, the timings for mode1d would be comparable to mode1. A: I added the two functions mode1 and mode1d from replies above to my script and tried to compare with the scipy.stats.mode. dir_name="C:/Users/test_mode" file_name="myfile2.h5" ds_name="myds" f_in=os.path.join(dir_name,file_name) def mode1(x): values, counts = np.unique(x, return_counts=True) m = counts.argmax() return values[m], counts[m] def mode1d(ar_sorted): ar_sorted.sort() idx = np.flatnonzero(ar_sorted[1:] != ar_sorted[:-1]) count = np.empty(idx.size+1,dtype=int) count[1:-1] = idx[1:] - idx[:-1] count[0] = idx[0] + 1 count[-1] = ar_sorted.size - idx[-1] - 1 argmax_idx = count.argmax() if argmax_idx==len(idx): modeval = ar_sorted[-1] else: modeval = ar_sorted[idx[argmax_idx]] modecount = count[argmax_idx] return modeval, modecount startTime=time.time() with h5py.File(f_in, "a") as f1: myds=f1[ds_name].value time1=time.time() file_read_time=time1-startTime print(str(file_read_time)+"\t"+"s"+"\t"+str((file_read_time)/60)+"\t"+"min") print("mode_scipy=") mode_scipy=scipy.stats.mode(myds) print(mode_scipy) time2=time.time() mode_scipy_time=time2-time1 print(str(mode_scipy_time)+"\t"+"s"+"\t"+str((mode_scipy_time)/60)+"\t"+"min") print("mode1=") mode1=mode1(myds) print(mode1) time3=time.time() mode1_time=time3-time2 print(str(mode1_time)+"\t"+"s"+"\t"+str((mode1_time)/60)+"\t"+"min") print("mode1d=") mode1d=mode1d(myds) print(mode1d) time4=time.time() mode1d_time=time4-time3 print(str(mode1d_time)+"\t"+"s"+"\t"+str((mode1d_time)/60)+"\t"+"min") The result from running the script for a numpy array of around 1M is : mode_scipy= ModeResult(mode=array([ 1.11903353e-06], dtype=float32), count=array([304909])) 938.8368742465973 s 15.647281237443288 min mode1=(1.1190335e-06, 304909) 0.06500649452209473 s 0.0010834415753682455 min mode1d=(1.1190335e-06, 304909) 0.06200599670410156 s 0.0010334332784016928 min
Q: How to create, load and use sprite sheets in allegro 5? I'm now familiar with allegro. But now allegro learning leads me to learn sprite sheets for my character animations. This time I want some help on how to create, load and use the sprite sheets in allegro 5. I'm using Dev c++ in windows PC. And without network connection(thought I should specify). A: Creating a spritesheet is just a matter of creating an image in the art program of your choice, divided up into rectangular regions. For the sake of this example, lets say each region in your spritesheet is 32x32 pixels. To load the spritesheet, just use al_load_bitmap There is an example here. To draw 'sprites', you can use al_draw_bitmap_region and tell it what subsection of the spritesheet to draw. Assuming our spritesheet is divided up into 32x32 pixel rectangles and x, y is the location you want to draw the sprite at: al_draw_bitmap_region(spritesheet, 0, 0, 32, 32, x, y) would draw the 'first sprite' (from the very top-left corner of the sheet), al_draw_bitmap_region(spritesheet, 32, 0, 32, 32, x, y) would draw the sprite just to the right of the first one, and so forth...
Q: unique number from a string - php I have some strings containing alpha numeric values, say asdf1234, qwerty//2345 etc.. I want to generate a specific constant number related with the string. The number should not match any number generated corresponding with other string.. A: Does it have to be a number? You could simply hash the string, which would give you a unique value. echo md5('any string in here'); Note: This is a one-way hash, it cannot be converted from the hash back to the string. This is how passwords are typically stored (using this or another hash function, typically with a 'salt' method added.) Checking a password is then done by hashing the input and comparing to the stored hash. edit: md5 hashes are 32 characters in length. Take a look at other hash functions: http://us3.php.net/manual/en/function.crc32.php (returns a number, possibly negative) http://us3.php.net/manual/en/function.sha1.php (40 characters) A: You can use a hashing function like md5, but that's not very interesting. Instead, you can turn the string into its sequence of ASCII characters (since you said that it's alpha-numeric) - that way, it can easily be converted back, corresponds to the string's length (length*3 to be exact), it has 0 collision chance, since it's just turning it to another representation, always a number and it's a little more interesting... Example code: function encode($string) { $ans = array(); $string = str_split($string); #go through every character, changing it to its ASCII value for ($i = 0; $i < count($string); $i++) { #ord turns a character into its ASCII values $ascii = (string) ord($string[$i]); #make sure it's 3 characters long if (strlen($ascii) < 3) $ascii = '0'.$ascii; $ans[] = $ascii; } #turn it into a string return implode('', $ans); } function decode($string) { $ans = ''; $string = str_split($string); $chars = array(); #construct the characters by going over the three numbers for ($i = 0; $i < count($string); $i+=3) $chars[] = $string[$i] . $string[$i+1] . $string[$i+2]; #chr turns a single integer into its ASCII value for ($i = 0; $i < count($chars); $i++) $ans .= chr($chars[$i]); return $ans; } Example: $original = 'asdf1234'; #will echo #097115100102049050051052 $encoded = encode($original); echo $encoded . "\n"; #will echo asdf1234 $decoded = decode($encoded); echo $decoded . "\n"; echo $original === $decoded; #echoes 1, meaning true A: You're looking for a hash function, such as md5. You probably want to pass it the $raw_output=true parameter to get access to the raw bytes, then cast them to whatever representation you want the number in. A: A cryptographic hash function will give you a different number for each input string, but it's a rather large number — 20 bytes in the case of SHA-1, for example. In principle it's possible for two strings to produce the same hash value, but the chance of it happening is so extremely small that it's considered negligible. If you want a smaller number — say, a 32-bit integer — then you can't use a hash function because the probability of collision is too high. Instead, you'll need to keep a record of all the mappings you've established. Make a database table that associates strings with numbers, and each time you're given a string, look it up in the table. If you find it there, return the associated number. If not, choose a new number that isn't used by any of the existing records, and add the new string and number to the table.
Q: Separation from URL the scrape of text I have a some URL like this: http://www.newspaper.pl/abcd/bcda.dll/article?AID=/20140128/XXX/140129527 and want to separate this scrape of text 20140128/XXX/140129527 but only when URL have this scrape of text article?AID=/ I have tried function "substring" but all of my options were wrong. What's more sometimes url doesn't end like this, but have sign & etc., like this http://www.newspaper.pl/abcd/bcda.dll/article?AID=/20140128/XXX/140129527&photo1 and I also want to separate the same scrape of text without &photo1 Do you have any idea? This scrape of text 'XXX/140129527' hasdifferent length. I really couldn't find the solution of this problem on stack. A: CREATE TABLE meuk ( total varchar , base_url varchar , rest_url varchar ); INSERT INTO meuk(total) VALUES ('http://www.newspaper.pl/abcd/bcda.dll/article?AID=/20140128/XXX/140129527') ; You could use regexp_replace() : UPDATE meuk SET base_url = regexp_replace(total, E'([^?]+)?AID=(.+)', E'\\1' ) -- , rest_url = regexp_replace(total, E'http://.+\?AID=/(.+)', E'\\1' ) , rest_url = regexp_replace(total, E'http://.+\?AID=/([^&]+)(.*)$', E'\\1' ) ; SELECT * FROM meuk; Result: CREATE TABLE INSERT 0 1 UPDATE 1 total | base_url | rest_url ---------------------------------------------------------------------------+------------------------------------------------+------------------------ http://www.newspaper.pl/abcd/bcda.dll/article?AID=/20140128/XXX/140129527 | http://www.newspaper.pl/abcd/bcda.dll/article? | 20140128/XXX/140129527 (1 row)
Q: In Python 3.6, why don't string literals (using the same quote type) work inside interpolated strings? Basic example: >>> table = {'username': 'John Doe'} >>> msg = f'Hello {table['username']}' File "<stdin>", line 1 msg = f'Hello {table['username']}' ^ SyntaxError: invalid syntax >>> msg = f"Hello {table['username']}" Why doesn't it work when both the format string and the inner string literal use the same quote type (both single-quoted or double-quoted)? Is this a bug in Python 3.6, or is this intentional? edit: To make it clear why I'm asking this, something like this works fine in C#: using System; public static class Program { public static void Main() { Console.WriteLine($"Hello {"world"}"); } } Proof A: This has nothing to do with interpolated strings. An interpolated string is read the same as any other string literal* and then interpolated, and you can't put unescaped quote characters in the middle of any string: >>> msg = 'Hello {table['username']}' File "<stdin>", line 1 'Hello {table['username']}' ^ SyntaxError: invalid syntax >>> msg = 'Hello 'world'' File "<stdin>", line 1 msg = 'Hello 'world'' ^ SyntaxError: invalid syntax This is exactly why we have a choice of two different quote characters—and, when that isn't enough, triple-quoted strings. And of course escaping. So, why can't Python be smarter here? Think about what "smarter" would mean. Assuming it can't read your mind, it would have to parse every possible way that pairs of quotes could be matched up if some of them were skipped and then figure out which one made for a valid result. That might not seem too bad for a simple one-liner at the interactive interpreter, but if it had to do that across an entire file, every time you run a non-trivial script or import a module with more than a few quotes in it, it would take minutes to try all the parses, and the result could well be ambiguous anyway. Could they instead add special rules for handling quotes only in interpolated strings, only inside currently-open braces (but not double braces, of course, because those are escapes), and so on? Sure, That wouldn't make the parser exponential, just more complicated. But more complicated is not good either. The fact that Python has a simple set of rules that anyone can knock out a LL(1) implementation of—and, maybe even more importantly, that anyone can keep in their heads and work through—is a major feature of the language as compared to, say, C++. So every time there's a tradeoff between nice syntactic sugar vs. keeping the parser simple, it has to be thought through, and the answer is always keeping the parser simpler. In fact, this was an explicit decision in the Python 3 transition: Simple is better than complex. This idea extends to the parser. Restricting Python's grammar to an LL(1) parser is a blessing, not a curse. It puts us in handcuffs that prevent us from going overboard and ending up with funky grammar rules like some other dynamic languages that will go unnamed, such as Perl. Also, of course, that would be a difference between f-strings and str.format, which would be another rule to learn, and to relearn every time you come back to Python after a few months away. Which is a different rule from the Zen: Special cases aren't special enough to break the rules. A: the problem is that it is a string and you did not do the interpolation, because that was the error, you should use string.Template to define a format string or you can use the format method of str class with which you can substitute values inside of a String 'Hello {table['username']}' this is bad you can use 'Hello {username}'.format(username=table['username']) see for more information: here
Q: Am automating a webpage which take time to load a page on clicking a link. Tried implicit and explicit waits,it is not working.Any other suggestions? driver.findElement(By.xpath("xxxx")).click(); Clicking on the above link will take to another page. But it will take long time. So while trying to find an element in the resulting page shows an error. driver.findElement(By.xpath("yy")).getText(); I have tried Implicit and Explicit Waits, but it is not working everytime. A: Use WebDriver wait. Put element which you need in 2nd page. Feel free to change any locator in below code :- WebDriverWait wait = new WebDriverWait(driver, 100); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid"))); Hope it will help you :)
Q: Prove that if $p\ge 7$ is a prime number , then $p^{4}\equiv 1\pmod{240}$ Prove that if $p\ge 7$ is a prime, then $$p^{4}\equiv 1\pmod {240}$$ This is the problem.I found that the given is true with modulo $24$. But I can't find his I cab site that $10\mid p^{4}-1$. A: First thing is that $240=16\times3\times5=2^4\times3\times5$. By Fermat little theorem you have the fact that $p^4\equiv 1 \pmod5$ (because $7\le p)$. It gives you $\gcd(p^4,5)=1$ and notice that $p\ge 7$. Moreover you know that $\gcd(p^4,3)=1=\gcd(p^4,15)$. Then you know that $\gcd(p,2)=1$ because $p\ge 7$. Then it gives you, developing by itself $(up+2v=1)$ with Bachet-Bézout, that $\gcd(p^2,2)=1$. You develop again by Bachet-Bézout two times and you have $\gcd(p^4,2)=1$. You do the exact the same thing with $2$, four times, and you get $\gcd(p^4,2^4=16)=1$. So you conclude that $\gcd(p^4,15\times16=240)=1 \Leftrightarrow p^4\equiv 1 \pmod{240}$. But you can also use the CRT as @Jack D'Aurizio suggests.
Q: TreeView connect to Multiple Visibility (ContentControl/ListView/etc..) in MVVM I have a TreeView connected to a ListView and a ContentControl. When we click on a node, that put the Visibility to Hidden or Visible. I already code that and it's working, but it's on MVVM so I want to convert it, and I do not know how. Code I have already: private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { String tmp = ((TreeViewItem)e.NewValue).Header.ToString(); Console.Write(tmp); if (tmp == "Lecteur") { Console.Write("Lecteur\n"); MediaPlayer.Visibility = Visibility.Visible; Bibliotheque.Visibility = Visibility.Hidden; } else if (tmp == "Bibliotheque") { Console.Write("Bibliotheque\n"); MediaPlayer.Visibility = Visibility.Hidden; Bibliotheque.Visibility = Visibility.Visible; } } If you have an idea, binding all Visibility of ContentControl/ListView or other... A: This can be done in the UI using triggers, you don't need any extra logic in the codebehind or in the ViewModel <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <TreeView Grid.Row="0" x:Name="TrV"> <TreeViewItem Header="Lecteur"/> <TreeViewItem Header="Bibliotheque"/> </TreeView> <ListView Grid.Row="1"> <ListView.Style> <Style TargetType="ListView"> <Setter Property="Visibility" Value="Visible"/> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=TrV,Path=SelectedItem.Header}"> <DataTrigger.Value> <system:String>Lecteur</system:String> </DataTrigger.Value> <Setter Property="Visibility" Value="Hidden"/> </DataTrigger> </Style.Triggers> </Style> </ListView.Style> <ListViewItem Content="Lv_One"/> <ListViewItem Content="Lv_Two"/> <ListViewItem Content="Lv_Three"/> </ListView> <MediaElement Grid.Row="2" > <MediaElement.Style> <Style TargetType="MediaElement"> <Setter Property="Visibility" Value="Visible"/> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=TrV,Path=SelectedItem.Header}"> <DataTrigger.Value> <system:String>Bibliotheque</system:String> </DataTrigger.Value> <Setter Property="Visibility" Value="Hidden"/> </DataTrigger> </Style.Triggers> </Style> </MediaElement.Style> </MediaElement> </Grid>
Q: Javascript Prototype Pattern - Feedback I'm switching from using a Javascript revealing module pattern and what I have below seems to work. What I want to know is if what I'm doing is correct and does it follow best practices. For example, is the way I'm preserving the 'this' state and calling an init function in the constructor correct? var testApp = function(){ //Kick it off this.init(); }; testApp.prototype = { getUsers: function(callback){ //do stuff }, buildUserTable: function(data){ //do stuff }, refreshTable: function(){ //Example this.getUsers(); }, init: function(){ //Preserve 'this' var instance = this; //Callback + init this.getUsers(function(data){ instance.buildUserTable(data); }); $('.formSection .content').hide(); $('.formSection .content:first').slideDown('slow').addClass('selected'); } }; window.onload = function () { var form = new testApp(); }; A: You're overriding the prototype completely. You can't deal with inheritance that way. Since {} is an object you are implicitly inheriting from Object but nothing else. Inheritance looks like this: function A() {}; function B() {}; B.prototype = new A(); var b = new B(); console.log(b instanceof A); // "true" B now inherits from A and Object. If you now do: B.prototype = { foo: function () {} }; var b = new B(); console.log(b instanceof A); // "false" You're not longer inhering from A; How to add functions to a prototype? Use this notation: B.prototype.foo = function () {};
Q: custom controller session reset I am facing strange issue. Session is reset on custom module controller. have anyone face the similar issue? My code is simple class Test_Testing_IndexController extends Mage_Core_Controller_Front_Action { public function indexAction() { $this->loadLayout(); $this->renderLayout(); } } It is related to customer session other pages are working normally changing the login to logout but not on custom module page. I am not using any custom session only Magento own session. My config.xml <config> <modules> <Test_Testing> <version>0.1.0</version> </Test_testing> </modules> <frontend> <routers> <testing> <use>standard</use> <args> <module>Test_Testing</module> <frontName>testing</frontName> </args> </testing> </routers> </frontend>
Q: Why JavaScript array is repeating after add canvas.addEventListener() for onclick event on canvas I have showing some images on canvas using JavaScript. Also I have generate on-Click event on canvas using canvas.addEventListener("mousedown", doMouseDown, false); . If I put alert an array before canvas.addEventListener("mousedown", doMouseDown, false); then fine but But when I put alert an array in Mouse_Down() then it showing Previous with current array in alert. All above code is re-execute on menu change. JavaScript Code is - var Image_Array = []; for (i = 0; i < Values.length; i++) { Image_Array.push(image_data[i]); } alert(Image_Array); // is showing fine canvas.addEventListener("mousedown", Mouse_Down, false); function Mouse_Down(event) { // here is problem means array showing previous and current array value. alert(Image_Array); } Above all code execute on menu change. Please help.
Q: Add Kendo UI MVC reference to Unit Test project I am trying to add kendo mvc ui reference to unit test project but it doesn't affect. How can I add reference kendo mvc ui dll to existing unit test project? A: What do you mean by "can't add reference"? Do you get some error message when selecting the dll? Does it show on the list af available assemblies at all? Does it appear in the references but with a yellow icon? Check the target framework version of the unit test project, in case it is not high enough for the Dll you want to add.
Q: How to remove undesirable text/HTML tags from FLEX LineChart's custom dataTips? I wrote a function to override my FLEX LineChart's datatips because the default datatips were ugly and rather boring. I finally set the style I wanted but am now having some problems removing un-necessary tags from being displayed in the custom datatips. For example, the datatips now display things like this: "<b>Humidity</b></BR>2010-07-05T00:15:00" I can always perform a "Replace()" to remove those break and bold HTML tags, but that seems really un-necessary and anti-development. I am using this to set the dataTip's label text: var hd:HitData = value as HitData; var item:LineSeriesItem = hd.chartItem as LineSeriesItem; _xAxisText = String(hd.displayText + ' ' + item.xValue); Why is [displayText] displaying HTML tags I must parse out? How can I format those tags out of my text's value? Is there a setting? I understand the HTML tag's purpose, although they are not being used by FLEX (apparently). I just dont understand how to remove them from the text. I already set my style attributes in the container, which I think would override these tags? Could that be why they are appearing? Any ideas or suggestions? Thanks! A: Flex should definitely be using the HTML tags to format your dataTip. Check this article. Because you are seeing HTML tags in your dataTips, I am wondering if you perhaps implemented the dataTipFunction incorrectly. If you are able to, you should post a little bit more code.
Q: A way to RegEx match a Number without a prefix tag? 1 <span class='Txt9Gray'>Decisions ( </span> I'm trying to grab the 1 from this string. Before the 1 is another span, but I can't use that as a marker because it can change from page to page. Is there any regex expression that can simply grab the 1? The word Decisions will always exist. That's my main way to find this line. Here's what I have been trying to no avail: strRegex.Append("(?<strDecisionWins>[^<]+)[\s]*? <span class='[\s\w\W]*'>\bDecisions\b \([\s\w\W]*?</span>") This keeps grabbing the spans before the actual 1. The full line containing the above is: <span class='Txt9Gray'>(T)KOs ( </span> 66.67 <span class='Txt9Gray'>%) </span> <br /> 1 <span class='Txt9Gray'>Decisions ( </span> 33.33 <span class='Txt9Gray'>%) </span> <br /> The problem is that the match is matching the very beginning, instead of the one piece. A: How about: \d+(?=\s*\<[^\>]+\>[^\<]*\bDecisions\b) \d+(?=\s*<[^>]+>[^<]*\bDecisions\b) That would only select 1 (and nothing else) The second form is for regex processor which does not need to escape < and >. The lookahead expression (?=...) guarantees to select a number \d+ followed by an element () containing a text (meaning no opening '<': [^<]*), which includes the word Decisions. The lookahead technique can be combined with other regex like: \s\d(?=\s*\<[^\>]+class\s*=\s*'Txt9Gray'[^\>]*\>) \s\d(?=\s*\<[^>]+class\s*=\s*'Txt9Gray'[^>]*>) would grab a single digit (provided it follows a space), followed by an element containing the attribute 'class='Txt9Gray''
Q: How to use "template" and "rowTemplate" field in syncfusion React DataGrid? I am setting up a Data Grid table from React syncfusion in my application. My application is built with antDesign Pro template, DvaJS, UmiJS, and ReactJS. I have made the basic syncfusion Data Grid that uses default fields to fetch the cell data and it works fine. As soon as I add "template" field to ColumnDirective or "rowTemplate" to GridComponent, I get the error. import React, { Component } from 'react'; import router from 'umi/router'; import { connect } from 'dva'; import { Input } from 'antd'; import moment from 'react-moment'; import { ColumnDirective, ColumnsDirective, Filter, Grid, GridComponent } from '@syncfusion/ej2-react-grids'; @connect(({loading, data})=> ({ data: data.data, loading: loading.effects['data/fetchData'] })) class dataComponent extends Component { constructor(){ super(...arguments); this.state = { data: [], } this.columnTemplate = this.columnTemplate; } columnTemplate(props) { return ( <div className="image"><p>text</p></div> ); } render() { const { match, children, location, dispatch, data} = this.props; return ( <GridComponent dataSource={data}> <ColumnsDirective> <ColumnDirective headerText='Heading' template={this.columnTemplate}/> <ColumnDirective field='EmployeeID' headerText='Employee ID'/> <ColumnDirective field='FirstName' headerText='Name'/> </ColumnsDirective> </GridComponent> ); } Expected output: Heading Employee ID FirstName Text 123 John In actual, it doesn't render anything after adding template field to code. In console, I get this error: Uncaught TypeError: str.match is not a function at evalExp (template.js:65) at compile (template.js:52) at Object.push../node_modules/@syncfusion/ej2-grids/node_modules/@syncfusion/ej2-base/src/template-engine.js.Engine.compile (template-engine.js:57) at compile (template-engine.js:16) at templateCompiler (util.js:145) at new Column (column.js:131) at prepareColumns (util.js:185) at GridComponent.push../node_modules/@syncfusion/ej2-grids/src/grid/base/grid.js.Grid.render (grid.js:704) at GridComponent.push../node_modules/@syncfusion/ej2-react-grids/src/grid/grid.component.js.GridComponent.render (grid.component.js:35) at finishClassComponent (react-dom.development.js:14741) at updateClassComponent (react-dom.development.js:14696) at beginWork (react-dom.development.js:15644) at performUnitOfWork (react-dom.development.js:19312) at workLoop (react-dom.development.js:19352) at HTMLUnknownElement.callCallback (react-dom.development.js:149) at Object.invokeGuardedCallbackDev (react-dom.development.js:199) at invokeGuardedCallback (react-dom.development.js:256) at replayUnitOfWork (react-dom.development.js:18578) at renderRoot (react-dom.development.js:19468) at performWorkOnRoot (react-dom.development.js:20342) at performWork (react-dom.development.js:20254) at performSyncWork (react-dom.development.js:20228) at requestWork (react-dom.development.js:20097) at scheduleWork (react-dom.development.js:19911) at Object.enqueueSetState (react-dom.development.js:11169) at DynamicComponent../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:335) at dynamic.js:91 When I click on template.js:65 it show the following as error: var isClass = str.match(/class="([^\"]+|)\s{2}/g); Here's the link to code I am trying to follow: Syncfusion template example I'd highly appreciate your help! A: Query #1: How to use the column template on Syncfusion EJ2 Grid in React platform. You can customize the own element instead of field value in EJ2 Grid column. Please refer the below code example, sample and Help Documentation for more information. export class ColumnTemplate extends SampleBase { constructor() { super(...arguments); this.template = this.gridTemplate; } gridTemplate(props) { return ( <div className="image"><p>text</p></div> //Here defined your element ); } render() { return (<div className='control-pane'> <div className='control-section'> <GridComponent dataSource={employeeData} width='auto' height='359'> <ColumnsDirective> <ColumnDirective headerText='Heading' width='180' template={this.template} textAlign='Center'/> <ColumnDirective field='EmployeeID' headerText='Employee ID' width='125' textAlign='Right'/> <ColumnDirective field='FirstName' headerText='Name' width='120'/> </ColumnsDirective> </GridComponent> </div> </div>); } } Sample link: https://stackblitz.com/edit/react-gdraob?file=index.js Help Documentation: https://ej2.syncfusion.com/react/documentation/grid/columns/#column-template Query #2: How to use the row template on Syncfusion EJ2 Grid in React platform. We have provided the EJ2 Grid with row template feature support it is allow template for the row and we have rendered element instead of each Grid row. Please refer the below code example, sample and Help Documentation for more information. export class RowTemplate extends SampleBase { constructor() { super(...arguments); this.format = (value) => { return instance.formatDate(value, { skeleton: 'yMd', type: 'date' }); }; this.template = this.gridTemplate; } gridTemplate(props) { return (<tr className="templateRow"> <td className="details"> <table className="CardTable" cellPadding={3} cellSpacing={2}> . . . . </tbody> </table> </td> </tr>); } render() { return (<div className='control-pane'> <div className='control-section'> <GridComponent dataSource={employeeData} rowTemplate={this.template.bind(this)} width='auto' height='335'> <ColumnsDirective> <ColumnDirective headerText='Employee Details' width='300' textAlign='Left' /> </ColumnsDirective> </GridComponent> </div> </div>); } } Sample link: https://stackblitz.com/edit/react-ka9ixk?file=index.js Please get back to us, if you need further assistance. Regards, Thavasianand S.
Q: Reusable expression Given a query with a Where clause CollectionA.Where(a => a.Prop1 == val1 && a.Prop2 == val2) and another query with a similar Where clause but the properties are linked via the Reference. CollectionB.Where(b => b.Reference.Prop1 == val1 && b.Reference.Prop2 == val2) For functions this does work: Func<A, bool> f1 = a => a.Prop1 == val1 && a.Prop2 == val2; Func<B, bool> g1 = b => f1(b.Reference); For expressions this doesn't work: Expression<Func<A, bool>> f2 = a => a.Prop1 == val1 && a.Prop2 == val2; Expression<Func<B, bool>> g2 = b => f2(b.Reference); // <-- Method name expected. I would like to reuse the expression in my queries using a specification. Like this: Specification specification = new Specification(val1, val2) CollectionA.Where(specification.ToExpression()); CollectionB.Where(specification.ToExpression(x => x.Reference));: public class Specification { private readonly int val1; private readonly long val2; public Specification(int val1, long val2) { this.val1 = val1; this.val2 = val2; } public Expression<Func<A, bool>> ToExpression() { return x => x.Prop1 == val1 && x.Prop2 == val2; } public Expression<Func<B, bool>> ToExpression<B>(Expression<Func<B, A>> navigate) { // ? } } How to implemented this method? Additionally I would like this to work on not only a binary 'and' expression but on any expression (i.e. any combination depth and type of parameters). (e.g. a => a.Prop1 == val1 && a.Prop2.Prop2a == val2a && a.Prop2.Prop2a == val2a) but basically it is just implementing the thing I try to do with function g2 above. A: You can't directly call the other expression f2(b.Reference). And it would be futile to create an expression that compiles and invokes f2. What you actually want to do is compose the expressions. Make a new expression that represents one expression chained to the other. The expression you're missing is actually just the argument selector that gets an A from a B like this: b => b.Reference; Here's a handy Compose method (similar to this one) to help chain them together. class A { public int Prop1 = 1; public int Prop2 = 2; } class B { public A Reference; } class Program { static Expression<Func<A, C>> Compose<A, B, C>( Expression<Func<A, B>> fAB, Expression<Func<B, C>> fBC) { var arg = Expression.Parameter(typeof(A)); return Expression.Lambda<Func<A, C>>( Expression.Invoke(fBC, Expression.Invoke(fAB, arg)), arg); } static void Main(string[] args) { int val1 = 1; int val2 = 2; Func<A, bool> f1 = a => a.Prop1 == val1 && a.Prop2 == val2; Func<B, bool> g1 = b => f1(b.Reference); Expression<Func<A, bool>> f2 = a => a.Prop1 == val1 && a.Prop2 == val2; Expression<Func<B, A>> argSelect = b => b.Reference; var g2 = Compose<B, A, bool>(argSelect, f2); A objA = new A(); B objB = new B() { Reference = objA }; var g2Compiled = g2.Compile(); Console.WriteLine(g2Compiled.Invoke(objB)); // Demonstrate that it's connected to our local variable val2 = 3; Console.WriteLine(g2Compiled.Invoke(objB)); } }
Q: Como cargar datos de una URL en ajax Quiero cargar opciones un select usando ajax. La url de donde quiero cargar las opciones es de esta url: https://www.etnassoft.com/api/v1/get/?get_categories=all Soy nuevo en ajax y estoy haciendo esto: <script type="text/javascript"> $(function() { //SELECT OPTION $.ajax({ type: 'GET', https:www.etnassoft.com/api/v1/get/?get_categories=all, dataType: 'json', //data: $(this).serialize(), success: function(response) { console.log(response); //$('#lCategorias').html(response); //console.log(response); //console.log(1); // for (i = 0; i < response.length; i++) { // $("#sCompany").append( // '<option value='response['idCompany']'>'response['Name']'</option>'; // ) // } } }); }); <form class="container-fluid"> <select id='lCategorias' name="lCategorias" class="search-select"> <option id="resp"></option> <!--<option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Joseph Swanson</option> <option value="4">Glenn Quagmire</option> </select>--> </form> <br> <div id="txtHint"><b>Person info will be listed here...</b></div> Me puedn aconsejar por favor y gracias. A: Una de las mil formas i mas sencillas seria de esta manera @SantySteinS $(document).ready(function(){ var api = 'https://www.etnassoft.com/api/v1/get/?get_categories=all'; $.ajax({ url: api, type: 'GET', cache: false, async: true, processData: false, contentType: 'application/json', beforeSend: function () { }, success: function (data) { data = JSON.parse(data) $('#combo').children().remove(); for(var a = 0; a < data.length; a++){ $('#combo').append('<option value="'+ data[a].category_id +'">' + data[a].name + '</option>'); } } }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="combo"></select>
Q: SafeConfigParser.read() with file object instead of string I'm using Click to pass in an argument that is a file name. This file name is meant to be used by ConfigParser.SafeConfigParser.read() to read an ini file. Unfortunately, Click passes in a file object which read() cannot handle. Is there a way to allow read() to take a file object or can Click be configured to not open the file (but still do the checks)? A: Note: I found out that ConfigParser has a method for reading file handles specifically. It is called readfp(self, fp, filename=None). This if probably a better answer. I'll leave my old answer below, if someone should be interested in that solution. You can get the filename from the filehandle using the name property. This can be passed to ConfigParser.SafeConfigParser.read(). Small example just printing out the filename: import click @click.command() @click.argument('filehandle', type=click.File('rb')) def print_filename(filehandle): print "File name: %s" % filehandle.name if __name__=="__main__": print_filename()
Q: I am not Getting where can i do correlation using Jmeter in my application. I ma new to Jmeter Our application login is related to Google authentication. While i am recording script using Blaze meter it is working fine. I ma importing same file into the Jmeter. If i am doing the execution using this script it is getting fail. I came to know the we need to correlate the Barer token. I am new to Jmeter and i am not sure where it is generating Token. Image for sample script A: One screenshot is not enough to help you, you'd better ask your network administrator and/or application developers which auth protocol of Google Identity Platform is being used under the hood, what is the authorization flow and how the token can be obtained. As long as you don't need to test the identity platform itself it should be possible to assign a static non-expiring token for the user which you can add to your tests via the HTTP Header Manager and that would be it. In case if it's not possible you will have to go the "hard" way, reference material can be found: * *How to Run Performance Tests on OAuth Secured Apps with JMeter *How to Load Test OpenId Secured Websites
Q: Using DataPoints with @Before in Unit Is there a way in JUnit that I could replace my @Before method to @Theory so that it could use DataPoints. Actually I want the @Before method to be called with different values, a functionality that @Theory provides using Data points. A: Can't you do that with parameterized tests? See the example at https://github.com/junit-team/junit/wiki/Parameterized-tests, and just replace @Test with @Before to set up different values in the @Before method.
Q: Does there exist a mathematical expression consisting of all mathematical expressions? The set of all mathematical expressions consist of all analytic expressions, closed-form expressions, algebraic expressions, polynomial expressions, and arithmetic expressions. Do we run into Russell's paradox when talking about a set whose elements are all possible mathematical expressions? or a mathematical expression consisting or equaling all possible mathematical expressions? If there existed a mathematical expression consisting of all mathematical expressions then it must contain itself and because we can do subtraction on mathematical expressions, would we reach a contradiction? Similarly, Does there exist a function whose terms are all the functions ever possible? A: No. A mathematical expression is a finite string of symbols constructed according to certain rules. The symbols and rules vary depending on the system you are working in, but that doesn't change the argument. I have seen it best developed for Peano Arithmetic in the context of Gödel's proof. You can do PA with about a dozen symbols. Gödel defines a mapping from strings of symbols to natural numbers and defines a function that tells you whether a number represents a string of symbols that is a legal sentence according to the rules of PA. You can't have a mathematical expression that consists of all mathematical expressions because the first has to be finite and the second is countably infinite. In PA you can't (easily) talk about sets, but in ZFC you can. ZFC can define the set of Gödel numbers of legal ZFC mathematical expressions. It is a countably infinite set, but there is no reason it should contain itself so there is no Russell's paradox.
Q: how to use "where" in the List like c# in android I need to select multiple items. I need the numbers greater than 50. I do not know how to write this code. Sample C # code defines me what I need.Is this supported in Android? List<int> _numbers=new ArrayList<Integer>(); _numbers.add(111); _numbers.add(54); _numbers.add(25); _numbers.add(552); _numbers.add(58); // like c# code : _numbers.where(d=>d>=50); A: Iterate though your list and put the values greater than 50 into another list. You can get the integers greater than 50 with an if-clausel: List<int> xxxx = new ArrayList<Integer> for(int value : _numbers){ if(value > 50) xxxx.add(value ) }
Q: Convert array of objects into an array of values from that object I have the following documents in my collection: { "archives" : [ { "colour" : "red", "default" : true }, { "colour" : "green", "default" : false } ] } { "archives" : [ { "colour" : "yellow", "default" : true } ] } I want to project the colour value from the archive objects as follows: { "archives" : [ "red", "green" ] } { "archives" : [ "yellow" ] } My proposal My best attempt at this has been this query: db.test.find({}, { 'archives': { '$map': { 'input': '$archives', 'in': '$archives.colour' } } }) But it's returning an array of arrays with redundant information, like so: { "archives" : [ [ "red", "green" ], [ "red", "green" ] ] } { "archives" : [ [ "yellow" ] ] } So what would be the correct query to give the result I need, preferably on the database side, and as efficient as possible? A: You can use aggregation framework: $unwind $group db.test.aggregate([ { "$unwind": "$archives" }, { "$group": { "_id": "$_id", "archives": { "$push": "$archives.colour" } } } ]) Playground And if you don't want the _id in the output, you can exclude it by adding an additional $project stage: db.test.aggregate([ { "$unwind": "$archives" }, { "$group": { "_id": "$_id", "archives": { "$push": "$archives.colour" } } }, { "$project": { _id: 0 } } ]) A: Why not simply this: db.test.aggregate([ { $set: { archives: "$archives.colour" } } ]) If you like to use $map, then is would be this one. You missed the $$this variable: db.test.aggregate([ { $set: { archives: { "$map": { "input": "$archives", "in": "$$this.colour" } } } } ]) or db.test.aggregate([ { $set: { archives: { "$map": { "input": "$archives.colour", "in": "$$this" } } } } ])
Q: Summarizing data-frame with NA I have 3 different class of mutation such as "CNA" "MUTATIONS" "STRUCTURAL_VARIANT" f <- dput(e) structure(list(track_name = c("AR", "ASCL1", "ATOH1", "PRDM1", "DLX1", "DLX2", "EPAS1", "ETV2", "EYA2", "FOXG1", "FOXC2", "GATA1", "GATA2", "GATA3", "GATA4", "GATA6", "GBX1", "GLI2", "GLI3", "MNX1" ), track_type = c("CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA", "CNA"), `TCGA-AB-2929` = c("amp_rec", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Amplification", NA, NA, NA, NA, NA, NA, NA, NA), aml_ohsu_2018_1408 = c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_), aml_ohsu_2018_1992 = c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame")) This gives me data-frame as such track_name track_type `TCGA-AB-2929` aml_ohsu_2018_1408 aml_ohsu_2018_1992 <chr> <chr> <chr> <chr> <chr> 1 AR CNA amp_rec NA NA 2 ASCL1 CNA NA NA NA 3 ATOH1 CNA NA NA NA 4 PRDM1 CNA NA NA NA 5 DLX1 CNA NA NA NA 6 DLX2 CNA NA NA NA 7 EPAS1 CNA NA NA NA 8 ETV2 CNA NA NA NA 9 EYA2 CNA NA NA NA 10 FOXG1 CNA NA NA NA 11 FOXC2 CNA NA NA NA 12 GATA1 CNA Amplification NA NA 13 GATA2 CNA NA NA NA 14 GATA3 CNA NA NA NA 15 GATA4 CNA NA NA NA 16 GATA6 CNA NA NA NA 17 GBX1 CNA NA NA NA 18 GLI2 CNA NA NA NA 19 GLI3 CNA NA NA NA 20 MNX1 CNA NA NA NA This is of my small subset. For each sample there are first column contains gene and the second column contain the mutation class. I m trying to find the mutation distribution of each gene in those class across the samples. My column after the second column contains various mutation such as Amplification,Inframe Mutation (putative passenger),Deep Deletion,Missense Mutation (putative passenger) which are distributed across each column of the samples. In my example data-frame I have one such observation GATA1 CNA Amplification Im doing this table(Store2df$track_name, Store2df$track_type) %>% prop.table() %>% round(2) Is there in better method/ways to summaries? A: Not necessarily a better way but if you are using dplyr you can do this - library(dplyr) e %>% count(track_name, track_type) %>% mutate(n = round(prop.table(n), 2)) This will return data in long format.
Q: Change HTTPS Wordpress using Docker NGINX I have a Wordpress website using Docker and works fine. I'm trying configure HTTPS and not works. I changed the siteurl and home into the wp_options table. I'm trying use this tutorial, but it's not working (results We were unable to establish a secure connection with this site 80.241.208.103 has sent an invalid response. ERR_SSL_PROTOCOL_ERROR): https://websitesetup.org/http-to-https-wordpress/ Look this configuration: NGINX: server { server_name brau.io www.brau.io; root /var/www/brau.io; location / { proxy_pass http://80.241.208.103:8083/; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/brau.io-0002/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/brau.io-0002/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = brau.io) { return 301 https://$host$request_uri; } # managed by Certbot server_name brau.io www.brau.io; listen 80; return 404; # managed by Certbot } wp_config.php if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') $_SERVER['HTTPS']='on'; if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST']; } .htaccess # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule> Any ideas?
Q: ios_command: Connection type ssh is not valid for this module Ansible raw command can work via SSH, but this playbook cannot work with the same Cisco command show version. It is giving this error message, related to SSH: fatal: [192.168.1.15]: FAILED! => {"changed": false, "msg": "Connection type ssh is not valid for this module"} Here is the inventory under inventory/host-file [routers] 192.168.1.15 [routers:vars] ansible_network_os=ios ansible_user=admin ansible_password=admin ansible_connection=network_cli And the playbook playbooks/show_version.yml --- - name: Cisco show version example hosts: routers gather_facts: false tasks: - name: run show version on the routers ios_command: commands: show version | incl Version register: output - name: print output debug: var: output.stdout_lines Here is my file structure . ├── ansible.cfg ├── hosts ├── inventory │   └── host-file └── playbooks └── show_version.yml I do run the playbook with the command below, from the folder playbooks ansible-playbook show_version.yml Is this a SSH issue? Can anyone share some experience? A: According your error message Connection type ssh is not valid for this module at least the variable ansible_connection wasn't set with a value as it should. A minimal working example from a running environment --- - name: Cisco show version example hosts: routers gather_facts: false vars: # for execution environment ansible_connection: ansible.netcommon.network_cli ansible_network_os: cisco.ios.ios ansible_become: yes ansible_become_method: enable tasks: - name: Gather only the config and default facts cisco.ios.ios_facts: gather_subset: - config - name: Show facts debug: msg: "{{ ansible_facts.net_version }}" In respect to the given comments, maybe you can add a debug task in your playbook - name: Show 'ansible_*' values debug: msg: - "{{ ansible_network_os }}" - "{{ ansible_connection }}" - meta: end_play to see what gets actually loaded.
Q: Handling '$' in Table name when using hibernate tools to do code generation I am using Hibernate tools (eclipse plugin) to do code generation to create the POJO & th hbm, But table name that contain '$' will make problem. e.g., for table 'Buyer$Souce' will generate a class named 'Buyer.souce' is there any way to solve this problem? I want to just ignore the '$' ,e.g., 'Buyer$source' generate 'BuyerSouce.java' Thanks A: I don't think there is a directly with the Hibernate Tools Plugin. You could generate everything except Buyer$Source and manually code the class for BuyerSource. Use an annotation (or modify the hbm) to set the table name. @Entity @Table(name="Buyer$Souce") public class BuyerSouce { //... }
Q: Running simple Python script for QGIS from outside I would like to run a few small and simple Python scripts for QGIS (Mac) from "outside" of QGIS (e.g. Sublime Text). With outside I mean in this context, either the normal os command line (terminal.app) or even better, directly out of Sublime Text (text-editor), but definitely not via the inbuilt QGIS Python Console. I've read through various tutorial e.g. http://www.qgis.org/pyqgis-cookbook/intro.html#python-applications and I am able to get a reference to the QGIS app, but unfortunately not to qgis.utils.iface or something else deeper. This little code snippet should for instance print out the name of the active layer ... here is what I have: import sys sys.path.append("/Applications/QGIS.app/Contents/Resources/python") from qgis.core import * import qgis.utils print "helo" # console output: helo QgsApplication.setPrefixPath("/Applications/QGIS.app/", True) QgsApplication.initQgis() print QgsApplication # console output: <class 'qgis.core.QgsApplication'> print qgis.utils.iface # = console output: none aLayer = qgis.utils.iface.activeLayer() print aLayer.name() QgsApplication.exitQgis() I am just looking for a quick and easy way to shoot scripts out of a comfortable text-editor to QGIS. A: Update for Nathan's option 4: (Windows, QGIS 2.18 Las Palmas) To print QGIS help document, qgis --help To open QGIS, load a project, then, run a python script. qgis --nologo --project c:/path/to/projfile.qgs --code c:/path/to/code.py These commands should run on OSGeo4W Shell without problems. QGIS 3.18 also works. Always use this command to see all the available options and the syntax of them:- qgis --help A: You can't get a reference to the iface object here because it doesn't exist in this context. The iface (QgisInterface) object is a convenience object for plugins, or scripts running inside QGIS, to access the main objects e.g. the map canvas, legend, composer, etc, and only exists when the main application is running. When you create a standalone Python script using the QGIS APIs none of this stuff exists because you are making your own mapping application. There are three different situations: * *A QGIS plugin *A script that runs inside QGIS (not a plugin) for automation *Standalone app using QGIS APIs 1. and 2. have access to iface, the last one doesn't. For 3 if you want to create a script that opens a layer in a map canvas you would do this after QgsApplication.initQgis() map = QgsMapCanavs() layer = QgsVectoryLayer('path.shp','myshapefile','ogr') map.setLayerSet([layer]) However if you are really looking for something like 2 then you can just write this in your script editor from qgis.core import * from qgis.gui import * import qgis.utils qgis.utils.iface.activeLayer() but this has to be run inside QGIS for qgis.utils to work. That can be done by putting the script on PATH and running import scriptname in the Python console or by using the ScriptRunner plugin. Note the following isn't QGIS yet There is a number 4 that hasn't been added yet, and hopefully will be in the future, and that is the option to run QGIS with a commandline arg to say run this code. For example: qgis --code=mycodefile.py Plugin logging (version 1.8) You can use the QgsMessageLog class to log information to the QGIS log window. The yellow exclamation mark in the bottom right corner. from qgis.core import * log = lambda m: QgsMessageLog.logMessage(m,'My Plugin') log('My message') or without using lambda QgsMessageLog.logMessage('My message', 'My Plugin') I prefer the lambda based one as it is shorter and less typing any time you want to log something. A: I think Nathan W's answer is out of date. I was able to run QGIS (version 2.6) python scripts from the command line (Nathan's option 4) using the following commands. man qgis qgis -nologo --project /path/foo.qgs --code /path/foo.py
Q: AngularJS SEO Meta and Description Tags I have started to make some AngularJS applications for mobiles and recently client has asked to ship one of these to the Desktop to making it responsive multi-channel architecture. I have seen this on a few sites: <meta name="keywords" ng-if="Meta.keywords" ng-attr-content="{{ Meta.keywords }}"> <meta name="description" ng-if="Meta.description" ng-attr-content="{{ Meta.description }}"> When Google or other robots scan this can they see the output HTML keyword data and also this applies to content and title tags. How good is Angular for SEO? A: Google processes JavaScript so content generated within it is available to googlebot to crawl. Other crawlers have not stated whether they can or not so until it is confirmed they do it should be assumed that this content will not be available to them. FYI, meta tags have no effect on rankings. The meta description might be displayed in Google's search results but not always. A: <meta name="keywords" ng-if="Meta.keywords" ng-attr-content="{{ Meta.keywords }}"> <meta name="description" ng-if="Meta.description" ng-attr-content="{{ Meta.description }}"> hint: to avoid having this in your index.html file (e.g. for non js crawlers or if something breaks with js) simply put a directive to your head tag. this is the cleanest way. look at this directive which renders canonical, keywords, meta into your head tag. to map your own directive to the head-tag set restrict: 'E', and angular.module('app').directive('head', ['$rootScope' function($rootScope) { --- i have sites where google definitely listens to the contents of my angular-rendered canonical tag (no html snapshots, plain single page application with a sitemap).
Q: Windows 8.1 control that opens the appbar? In the Internet Explorer App, there is a little bar on the bottom that is used to open the app/command bar. It also shows up in the mail app: I have just a simple CommandBar at the moment, which is completely hidden until the user right-clicks or swipes from the bottom: <Page.BottomAppBar> <CommandBar> <AppBarButton x:Name="Button_Save" Icon="Save" Label="Save" Click="Button_Save_Click"/> <CommandBar.SecondaryCommands> <AppBarButton Icon="Crop" Label="Canvas Size"></AppBarButton> <AppBarButton Label="Grid Size" Icon="ViewAll"></AppBarButton> </CommandBar.SecondaryCommands> </CommandBar> </Page.BottomAppBar> Rather than just creating my own control, it would be nice if there was one that already existed for me to use. I don't know the name of this "Command bar grip" so I cant seem to find much information on it. If it does exist, what's the name of it? And if not, any ideas on how to make one? I would probably just use a rectangle and add the little "..." on the side. I have seen it in some apps apart from Microsoft, but there appears to be no information on the control. A: There isn't a standard control for this. The in-box AppBar on Windows 8.1 either hides or shows and doesn't have an intermediate hint mode. You can implement it yourself by creating a panel at the bottom of the page animating its position so it is either fully visible or shows only the ellipses. This can be done fairly easily by setting visual states for the visible and hinting states and switching to the visible state when the control receives focus or pointer input. As Robert Hartley suggests, the ellipses can be found in the Segoe UI Symbol font at 0xE10C ("More") <TextBlock Text="&#xE10C;" HorizontalAlignment="Right" VerticalAlignment="Top" FontFamily="Segoe UI Symbol"/> I haven't used it, but Dave Smits provided a sample AppBarHint control which implements a hinting app bar for Windows. You might want to take a look at how he did that too.
Q: Drop all connections for a specific IP that aren't from a single source in iptables on EC2 I'm using amazon EC2 and looking to set up some firewall rules for my scenario. EC2 is strange - in case you aren't familiar with EC2 - amazon offers elastic IP addresses that resolve to private IP addresses - there is no such thing as a truly public IP. I've got two private IP addresses attached to a single ethernet interface (eth0), and two corresponding elastic IPs that resolve to the private IPs to allow public access to the machine. For the second private IP, I only want to accept packets if they come from a particular source (my IP address). I can NOT use multiple ethernet interfaces to solve this, as I can only simulate multiple public IP addresses from the same interface (eth0) on EC2. I've got standard rules in-place that allow ALL connections to commonly-used public ports from any source. -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT -A INPUT -p tcp -m tcp --dport 587 -j ACCEPT -A INPUT -p tcp -m tcp --dport 110 -j ACCEPT -A INPUT -p tcp -m tcp --dport 995 -j ACCEPT -A INPUT -p tcp -m tcp --dport 143 -j ACCEPT -A INPUT -p tcp -m tcp --dport 993 -j ACCEPT -A INPUT -p tcp -m tcp --dport 9001 -j ACCEPT How can I add a rule further in the chain, that will further inspect the destination for EVERY request, and simply drop the request if the source (-s) isn't the IP address I specify? I basically want to use a second IP address along with iptables and apache2 to only serve certain pages to me when I'm on my home network. Thanks! A: Add iptable rule at the top to allow yourself access: INPUT -s home_ip_address -j ACCEPT Add rule at the end to block all access to 2nd private ip: INPUT -d 2nd_private_ip -j DROP
Q: Implementing mutexes? I'm trying to implement mutexes inside my standard library but I'm not getting anywhere with them. I know that it is a bad idea to try to implement something that you do not necessarily understand, but I have to, since compiling an existing threading library (such as uClibc) is impossible for this platform. Are there any "explain it to me like I'm 5" things for mutexes? Or are there any "simple to follow" implementations? All of the pthread implementations I've seen so far are impossible to follow. My implementation of the locking function is provided below. I'm pretty sure there is something seriously wrong with it, since I have no idea what I'm doing. int pthread_mutex_lock(pthread_mutex_t *pmutex) { OSMutex* mutex = GetOSMutex(pmutex); /* Decrement the mutex counter */ OSAtomicDecrement32(&(mutex->count)); if (mutex->count < -1) { /* Contended, wait for the mutex to be released. */ lnkLog("mutex %p already held (n=%d), waiting for stuff to change", mutex, mutex->count); futex$LINUX(&(mutex->data), FUTEX_WAIT, MUTEX_MAGIC, NULL, NULL, 0); lnkLog("mutex %p was released", mutex); return 0; } else { /* Not contended. Acquire the mutex. */ lnkLog("locking %p", mutex); mutex->data = MUTEX_MAGIC; return 0; } } P.S. If you're wondering about the futexes, I'm using the Linux kernel. A: http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html Look into __sync_lock_test_and_set You have to have hardware support for doing atomics. GCC builtins are a good start.
Q: how to use h2load to do benchmark for http2 server based on Netty? When I use default no-tls protocol h2c of h2load, I find netty doesn't do upgrade because h2load doesn't send upgrade request. How can I do benchmark for clear-text http2 benchmark for my netty http2 server? Look forward to your reply. This statement return false : io.netty.handler.codec.http.HttpServerUpgradeHandler#isUpgradeRequest A: io.netty.handler.codec.http2.CleartextHttp2ServerUpgradeHandler.PriorKnowledgeHandler Peek inbound message to determine current connection wants to start HTTP/2 by HTTP upgrade or prior knowledge
Q: bibliographies and siunitx in pandoc I'm using pandoc to convert my TeX file in a .docx file. The formatting, equations and images work very well, but I have some issues: * *References to images don't show properly. They show only the name of the image file, not the number, neither in the caption nor inside the text. *The bibliography doesn't show; the numbers of the references papers ([1], [2] etc.) also don't show. *In the LaTeX file I'm using the siunitx package; pandoc doesn't convert syntax like \SI{5}{mm}. Can anyone help me?
Q: Xamarin Tabbed Page not showing Content trying to learn more about Tabbed Pages with i've built a very simple App containing three content Pages with a code like this: public class Page1 : ContentPage { public Page1() { Content = new StackLayout { Children = { new Label { Text = "Hello Page1" } } }; } protected override void OnAppearing() { base.OnAppearing(); System.Diagnostics.Debug.WriteLine("Page 1 On Appearing"); } protected override void OnDisappearing() { base.OnDisappearing(); System.Diagnostics.Debug.WriteLine("Page 1 Disappearing"); } } The Main Page looks like this: public class MainPage : TabbedPage { public MainPage() { var page1 = new Page1(); page1.Title = "Page1"; var page2 = new Page2(); page2.Title = "Page2"; var page3 = new Page3(); page3.Title = "Page3"; Children.Add(page1); Children.Add(page2); Children.Add(page3); } } Now when i click on a new tab, the OnDisappearing() method of the old tab is called, as well as the OnAppearing() method of new tab, BUT the content of the new page is not shown. It remains the content of the old page. To show the content of the new page i have to click again on the tab. Does anybody has experienced this kind of behaviour? Best regards, Marco
Q: 8/16/32 Bits of microcontrollers I am new to the field of embedded systems. Recently I was learning about the differences between different bit size (8, 16, 32) microcontrollers. What I found was that the size of bit indicates the memory addressing capacity, data bus and address bus size etc. Every other website has almost the same explanation. But still I could not find answer to some of the questions. To list them: * *Is it really necessary for the address and data bus to be the same size as the bit size of the micro. *What is it that will become fixed for sure for a given bit sized microcontroller? *Do a microcontroller have have same address bus for all the memories (RAM, flash, EEPROM) and if so, is it the choice of manufacturer to allot any size to any type of memory out of the available addresses? *Say there's an 8 bit microcontroller. So it can adress 2^8 memory locations (that's what I figured out, I am not sure). If each register is 8 bit it means a total of (2^8)*8 =2048 bits of memory. That's not even close to the 32kb of flash inside most of them. What blunder am I making? A: The "bit size" of a CPU typically refers to the size of its general-purpose registers (or its primary register, in parts with nonuniform registers). For example, the MC68000 is generally considered a 32-bit architecture as its registers are all 32 bits wide -- even though it has a 16-bit data bus and a 20-bit address bus. (This means that it must make two memory accesses to write a single register to memory. The top 4 bits of an address register are simply ignored, which is a bit of an oddity.) The sizes of the address and/or data busses connecting the processor to its various memories are often different, either from the size of registers or even from each other. In more complex architectures, it is not uncommon for the same memory to even be accessible over multiple data busses of different widths. A: It is not necessary that data bus and address bus widths are same in a micro-controller. For eg, in the good old 8051, data bus is of 8 bits and address bus is of 16 bits. '8-bit' in the naming convention of a micro-controller is quite abstract. Mostly it refers to the size of registers inside 8. All general purpose registers inside 8051 are 8-bit registers except PC and DPTR. You have to go thru the data sheet. So you are wrong in your assumptions about 4th question, because '8-bit micro-controller' doesn't always mean that it has an address/data bus of 8-bit. Need more info to clarify it. 2,3 are purely architectural based. Yea, you can have different buses inside. Big topic. A: Well that's a lot of learning books. You should get one in the library. * *No, usually the address bus is wider than data bus. This is very basic knowledge on processors. *Depends on architecture of the processor. Newer ARM RISC processors have many address buses. Learn: von Neuman VS. Harvard architecture. For example the MCU can have separate internal RAM and FEPROM bus and yet 3rd external address and data bus *As stated in 2. it can have more internal buses, depends on architecture. *You're wrong. For 32kB space you would need an address bus at least (or exactly) 15 bit wide. source of the image A: (3) Do a microcontroller have have same address bus for all the memories...? Not necessarily. Unlike a larger computer system where an operating system can load and execute different programs on-the-fly, the application code in a microcontroller typically is burned into the flash memory at the factory, and then is seldom or never changed after that. There is no need, therefore, for one microcontroller program to be able to treat the instructions of another program like data. A system which, like some of the world's earliest stored-program computers, has separate data paths for fetching instructions and, for accessing data, can be simpler (cost less/use less power) than a so-called Von Neumann machine that stores instructions and data in the same memory space.
Q: Windows automatically installing updates and rebooting despite group policy I have been trying to find any pertinent articles online regarding this problem, but haven't uncovered much that is helpful. For a couple months now I have been plagued with workstations and servers rebooting themselves for updates, despite the fact that my group policy explicitly tells it to not. The results of rsop.msc and gpresult /R both pull computer policies that configure the windows updates as such: --Configure Automatic Updates - Enabled '2' (Notify for download and install) --No Auto-restart with logged on users for scheduled.... - Enabled I should note that there are no errors on the computer configuration policies for rsop.msc - but there are errors on the user configurations. Are there some log files that might indicate why these policies are being ignored? Is it possible Microsoft is continuously releasing patches that are ignoring policy due to a critical security nature? Thank you, and I apologize if this issue has been recorded somewhere else and I just haven't found it due to a failure of google-fu. Update 1: I am able to run gpupdate /force without any incident and it says it completed successfully. Windows logs reciprocate this message by saying that the gp objects were detected and applied. Looking further through the logs I see an entry indicating that the server was being forced to restart in 30 minutes to complete installing a security update for IE 11 (among others, I am finding now). Digging even more I am finding that the registry settings for Windows Update are all over the place - some configured correctly, some set to something that would seem conflicting: However, the "most important" setting "NoAutoRebootWithLoggedOnUsers" is clearly set to be enabled and stop it from rebooting while I was logged in.
Q: Selected Item is not showing in Andoid spinner I'm new in android programmin so,please pardon if i did silly mistake I want the list of users from Users collection and display in the spinner, so i can select i've tried almost everything but didn't resolve the issue, where is the problem? problem in my java code or in xml file? #Here is my XMl:# <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <RelativeLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2"> <TextView android:layout_width="match_parent" android:text="Assigned User" android:textStyle="bold" android:textAppearance="@style/TextAppearance.AppCompat.Medium" android:layout_margin="15dp" android:layout_height="wrap_content"/> </RelativeLayout> <RelativeLayout android:layout_weight="4" android:layout_height="wrap_content" android:layout_width="0dp"> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:textColor="@color/black" android:spinnerMode="dropdown" android:id="@+id/edt_assigned_user_task" /> </RelativeLayout> </LinearLayout> #Here is my code ---># when i select the item from the list the selected item dissappeared spinnerUser = myview.findViewById(R.id.edt_assigned_user_task); spinnerProject =myview.findViewById(R.id.edt_project_task); populateSpinnerUser(); private void populateSpinnerUser() { final List<String> mUserList = new ArrayList<>(); db.collection("Users").get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(DocumentSnapshot documentSnapshot: task.getResult()){ Log.d("TAG", documentSnapshot.getId() + " => " + documentSnapshot.getData()); String user = documentSnapshot.getString("uID"); mUserList.add(user); } } adapter.notifyDataSetChanged(); } }); ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, mUserList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerUser.setAdapter(adapter); } spinnerUser.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String userName = parent.getItemAtPosition(position).toString(); spinnerUser.setSelection(position); Toast.makeText(parent.getContext(),userName,Toast.LENGTH_SHORT); } @Override public void onNothingSelected(AdapterView<?> parent) { } });
Q: Non-Scrolling Fragment in a ViewPager inside CoordinatorLayout I am using a ViewPager in a CoordinatorLayout (from latest version of Design Library) in an Activity. Some fragments for this ViewPager have layouts such as RecyclerView or NestedScrollView, but some just cannot scroll given their small content. <android.support.design.widget.AppBarLayout android:id="@+id/tabanim_appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/MyTheme"> <android.support.v7.widget.Toolbar android:id="@+id/tabanim_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/> <android.support.design.widget.TabLayout android:id="@+id/tabanim_tabs" android:layout_width="match_parent" android:layout_height="wrap_content" /> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/tabanim_viewpager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> But in one Fragment with a FrameLayout as the root view, I need to have a button that is anchored to the bottom, but it appears to be drawn off-screen. To be able to see it, I need to add a bottom padding equals to the height of the Toolbar. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Home screen" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:layout_width="match_parent" android:layout_height="70dp" android:layout_gravity="bottom" android:gravity="center" android:text="@string/brand" android:textColor="@color/brandColor" android:textSize="20sp" /> </FrameLayout> Likewise, a layout_gravity set to 'center' on an element does not appear to be in the center of the visible area for this fragment. My understanding is that CoordinatorLayout is only intented to work with scrolling contents, is that correct ? So that using only regular ViewGroup such as FrameLayout, RelativeLayout, LinearLayout for the ViewPager fragments will have their bottom part drawn off-screen ? In that case, do I need to remove this button from this fragment layout and move it to the activity layout containing the CoordinatorLayout ? It needs to be shown only on the first fragment. A: From reference to this answer The below worked for me Extend scrollview behavior public class MyBehavior extends AppBarLayout.ScrollingViewBehavior { private View layout; public MyBehavior() { } public MyBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) { boolean result = super.onDependentViewChanged(parent, child, dependency); if (layout != null) { layout.setPadding(layout.getPaddingLeft(), layout.getPaddingTop(), layout .getPaddingRight(), layout.getTop()); } return result; } public void setLayout(View layout) { this.layout = layout; } } Specify that to viewpager <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> </android.support.design.widget.AppBarLayout> <org.nsu.myapplication.VerticalViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_behavior="your.domain.name.MyBehavior" /> </android.support.design.widget.CoordinatorLayout> and in onCreate of activity CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) viewPager.getLayoutParams(); MyBehavior behavior = (MyBehavior) lp.getBehavior(); behavior.setLayout(viewPager); A: The issue is caused by intercepting of touch events from ViewPager by parent container. Parent scroll container listens for scroll touch events and if there vertical shift it steals the event from it's child views. It just thinks that user wants to scroll the parent container vertically Below is the code resolve it import android.content.Context; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.ScrollView; public class CustomScrollView extends ScrollView { private GestureDetector mGestureDetector; private View.OnTouchListener mGestureListener; public CustomScrollView(Context context, AttributeSet attrs) { super(context, attrs); mGestureDetector = new GestureDetector(context, new YScrollDetector()); setFadingEdgeLength(0); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev); } class YScrollDetector extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return Math.abs(distanceY) > Math.abs(distanceX); } } } Use this class instead of your ViewPager <(your packagename).CustomScrollView android:id="@+id/tabanim_viewpager" android:layout_width="match_parent" android:layout_height="match_parent"/>
Q: Arrays as Class Variables, Set in Constructs in Class Is there a way to pass an array to a class/object construct and access/return it or manipulate it? Code: $affiliates = array( "clickbank" => "clickbankdata", "meepbank" => array( "meepbankdata" => "meep" ) ); class Affiliate { public $affiliates = array(); public function __construct($array) { $this->affiliates = $array; } public function getAffiliatesArray() { return $this->$affiliates; } } $main = new Affiliate($affiliates); print_r($main->getAffiliatesArray()); A: public function getAffiliatesArray() { return $this->$affiliates; } should be public function getAffiliatesArray() { return $this->affiliates; } A: Replace return $this->$affiliates; ^ |-------- Remove This With return $this->affiliates;
Q: Ternary operator logic I need to convert a double number to an integer based on a condition, but when I use the ternary operator I get some weird results. I wrote this simple program to test my logic but I cannot understand what's going on. #include <stdio.h> int main() { double n = 50.0; printf("%i\n", (int)n); printf("%i\n", ((1) ? (int)n : n)); printf("%i\n", ((1) ? n : (int)n)); printf("%i\n", ((0) ? (int)n : n)); printf("%i\n", ((0) ? n : (int)n)); return 0; } I expected to get the following output: 50 50 0 0 50 But the output I got was: 50 0 0 0 0 A: When the 2nd and 3rd operands to the ternary operator have different types, they are automatically converted to the same type, using the usual arithmetic conversions. So doing a cast on just one of the operands doesn't have the effect you expect -- (int) n will be cast back to double and that will be the type of the ternary expression. This will then be passed to printf, and you'll get undefined behavior because you're trying to print a double using %i format, which expects an int. If you want the type of the argument to depend on the condition, you need to use an ordinary if. For instance, this is what you were apparently trying to accomplish in your first ternary example: if (1) { printf("%i\n", (int) n); // valid } else { printf("%i\n", n); // invalid } A: You have tripped over two dark corners of the C language at once. * *Given double n, the "usual arithmetic conversions" cause (ANYTHING ? (int)n : n) and (ANYTHING ? n : (int)n) to both have type double. That is, if the (int)n branch is taken, the value n is converted to int and then back to double. *printf("%i\n", (double)whatever) provokes undefined behavior. This is because printf relies on its format string to know the types of its variadic arguments. If you tell it to print an int but you pass a double it will look in the wrong place for the value to print. Because of (1), (2) affects all four of the printf statements containing a ternary expression, not just the ones where the cast-to-int branch was not taken. I don't understand what you were trying to accomplish with (condition ? (int)n : n), so I can't tell you what you should have done instead. A: In the standard for the 'conditional operator', it says: If both the second and third operands have arithmetic type, the result type that would be determined by the usual arithmetic conversions, were they applied to those two operands, is the type of the result. Since you have int and double as the types, the result of the conditional is always double, so you get whatever garbage you get when you print it with the wrong format — which is invoking undefined behaviour and a bad idea
Q: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase I am building a Flutter application and I have integrated Firebase, but I keep getting this error when I click on a button either to register, login or logout. I have seen other people have asked the same question, but none seems to work for me. I am using Flutter and Android Studio. How can I fix this problem? This is an excerpt of my code class HomeScreen extends StatefulWidget { @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.red, body: Center( child: Container( child: RaisedButton( onPressed: () { FirebaseAuth.instance.signOut().then((value) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => LoginScreen())); }); }, child: Text("Logout"), ) ) ) ); } } Below is the thrown exception ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════ The following FirebaseException was thrown while handling a gesture: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() When the exception was thrown, this was the stack: #0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5) #1 Firebase.app (package:firebase_core/src/firebase.dart:52:41) #2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47) #3 _HomeScreenState.build.<anonymous closure> (package:cosytok/screens/home.dart:20:28) #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19) #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38) #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24) #7 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11) #8 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5) #9 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7) #10 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9) #11 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12) #12 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9) #13 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8) #14 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18) #15 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7) #16 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19) #17 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22) #18 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7) #19 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7) #20 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7) #24 _invoke1 (dart:ui/hooks.dart:267:10) #25 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5) (elided 3 frames from dart:async) Handler: "onTap" Recognizer: TapGestureRecognizer#f0104 ════════════════════════════════════════════════════════════════════════════════════════════════════ ════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════ The following FirebaseException was thrown while handling a gesture: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() A: Peter's answer is perfect!! But if you still get an error in your code and following the Flutter Firebase codelab, note that those tutorials are outdated as of August 2020 and not updated yet. You need to do many other changes like: * *replace .data with .data() *replace updateData with update A: Flutter Web with Firebase If you are using Flutter Web with Firebase make sure you have the SDKs installed in the body tag of your ./web/index.html <script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-analytics.js"></script> Furthermore, make sure you call firebase.initializeApp(...) with the configuration parameters in the index.html as well. <script> // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional var firebaseConfig = { apiKey: "AIz...", authDomain: "...", databaseURL: "https://<project-name>.firebaseio.com", projectId: "...", storageBucket: "<project-name>.appspot.com", messagingSenderId: "...", appId: "...", measurementId: "..." }; firebase.initializeApp(firebaseConfig); firebase.analytics(); </script> At last configure firebase as described in Peter Haddad's answer: void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } A: Since Flutter versions 2.8, FlutterFire can now be initialized from Dart on all platforms using the Firebase.initializeApp function. There's a more simple and quicker way to initialize a firebase project, instead of downloading the .json and .plist file from the firebase console and placing them into your Flutter project folders which can result in several warnings. This is a problem I've experienced several times and here's how I solved it. After creating your project in the firebase console steps here and installed the Firebase CLI here, please proceed with the following steps: You can skip step 1 and jump to step 4 if you've already configured your firebase project with flutterfire configure. * *From your project root terminal, command: $ flutterfire configure // This requires the Firebase CLI to work. *Select firebase project by hitting return or enter. *insert the bundle ID. You can get this by right clicking the ios folder > then click'Open in xcode'. The Bundle Identifier will appear in the right white panel and you'll have to type this in the terminal manually when prompted. ** Proceed to step 5 if you already have the firebase_core plugin installed. ** *Install the latest version of the firebase_core plugin by running this command from your project root directory: $ flutter pub add firebase_core // Adds to pubspec.yaml *Add imports to the main file: import 'package:firebase_core/firebase_core.dart'; // import 'firebase_options.dart'; // Generated file *Update your main function to initialize firebase with this async function: Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); runApp(const YourAppName()); } See the FlutterFire documentation for more information. A: Starting Since August 17 2020 All Firebase versions have been updated and now you have to call Firebase.initializeApp() before using any Firebase product, for example: First, all Firebase products now depend on firebase_core version (0.5.0+), therefore you need to add it in the pubspec.yaml file: dependencies: flutter: sdk: flutter firebase_core : ^0.5.0 # cloud_firestore: ^0.14.0 other firebase dependencies Then you have to call Firebase.initializeApp(): First Example import 'package:flutter/material.dart'; // Import the firebase_core plugin import 'package:firebase_core/firebase_core.dart'; void main() { runApp(App()); } class App extends StatelessWidget { @override Widget build(BuildContext context) { return FutureBuilder( // Initialize FlutterFire future: Firebase.initializeApp(), builder: (context, snapshot) { // Check for errors if (snapshot.hasError) { return SomethingWentWrong(); } // Once complete, show your application if (snapshot.connectionState == ConnectionState.done) { return MyAwesomeApp(); } // Otherwise, show something whilst waiting for initialization to complete return Loading(); }, ); } } Second Example with Firestore: import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: FirstRoute(title: 'First Route'), ); } } class FirstRoute extends StatefulWidget { FirstRoute({Key key, this.title}) : super(key: key); final String title; @override _FirstRouteState createState() => _FirstRouteState(); } class _FirstRouteState extends State<FirstRoute> { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("test"), ), body: FutureBuilder( future: getData(), builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) { if (snapshot.connectionState == ConnectionState.done) { return Column( children: [ Container( height: 27, child: Text( "Name: ${snapshot.data.data()['name']}", overflow: TextOverflow.fade, style: TextStyle(fontSize: 20), ), ), ], ); } else if (snapshot.connectionState == ConnectionState.none) { return Text("No data"); } return CircularProgressIndicator(); }, )); } Future<DocumentSnapshot> getData() async { await Firebase.initializeApp(); return await FirebaseFirestore.instance .collection("users") .doc("docID") .get(); } } Third Example: Initialize it in initState() then call setState() which will call the build() method. @override void initState() { super.initState(); Firebase.initializeApp().whenComplete(() { print("completed"); setState(() {}); }); } Fourth Example: Initialize it in the main() method after calling WidgetsFlutterBinding.ensureInitialized(); void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } Note: You only have to call initializeApp() once A: You need to add await Firebase.initializeApp(); which is a Future. Do it inside the dart file that is running your Firebase function like below: import 'package:firebase_core/firebase_core.dart'; ... Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MaterialApp()); } A: If you still have the problem when you leave the app to the main screen, you could add this to whatever .dart file using Firebase: class App extends StatelessWidget { final Future<FirebaseApp> _initialization = Firebase.initializeApp(); @override Widget build(BuildContext context) { Or in the case of a StatefulWidget: import 'package:flutter/material.dart'; // Import the firebase_core plugin import 'package:firebase_core/firebase_core.dart'; void main() { runApp(App()); } class App extends StatefulWidget { _AppState createState() => _AppState(); } class _AppState extends State<App> { // Set default `_initialized` and `_error` state to false bool _initialized = false; bool _error = false; // Define an async function to initialize FlutterFire void initializeFlutterFire() async { try { // Wait for Firebase to initialize and set `_initialized` state to true await Firebase.initializeApp(); setState(() { _initialized = true; }); } catch(e) { // Set `_error` state to true if Firebase initialization fails setState(() { _error = true; }); } } @override void initState() { initializeFlutterFire(); super.initState(); } @override Widget build(BuildContext context) { // Show error message if initialization failed if(_error) { return SomethingWentWrong(); } // Show a loader until FlutterFire is initialized if (!_initialized) { return Loading(); } return MyAwesomeApp(); } } For more information, check this link. A: This is the way to initialize firebase in 2022 First of all, Install FlutterFire with this link ==> Flutter Fire Installation Link After installing FlutterFire, you'll need to add these lines of code in your lib/main.dart file import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; Then edit your Main Function as done below void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform,); runApp(MyApp()); } This can change in the future, so refer to this link for the latest implementation reference below Initializing FlutterFire# A: In most cases this problem is observed after upgrading the project from older Flutter version to null safety. These things should be checked: Ensure you have firebase-core in pubscpec.yaml Import firebase core: import 'package:firebase_core/firebase_core.dart'; Init Firebase before any call - preferably inside main.dart so it is executed before any other implementation: WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); From offical documentation. A: Dart-only initialization (Recommended) * *Initialize Firebase on all platforms using CLI. *No need to add any native code. *No need to download any Google services file. * *Install FlutterFire CLI dart pub global activate flutterfire_cli *(Optional) Add the following line to your ~/.zshrc file and save it export PATH="$PATH":"$HOME/.pub-cache/bin" *Run the configure: flutterfire configure *Press enter to configure all the platforms *You should now have a lib/firebase_options.dart file. Import this file in your main.dart and use Firebase.initializeApp. import 'firebase_options.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // This is the last thing you need to add. await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(...); } Migrating to Dart-only initialization: If you already have an existing application, you can migrate it in the following ways. * *Android: * *Delete google-services.json file from <flutter-project>/android/app: *Delete the following line in <flutter-project>/android/build.gradle file *Delete the following line in <flutter-project>/android/app/build.gradle file *iOS Open <flutter-project>/ios/Runner.xcworkspace file in Xcode and delete the GoogleService-Info.plist file from the Runner. *macOS Open <flutter-project>/macos/Runner.xcworkspace file in Xcode and delete the GoogleService-Info.plist file from the Runner. More information can be found here A: I needed to reconfigure the Firebase app with FlutterFire cli. https://firebase.flutter.dev/docs/cli * *Install firebase-tool via NPM: npm install -g firebase-tools *Install flutterfire cli: dart pub global activate flutterfire_cli *Run this command to configure firebase in your project: flutterfire configure Follow the above link and initialise as follows: void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); runApp(const MyApp()); } As its await call, The app will show splash screen and Firebase may not initialise so I proceeded next with another FutureBuilder for home screen to make sure Firebase app is initialised before I use FirebaseAuth. home: FutureBuilder( future: Firebase.initializeApp(), builder: (context, snapshot) { if (snapshot.hasError) { return Text(snapshot.error.toString(), style: TextStyle(fontSize: 10)); } if (snapshot.connectionState == ConnectionState.done) { return StreamBuilder( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { return snapshot.hasData ? Home() : AuthPage(); }, ); } else { return Text(''); } }) A: If you followed Peter's answer and are still getting the same error, check to make sure anything else you have in your main function comes after the await Firebase.initializeApp() call, like so: void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true); FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError; runApp(MyApp()); } A: Since August 2017, all Firebase services have been updated so that you have to call Firebase.initializeApp() in your main before you can use any of the Firebase products, for example: If you want to use the firebase_core plugin in a flutter application, then in your pubspec.yaml file add the firebase_core as below dependencies: flutter: sdk: flutter firebase_core: ^1.19.1 Then call the Firebase.initializeApp(): in your app. same as something below: import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } A: * *Add to pubspec.yaml firebase_core : *add to main.dart import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } A: First, add this dependency: firebase_core : Second: in the project main function, add these two lines and make the function async: void main() async { // These two lines WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); // runApp(MyApp()); } Now you can use Firebase normally in any file or widget in the project. The FutureBuilder widget will work either, but you must add it every time you want to access Firebase. A: You can initialize in the main.dart file as well like this using FutureBuilder. future: Firebase.initializeApp(), Look at this example. void main() { runApp(App()); } class App extends StatelessWidget { @override Widget build(BuildContext context) { return FutureBuilder( // Initialize FlutterFire future: Firebase.initializeApp(), builder: (context, snapshot) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'NEWSAPI.org', home: SplashScreen(), routes: <String, WidgetBuilder>{ SPLASH_SCREEN: (BuildContext context) => SplashScreen(), },); }, ); } } A: you neeed to add await FirebaseApp.initializeApp() in main function remember to add await in main function A: I wanted to comment. But this issue have lot of trails. For my case. I was initializing Injection Container Before Firebase. Hierarchy needs to be check. Hive.init(directory.path); await Firebase.initializeApp();// before await di.init(); A: For Flutter Users If you've set Firebase correctly, do not forget to add await before Firebase.initializeApp(); That is mainly the problem with that Exception. And since it's a Future, do this: Future<void> main() async { await Firebase.initializeApp(); A: On my case, I added web support to my existing project. The one thing which solved the issue is, In the web/index.html file Changing the verison of all the firebase sdk imports from 9.6.6 to 8.10.0 Snippet <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app-check.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-storage.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"></script> <script> var firebaseConfig = { .... } A: If you are working on a project in which the firebase_core was preconfigured and then you are trying to add new packages it will give that error. You have to first remove firebase_core: from pubsec.yaml and then save the file and reconfigure it through flutter pub add firebase_core and then flutterfire configure. Then you can add any new packages. A: Initialise with firebase options void main() async{ WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform).catchError((e){ print(" Error : ${e.toString()}"); }); } A: Make sure you are using the right/official version of the firebase package. I was using: firebase_core_dart: <version-number> at: https://pub.dev/packages/firebase_core_dart instead of the official firebase_core: <version-number> at https://pub.dev/packages/firebase_core Using the first option, I got the initialized when using: await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ).whenComplete( () => print('FIREBASE INITIALIZED================>')); but the authentication failed with the error message described by the OP. A: Try the below code. It will resolve the issue for both IOS and Android. import 'dart:io'; import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); if (Platform.isIOS) { await Firebase.initializeApp( options: const FirebaseOptions( apiKey: "found in your google service-info.plist", appId: "found in your google service-info.plist", messagingSenderId: "found in firebase", projectId: "found in firebase"), ); } else { await Firebase.initializeApp(); } runApp(const MyApp()); } A: In my case it was because for the Web version you have to manually add stuff in the index.html file, not only the .js dependency, but the configuration. See Web Installation. We tend to forget that for most stuff Flutter is compiled to the target without the need to change anything target-specific, but in this case one must add the configuration for each target. A: Use This for flutter : const firebaseConfig = { apiKey: "", authDomain: "", projectId: "", storageBucket: "", messagingSenderId: "", appId: "", measurementId: "" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.getAnalytics(app); Instead of this const firebaseConfig = { apiKey: "", authDomain: "", projectId: "", storageBucket: "", messagingSenderId: "", appId: "", measurementId: "" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); A: Initialise with firebase options void main() async{ WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform).catchError((e){ print(" Error : ${e.toString()}"); }); } like this A: The problem for me was I initialized it without "await": void main() async { WidgetsFlutterBinding.ensureInitialized(); Firebase.initializeApp(); The correct way is: void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp();
Q: How can I save a shortcut's icon? I am trying to write a program where I can open any program from a folder of shortcuts on my desktop. As part of the gui, I would like the shortcut's icon to be visible next to its name. Any idea how I can get a shortcuts icon from a directory, without manually finding and saving it? I tried to find the shortcut's file properties to see where its icon was, but I couldn't find any code to help me see it. A: Using pywin32 according to http://timgolden.me.uk/pywin32-docs/win32com.shell_and_Windows_Shell_Links.html from win32com.shell import shell import pythoncom shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink ) shortcut.QueryInterface( pythoncom.IID_IPersistFile ).Load( filepath ) Get the Icon path and ID: >>> print(shortcut.GetIconLocation()) ('', 0) If manually changed: ('%ProgramFiles%\\Blender Foundation\\Blender 3.4\\blender-launcher.exe', 0) So we need to get the EXE path to resolve the Icon if the path is empty. See docs for the ENUM supplied. And I manually pretty printed the result. >>> print(shortcut.GetPath(shell.SLGP_UNCPRIORITY )) ( 'C:\\Program Files\\Blender Foundation\\Blender 3.4\\blender-launcher.exe', ( 32, pywintypes.datetime(2022, 12, 20, 2, 2, 52, tzinfo=TimeZoneInfo('GMT Standard Time', True)), pywintypes.datetime(2023, 1, 16, 10, 30, 16, 724000, tzinfo=TimeZoneInfo('GMT Standard Time', True)), pywintypes.datetime(2022, 12, 20, 2, 2, 52, tzinfo=TimeZoneInfo('GMT Standard Time', True)), 0, 1079520, 0, 0, 'blender-launcher.exe', '' ) ) The extra data seems to be from the EXE, see MS Windows Docs: https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-win32_find_dataa
Q: PCRE regex matching strings that look like an annotation I'm trying to parse custom annotations out of a document block retrieved via ReflectionClass::getDocComment. I figured using preg_match_all with the regex "/(@\w+)\s+([^@]+)/" with the PREG_SET_ORDER flag would do what I want. I tested it in an interactive shell and it seemed golden. What I didn't think to test was the @author tag from phpdoc. The optional email address for the author tag (obviously) has an @ in it. I can't use \b inside the character class of the regex to require the @ be at the start of a word because it won't be interpreted as a word boundary character but a backspace. I need some inspiration! Update: Thank you Arne, your answer gave me some ideas but I prefer a general solution to one that adapts only to the specific issue at hand. I've come up with two possibilities so far. The first one only works if there is a trailing space which there currently is but I'm not sure that I can guarantee there always will be. The second one appears to work regardless but is much less ... finessful. First regex is "/(@\w+)\s+((?:[^@]\S*?\s+)*)/" Second regex is "/(@\w+)\s+((?:[^@]\S*?(?:\s|$)+)*)/" Perhaps someone can help me clean up the second one. A: \b as word boundary can't be used inside a character class, because \b as word boundary is a pattern, not a character. I guess you want to match something like @import file @author firstname lastname <[email protected]> and your interested in the annotations name and parameter. If you simply extend your character family to not contain the < and append an optional pattern for the mail address, you may end up with something like this: (@\w+)\s+([^<@]+(?:<[^>]+>)?) I don't know if this matches all annotations of your interest, but may be it's a starting point.
Q: Align ImageView with EditText horizontally I'm trying hard to find a way of aligning an EditText and an ImageView properly on Android. I keep getting this result: The XML part is quite simple: <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:gravity="center" android:scaleType="centerInside" android:src="@drawable/android" android:visibility="gone" /> <EditText android:id="@+id/edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true" /> </LinearLayout> I've also tried many of the suggestions below, including PravinCG's (RelativeLayout with alignTop/alignBottom): <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/edittext" android:layout_alignTop="@+id/edittext" android:scaleType="centerInside" android:src="@drawable/android" android:visibility="visible" /> <EditText android:id="@+id/edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/image" android:hint="@string/username" android:singleLine="true" /> </RelativeLayout> But the result is exactly the same. I've tried playing with the EditText's background padding, intrinsic height, but to no avail. The EditText's background drawable is different among Android versions/ROMs, and I want to support them all. How can I make this alignment pixel perfect on any android version (and style)? A: Finally found a suitable solution that scales across different Android versions/ROMs/styles. The main problem is that the EditText's background drawable itself has transparent padding: Also, I've noticed this transparent padding varies a lot between different Android versions/ROMs/styles (stock ICS, for instance, has no transparent padding at all). In a mid-way conclusion, my original code properly alignes my ImageView with my EditText. However, what I really want is to align my ImageView with the visible part of the EditText's background. To achieve this, I scan a Bitmap I create from my EditText's background drawable. I scan it top-bottom and bottom-up to find the amount of fully transparent lines and use those values as top/bottom padding for my ImageView. All this consistently takes less than 5ms on my N1. Here's the code: if(editor.getBackground() != null) { int width = editor.getWidth(); int height = editor.getHeight(); Drawable backgroundDrawable = editor.getBackground().getCurrent(); // Paint the editor's background in our bitmap Bitmap tempBitmap = Bitmap.createBitmap(width, height, Config.ARGB_4444); backgroundDrawable.draw(new Canvas(tempBitmap)); // Get the amount of transparent lines at the top and bottom of the bitmap to use as padding int topPadding = countTransparentHorizontalLines(0, height, tempBitmap); int bottomPadding = countTransparentHorizontalLines(height-1, -1, tempBitmap); // Discard the calculated padding if it means hiding the image if(topPadding + bottomPadding > height) { topPadding = 0; bottomPadding = 0; } tempBitmap.recycle(); // Apply the padding image.setPadding(0, topPadding, 0, bottomPadding); } private int countTransparentHorizontalLines(int fromHeight, int toHeight, Bitmap bitmap) { int transparentHorizontalLines = 0; int width = bitmap.getWidth(); int currentPixels[] = new int[width]; boolean fullyTransparentLine = true; boolean heightRising = (fromHeight < toHeight); int inc = heightRising ? 1 : -1; for(int height = fromHeight; heightRising ? (height < toHeight) : (toHeight < height); height+=inc) { bitmap.getPixels(currentPixels, 0, width, 0, height, width, 1); for(int currentPixel : currentPixels) { if(currentPixel != Color.TRANSPARENT && Color.alpha(currentPixel) != 255) { fullyTransparentLine = false; break; } } if(fullyTransparentLine) transparentHorizontalLines++; else break; } return transparentHorizontalLines; } And it works like a charm! A: You need to use RelativeLayout with android:align_bottom and android:align_Top attribute. I am not writing the code though. A: Have you tried the setCompoundDrawables() methods for the EditText. You can try setting the intrinsic bounds using the setBounds() method on the Drawable or by using the setCompoundDrawablesWithInstrinsicBounds() method. This should work on all devices. A: To get rid of the padding in the EditText, just use a custom image as background... rectangle with some shadow is enough... or whatever you like... and assign the background to the EditText using android:background="@drawable/myBackground" A: use android:layout_centerInParent = true for edit text and see weather it works? A: remove editText's and ImageView's properties android:gravity="center" and set gravity property of linearlayout to center_vertically. A: I used a quick workaround by simply moving the EditText down 2dp by simply adding the following to the EditText: android:layout_marginBottom="-2dp" android:layout_marginTop="2dp"
Q: Access Corev15.css file of Online SharePoint Office 365 As far as my understanding, In SharePoint on-premise version of SharePoint corev15.css file is located at c:\program files\common files\microsoft shared\web server extensions\ _layouts\15\1036\styles\corev15.css path in local system. But I was trying to find corev15.css file in office 365 in SharePoint online, and I could not find this file in any folder. I can check this file in browser by entering correct URL in browser, But I can not make any change as far as I could not open it by physical location. One of the my office mate advice me to copy the content of corev15.css file into another file and upload it to style Library and overwrite all css again. Is it correct way to do so? A: Do you want to add some customization to your current css? If yes, then it's better to create new css with your additional css settings and upload it into Site Asset. And go to Site Master Page Settings -> Alternate CSS URL -> choose your uploaded css -> OK You dont have to copy content of corev15.css. It will added automatically into your current css EDITED you can go to http://yoursite/_layouts/15/1033/styles/Themable/corev15.css to see your corev15.css
Q: Christoffel symbols and torsion of the connection Suppose we have a metric tensor $g_{\mu \nu}$ defining a Riemannian manifold. The Christoffel symbols related to this metric are not tensors. Their difference anyway is a tensor: $$T^k_{ij}=\Gamma^k_{ij}-\Gamma^k_{ji}$$ This $T^k_{ij}$ defines the 'Torsion' of the connection. Why is there this link between this tensor and the torsion? Thanks in advance A: In advance: I know this should be a comment, but I do not have the required repution,yet... Idk what you are asking for. It is pretty much how torsion is defined in this setting, at least in local coordinates, which is evident from $$T(X,Y):= \nabla_XY -\nabla_YX -[X,Y] $$ and $$\nabla_{\partial_{i}}\partial_j = \sum_{k=1}^n \Gamma^k_{ij} \partial_k$$ where $\{\partial_1,...,\partial_n\}$ are the vector fields corresponding to some (local) coordinate system $\{x_1,...,x_n\}$. By definition, $T$ is the Torsion Tensor. So... Is your Question: * *If this equation is ineed correct? *If $T$ is indeed a Tensor? *If this definition of $T$ is equivalent or related to some other definition? *Something completly different?
Q: Reporting Cell based on number from another cell I have a group of 400 proxies in column C. I would like a formula that would report a random list of the proxies (from C) to column A and B based on the number in cell A1 and B1 A1 B1 C1:C400 10 20 Proxy List So based on the number in Row 1 I would like a list to pop up of that many proxies and in a random order. So if A1 is 10 I would like 10 proxies from the proxy like to pop up starting in A2. Also I would like it so that these proxies are not used more than one time so there will not be the same proxies in Row A and B. In each column I would like the proxies from AF to be placed there based on the amounts in row 1 and I would like these proxies to only be used one time. A: One way to accomplish this without VBA is to use the formula you have an conditional formatting. Since RANDBETWEEN is a volatile function you can use conditional formatting to show any duplicate values that show up and then just re-calculate the list until you do not see duplicates. See below: A2 and B2 have the formula: =IF(ROW()<=A$1,INDEX($C:$C,RANDBETWEEN(1,COUNTA($C:$C)),1),"") change to B$1 for column B Drag these formulas down for as many rows as you think you may need to cover for a given value in A1 and / or B1. Then apply the following rules for Duplicate Values in Conditional Formatting Wizard. First rule is for cells that contain blanks (make sure to step Stop If True - this will stop blank cells from showing as duplicates`. Then if duplicates exist in column A and/or B, you will see them easily: CAVEAT - this works well with smaller numbers in A1 and B1, but fails a bit with larger numbers of IP addresses, since the randomness of the formula creates more duplicates.
Q: FFTW: Inverse of forward fft not equal to original function I'm trying to use FFTW to compute fast summations, and I've run into an issue: int numFreq3 = numFreq*numFreq*numFreq; FFTW_complex* dummy_sq_fft = (FFTW_complex*)FFTW_malloc( sizeof(FFTW_complex)*numFreq3 ); FFTW_complex* dummy_sq = (FFTW_complex*)FFTW_malloc( sizeof(FFTW_complex)*numFreq3 ); FFTW_complex* orig = (FFTW_complex*)FFTW_malloc( sizeof(FFTW_complex)*numFreq3 ); FFTW_plan dummyPlan = FFTW_plan_dft_3d( numFreq, numFreq, numFreq, orig, dummy_sq_fft, FFTW_FORWARD, FFTW_MEASURE ); FFTW_plan dummyInvPlan = FFTW_plan_dft_3d( numFreq, numFreq, numFreq, dummy_sq_fft, dummy_sq, FFTW_BACKWARD, FFTW_MEASURE ); for(int i= 0; i < numFreq3; i++) { orig[ i ][ 0 ] = sparseProfile02[ 0 ][ i ][ 0 ]; //img. part == 0 orig[ i ][ 1 ] = sparseProfile02[ 0 ][ i ] [ 1 ]; } FFTW_execute(dummyPlan); FFTW_execute(dummyInvPlan); int count = 0; for(int i=0; i<numFreq3; i++) { double factor = dummy_sq[ i ][ 0 ]/sparseProfile02[ 0 ][ i ][ 0 ]; if(factor < 0) { count++; } } std::cout<<"Count "<<count<<"\n"; FFTW_free(dummy_sq_fft); FFTW_free(dummy_sq); FFTW_destroy_plan(dummyPlan); FFTW_destroy_plan(dummyInvPlan); (Here sparseProfile02[0] is of type FFTW_complex*, and contains only positive real data.) Since we have dummy_sq = IFFT(FFT(sparseProfile02[ 0 ])), we must have dummy_sq = n^3*sparseProfile02. But this is true only some of the time; in fact, values on the dummy_sq grid are negative whenever corresponding values on the sparseProfile02 grid are zero (but not vice-versa). Does anyone know why this is happening? A: At the risk of dabbling in necromancy, you should note in the fftw docs (here) that it expressly states that fftw does not normalize, thus the result of the inverse transform of a previously transformed signal will be the original signal scaled by 'n' or the length of the signal. Could be the problem. A: The FFTs (forward and inverse) have rounding error, and I think this is what's biting you. In general, you shouldn't expect a zero to stay exactly zero through your process (although it could be zero for trivial test cases). In your test loop, is fabs(dummy_sq[i][0] - numFreq*numFreq*numFreq*sparseProfile02[0][i][0]) large relative to the magnitude of your data? As a really simple (pathological) example with just a 1D FFT of size 2 with real values: ifft(fft([1e20, 1.0])) != [2e20, 2.0] The 1.0 is lost in the 1e20 with a double precision FFT. It's also possible you're getting some NaNs for factor when you divide by a zero sample in sparseProfile02.
Q: ldd can't find one library, but links to the other ones in same directory I'm trying to deploy my application. I created a deb package. If I install it on the same machine that I built it, everything works. When I try to use a deb package generated by my CI setup on gitlab, I encounter problems. After installing, here's the error: $ NCATests NCATests: error while loading shared libraries: libQt5Core.so.5: cannot open shared object file: No such file or directory This is surprising, because I installed a conf file (/etc/ld.so.conf.d/nca.conf) with a path /usr/lib/nca and ran a post-install ldconfig. To make sure that this worked I ran: $ ldconfig -v (snip) /usr/lib/nca: libpcre2-16.so.0 -> libpcre2-16.so.0.7.1 libicuuc.so.63 -> libicuuc.so.63.1 libicui18n.so.63 -> libicui18n.so.63.1 libicudata.so.63 -> libicudata.so.63.1 libdouble-conversion.so.1 -> libdouble-conversion.so.1.0 libQt5Widgets.so.5 -> libQt5Widgets.so.5.11.3 libQt5Test.so.5 -> libQt5Test.so.5.11.3 libQt5Gui.so.5 -> libQt5Gui.so.5.11.3 libQt5DBus.so.5 -> libQt5DBus.so.5.11.3 libQt5Core.so.5 -> libQt5Core.so.5.11.3 libNCACore.so.1 -> libNCACore.so.1.3.8 (snip) And yet: $ ldd /usr/bin/NCATests linux-vdso.so.1 (0x00007fffc1081000) libNCACore.so.1 => /usr/lib/nca/libNCACore.so.1 (0x00007f049a368000) libQt5Test.so.5 => /usr/lib/nca/libQt5Test.so.5 (0x00007f049a310000) libQt5Core.so.5 => not found libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f049a0f0000) libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f0499d60000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f04999c0000) libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f0499790000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f0499390000) /lib64/ld-linux-x86-64.so.2 (0x00007f049a600000) libQt5Core.so.5 => not found libQt5Core.so.5 => not found The library is there: $ ll /usr/lib/nca | grep 5Core lrwxrwxrwx 1 root root 20 Mar 15 08:20 libQt5Core.so.5 -> libQt5Core.so.5.11.3 lrwxrwxrwx 1 root root 20 Mar 15 08:20 libQt5Core.so.5.11 -> libQt5Core.so.5.11.3 -rw-r--r-- 1 root root 5200168 Mar 15 08:20 libQt5Core.so.5.11.3 Both files are 64 bit: $ file /usr/bin/NCATests /usr/bin/NCATests: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=8adef8969237a756f7d2743121f87791c8ceafc2, not stripped $ file /usr/lib/nca/libQt5Core.so.5.11.3 /usr/lib/nca/libQt5Core.so.5.11.3: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=b126d6e6aafc3d2d6e2b7904786b22e7e84e252e, for GNU/Linux 3.17.0, stripped Ubuntu version 18.04. What is the problem here? A: sudo apt install libqt5core5a There is your missing libary
Q: log4j.properties Simple question log4j.logger.mylog = debug, A1 I want to know 2 things, * *what is "mylog" here? *what is "A" here? A: mylog is the logger name (which you pass to Logger.getLogger() in your code; you can also pass a class in which case the logger name is the name of the class). In fact in a configuration file it can be the prefix for a logger name - so in this case, any logger name beginning with mylog will use appender A1 (and possibly others). A1 is the appender name (which is configured elsewhere in the configuration file) - this determines where the actual output goes. The "short introduction to log4j" is a good starting point for this sort of thing. A: * *mylog is the name of your logger (as requested in your code using Logger.getLogger("mylog"). *A1 is the id of an appender that you defined in your configuration.