source
sequence
text
stringlengths
99
98.5k
[ "english.stackexchange", "0000019967.txt" ]
Q: What does "Google-fu" mean? Exact Duplicate: Can anyone tell me what the suffix “-fu” stands for in the following sentence? I was reading an article on MSDN where I found a mention to google-fu. It says, “To search for C++ delimeters and code snippets is going to take a little Google-fu on the reader's part.” what does google-fu mean? A: Google-fu is defined as "skill in using search engines (especially Google) to quickly find useful information on the Internet." It is a somewhat tongue-in-cheek reference to kung-fu, which is generally perceived as requiring a high degree of skill to master in the western hemisphere. In the example sentence you provided, the author is suggesting that the expected results are somewhat difficult to attain and you will need to use diligence when searching. I used a bit of Google-fu to research this answer. A: It means “mastery of Google” or “Googling skill”. It is modelled after kung fu: kung fu (noun): a primarily unarmed Chinese martial art resembling karate. ORIGIN from Chinese gōngfú, from gōng ‘merit’ + fú ‘master.’
[ "stackoverflow", "0027464275.txt" ]
Q: Ruby - incorrect line break within statement still gives result? The distilled script is the following: z1 = (12 - 2) / (5) z2 = (12 - 2) / (5) puts(z1.to_s + " " + z2.to_s) Which gives: $ ruby rubytest.rb 2 -1 Now, I'm aware that the z1 case is the right way to do it, because a hanging operator on the end of the line is interpreted as an automatic continuation of the line. However, I would expect the interpreter to fail-fast on the z2 case, and tell me that the statement is incomplete, or that its second line is nonsensical. But it handles it "just fine" and gives the "-1" answer. Is it trying to appear confident by not admitting it's confused and hoping the bullshit answer will go unnoticed? Could someone explain what is actually happening with the evaluation of z2, why is it "-1", why is there no syntax error, and is there an example where this behaviour is useful (or should we file a request to remove it)? A: It's a feature, but you might think it's a bug at first. It's for the same reason you are able to do this (which is handy many cases): (call_function_1; call_function_2) if some_condition A line feed is interpreted the same as ;. You will notice this evaluates fine for example, and only the last expression is returned, but all expression ARE evaluated none the less: (1 2 3 4 5) => 5 It's the same as (1; 2; 3; 4; 5) => 5 To see that all expressions are evaluated you can try this for example: (puts "A" puts "B" puts "C" 123) A B C => 123 So your example becomes: (12; -2) / 5 Which is the same as: -2 / 5 Which is -1. To make Ruby interpret 12 as an unfinished statement and not a separate statement you can tell Ruby this by adding a line continuation hint \: (12 \ - 2) / 5 => 2
[ "stackoverflow", "0062341878.txt" ]
Q: ASP.NET Authorization without built in functionality I am currently working on some online shop so far so good. The only worry is I don't want to use built-in authorization functions. I want to do something different, to use Global.asax file. To catch Request.RawUrl in Application_BeginRequest so in the moment request is sent and to check for a specific folder if it is requested and to redirect back to log in if it is not authorized. The reason why I don't want to use built-in is because of the database. I want my own custom made database because there is many things I have done that I want to have full control of it. Yes, I saw many tutorials as recommended here before. I have searched for this stuff for a few days already saw many tutorials on how to customize those built-in functionalities. Maybe my question looks complicated but in the end, I will ask simply. Is it safe to intercept each request in Global.asax file? And is it good idea to use Application_BeginRequest or something else? Thank you kindly, everyone. A: It basically depends on your system and business model, if your every request needs to be authorized, then implement the authorization logic in Application_BeginRequest may meet your need. But in practice, I wouldn't recommend you to take this action, because once you do this, if someday you have a feature that can be access without logging in, then you have to find out another way to break this rule. That means your system will lose flexibility. I suggest using Authorization filter, you can inherit AuthorizeAttribute class, and override its methods with your customized authorization logic. For more details: Custom Authorization filter in ASP.NET MVC 5?
[ "stackoverflow", "0009090015.txt" ]
Q: Is there a way to disable the auto-indentation when pasting in Xcode 4? I like the auto-indentation in XCode 4 when coding/typing, but I want to disable this function when I'm pasting the code. So is there a way to have separate settings for the two situations? A: Instead of using a normal paste, use "Paste and Preserve Formatting". It's in the Edit menu, and its shortcut is "Alt+Shift+Cmd+V".
[ "stackoverflow", "0016057869.txt" ]
Q: Setting the size of the plotting canvas in Matplotlib I would like Matplotlib/Pyplot to generate plots with a consistent canvas size. That is, the figures can well have different sizes to accomodate the axis descriptions, but the plotting area (the rectangle within which the curves are drawn) should always have the same size. Is there a simple way to achieve that? The option figsize of pyplot.figure() seems to set the overall size of the figure, not that of the canvas, so I get a different canvas size whenever the axis description occupies more or less space. A: This is one of my biggest frustrations with Matplotlib. I often work with raster data where for example i want to add a colormap, legend and some title. Any simple example from the matplotlib gallery doing so will result in a different resolution and therefore resampled data. Especially when doing image analysis you dont want any (unwanted) resampling. Here is what i usually do, although i would love to know if there are simpler or better ways. Lets start with loading a picture and outputting it just as it is with the same resolution: import matplotlib.pyplot as plt import urllib2 # load the image img = plt.imread(urllib2.urlopen('http://upload.wikimedia.org/wikipedia/en/thumb/5/56/Matplotlib_logo.svg/500px-Matplotlib_logo.svg.png')) # get the dimensions ypixels, xpixels, bands = img.shape # get the size in inches dpi = 72. xinch = xpixels / dpi yinch = ypixels / dpi # plot and save in the same size as the original fig = plt.figure(figsize=(xinch,yinch)) ax = plt.axes([0., 0., 1., 1.], frameon=False, xticks=[],yticks=[]) ax.imshow(img, interpolation='none') plt.savefig('D:\\mpl_logo.png', dpi=dpi, transparent=True) Note that i manually defined the axes position so that spans the entire figure. In a similar way as above you could add some margin around the image to allow for labels or colorbars etc. This example adds a 20% margin above the image, which is then used for plotting a title: fig = plt.figure(figsize=(xinch,yinch/.8)) ax = plt.axes([0., 0., 1., .8], frameon=False, xticks=[],yticks=[]) ax.imshow(img, interpolation='none') ax.set_title('Matplotlib is fun!', size=16, weight='bold') plt.savefig('D:\\mpl_logo_with_title.png', dpi=dpi) So the figure y-size (height) is increased and the y-size of the axes is decreased equally. This gives a larger (overall) output image, but the axes area will still be the same size. It might be nice the have a figure or axes property like .set_scale() to force a true 1-on-x output.
[ "stackoverflow", "0027282938.txt" ]
Q: target_link_libraries and add_dependencies Is there any use case in which target_link_libraries(my-lib x y z) add_dependencies(my-lib x) # this is not just a waste of bytes? If so, can someone explain what it would be? A: In current CMake releases: After some error checking add_dependencies results in a call to Target->AddUtility(). x is added to the list of utilities for my-lib. target_link_libraries does not result in a call to AddUtility, but it does add the arguments to the LINK_LIBRARIES target property. Later, both the content of the LINK_LIBRARIES target property and the list of utilities are used to compute the dependencies of the target in cmComputeTargetDepends. The list of utilities in a target can not be queried at configure time, and is only used at generate time, so the use of add_dependencies with arguments which are libraries already added with target_link_libraries is redundant. A: I don't know what you're particularly interested in... From a conceptual point of view -- I think you're right. It is a waste of bytes. From a CMake documentation point of view -- You should prefer make so to guarantee the correct build order. According to the documentation target_link_libraries, add_dependencies concepts was ideologically split. Such an idea of split dependencies, and linker options is also persisted in the Makefile format in the GNU make tool. target_link_libraries ..Specify libraries or flags to use when linking a given target.. add_dependencies ...Make a top-level <target> depend on other top-level targets to ensure that they build before <target> does... In modern CMake from 3.* you can omit add_dependencies if you will perform linking with an aliased target: add_library(fooLib 1.cpp 2.cpp) add_library(my::fooLib ALIAS fooLib) ... target_link_libraries(fooBin my::fooLib)
[ "stackoverflow", "0022591270.txt" ]
Q: How to iterate in Python? I'm new to Python but I have gone thru the syntax. Here's my scenario: I have two instances of Cursors AllImages & AllAlbums (I'm getting the data from a db & I'm getting them like this: AllImages = Images.find() AllAlbums = Albums.find() ) [Edit: I'm using the PyMongo API] Inside every dictionary in AllAlbums I have an array of numbers called images = [1234,2234,16363] Inside every dictionary in All Images I have a field called _id Here's how both dicts look like: From AllAlbums: { _id:23 images:[1123,6643,4,9087] } From AllImages: { _id:6643} Now, I need to see if this _id is present in images This is what I've written so far: for img in AllImages: for alAl in AllAlbums: alIm = alAl['images'] for qq in alIm: if qq==img['_id']: print 'Here!',img['_id'],' with',alAl['_id'] Now here's what I get for output: The program correctly matches _id = 0 in images for a dictionary in AllAlbums with _id of 69. However, after that (for the rest of the _ids like 1,2,3...8899...9999) it does not enter into the second for loop to iterate. Yes, I know my approach is probably crude and all, but I just need this basic code to run. How do I re-iterate this cursor for AllAlbums ? Apologies if I've not formatted the code properly. I'm on Python 2.7 A: Solution is very simple. I simply made a list out of the cursor instance AllAlbums and was able to re-iterate multiple times. Thanks a lot to those who pointed this out to me (: AllAlbumList = list(AllAlbums)
[ "math.stackexchange", "0000767240.txt" ]
Q: Is $\ \Large\pi^e$ rational? Is the number $\ \Large\pi^e$ rational? A: The answer is unknown (though it seems intuitive to assume that the result will be irrational - just because $\pi$ raised to any rational number other than 0 will be already irrational). Though nothing is for certain. Maybe by some bizarre connection, $e$ and $\pi$ could be established to be 2 faces of the same thing, such that some non-trivial operations on them (like yours) would result in a rational number! The challenge, fundamentally, lies in proving that $\pi$ and $e$ are algebraically independent of one another. I.e. there is no polynomial expression with coefficients which are algebraic numbers (numbers which themselves are roots of polynomials with rational coefficients) equating the 2 numbers. For imagine if there was indeed such a polynomial that equated the 2 - then you could take the numerator of one side, divide both sides by it, and then attain 1 = … where RHS would be a "mixture" of $\pi$ and $e$. Maybe, given that the polynomial "connections" were workable enough, you could find ways to create even more astounding equalities, such as the one you are pondering about. As it turns out, proving the independency of the two numbers is not easy. A: It seems highly likely that $\pi^e$ is irrational, but no one has figured out how to prove it yet.
[ "stackoverflow", "0047705995.txt" ]
Q: JavaScript: Compressing object assignment for different cases I'm trying to set the porperties of an object based on a specific case. I think the following code can be compressed and I'm looking for the best way to go about it. NOTE: I have considered using a switch statement but it results in pretty much the same number of lines. let oNoificationData = {}; if (data.type === 'newUser') { oNotificationData = { title: `${data.user} is online!`, icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`, body: 'A new user has come online', }; } else if (data.type === 'logoff') { oNotificationData = { title: `${data.user} has logged out!`, icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`, body: 'A user has logged out' }; } else if (data.type === "newMsg") { oNotificationData = { title: `new message from ${data.user}`, icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`, body: 'You have a new message!' }; } else if (data.type === "closeRoom") { oNotificationData = { title: `${data.user} has left the chat`, icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`, body: 'Chat user has left' }; } A: So use an object var notifications = { newUser : { title: `${data.user} is online!`, icon:`https://www.gravatar.com/avatar/${sHash}?d=mm`, body: 'A new user has come online', }, logoff : { title: `${data.user} has logged out!`, icon:`https://www.gravatar.com/avatar/${sHash}?d=mm`, body: 'A user has logged out' } } and it is just var obj = notifications[data.type];
[ "stackoverflow", "0036137371.txt" ]
Q: How do I use a private iOS framework from Swift? I want to make use of a private framework on iOS from a Swift app. I am well aware why this is a bad idea, but it will be useful during testing, so App Store limitations are not an issue, and I have quite exhaustively looked into alternatives. What I would like to do is something along the lines of this: dlopen("/Developer/Library/PrivateFrameworks/UIAutomation.framework/UIAutomation".fileSystemRepresentation,RTLD_LOCAL); let eventsclass = NSClassFromString("UIASyntheticEvents") as? UIASyntheticEvents.Type eventGenerator = eventsclass!.sharedEventGenerator() as! UIASyntheticEvents The problem is that this will cause a linker error: Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_UIASyntheticEvents", referenced from: type metadata accessor for __ObjC.UIASyntheticEvents in Test.o If I link the framework directly rather than use dlopen(), it will work fine on the simulator, but will fail to build for an actual device, as the framework supplied in the SDK is for the simulator only and will not link during a device build. I have tried doing these calls in Objective-C instead, in case it was just the .Type cast that was causing problems, but this does not help. If I access the returned object from Swift, I still get the same error. I suppose I could create a wrapper in Objective-C that just passes all the calls to the class straight through, but this seems excessive. Is there a more elegant solution to this problem? A: I found one solution which requires some manual work, but does work in pure Swift. The trick is to create an @objc protocol in Swift which matches the Objective-C methods, then do an unsafe cast to that protocol type. In my case, the protocol looks like this: @objc protocol UIASyntheticEvents { static func sharedEventGenerator() -> UIASyntheticEvents //@property(readonly) struct __IOHIDEventSystemClient *ioSystemClient; // @synthesize ioSystemClient=_ioSystemClient; var voiceOverStyleTouchEventsEnabled: Bool { get set } var activePointCount: UInt64 { get set } //@property(nonatomic) CDStruct_3eca2549 *activePoints; // @synthesize activePoints=_activePoints; var gsScreenScale: Double { get set } var gsScreenSize: CGSize { get set } var screenSize: CGSize { get set } var screen: UIScreen { get set } var onScreenRect: CGRect { get set } func sendPinchCloseWithStartPoint(_: CGPoint, endPoint: CGPoint, duration: Double, inRect: CGRect) func sendPinchOpenWithStartPoint(_: CGPoint, endPoint: CGPoint, duration: Double, inRect: CGRect) func sendDragWithStartPoint(_: CGPoint, endPoint: CGPoint, duration: Double, withFlick: Bool, inRect: CGRect) func sendRotate(_: CGPoint, withRadius: Double, rotation: Double, duration: Double, touchCount: UInt64) func sendMultifingerDragWithPointArray(_: UnsafePointer<CGPoint>, numPoints: Int32, duration: Double, numFingers: Int32) func sendPinchCloseWithStartPoint(_: CGPoint, endPoint: CGPoint, duration: Double) func sendPinchOpenWithStartPoint(_: CGPoint, endPoint: CGPoint, duration: Double) func sendFlickWithStartPoint(_: CGPoint, endPoint: CGPoint, duration: Double) func sendDragWithStartPoint(_: CGPoint, endPoint: CGPoint, duration: Double) func sendTaps(_: Int, location: CGPoint, withNumberOfTouches: Int, inRect: CGRect) func sendDoubleFingerTap(_: CGPoint) func sendDoubleTap(_: CGPoint) func _sendTap(_: CGPoint, withPressure: Double) func sendTap(_: CGPoint) func _setMajorRadiusForAllPoints(_: Double) func _setPressureForAllPoints(_: Double) func moveToPoints(_: UnsafePointer<CGPoint>, touchCount: UInt64, duration: Double) func _moveLastTouchPoint(_: CGPoint) func liftUp(_: CGPoint) func liftUp(_: CGPoint, touchCount: UInt64) func liftUpAtPoints(_: UnsafePointer<CGPoint>, touchCount: UInt64) func touchDown(_: CGPoint) func touchDown(_: CGPoint, touchCount: UInt64) func touchDownAtPoints(_: UnsafePointer<CGPoint>, touchCount: UInt64) func shake() func setRinger(_: Bool) func holdVolumeDown(_: Double) func clickVolumeDown() func holdVolumeUp(_: Double) func clickVolumeUp() func holdLock(_: Double) func clickLock() func lockDevice() func holdMenu(_: Double) func clickMenu() func _sendSimpleEvent(_: Int) func setOrientation(_: Int32) func sendAccelerometerX(_: Double, Y: Double, Z: Double, duration: Double) func sendAccelerometerX(_: Double, Y: Double, Z: Double) func _updateTouchPoints(_: UnsafePointer<CGPoint>, count: UInt64) func _sendHIDVendorDefinedEvent(_: UInt32, usage: UInt32, data: UnsafePointer<UInt8>, dataLength: UInt32) -> Bool func _sendHIDScrollEventX(_: Double, Y: Double, Z: Double) -> Bool func _sendHIDKeyboardEventPage(_: UInt32, usage: UInt32, duration: Double) -> Bool //- (_Bool)_sendHIDEvent:(struct __IOHIDEvent *)arg1; //- (struct __IOHIDEvent *)_UIACreateIOHIDEventType:(unsigned int)arg1; func _isEdgePoint(_: CGPoint) -> Bool func _normalizePoint(_: CGPoint) -> CGPoint //- (void)dealloc; func _initScreenProperties() //- (id)init; } This was converted by hand from a class-dump output. If anyone knows a quicker way to do it, I'd love to know. Once you have this protocol, you can simply do the following: dlopen("/Developer/Library/PrivateFrameworks/UIAutomation.framework/UIAutomation".fileSystemRepresentation,RTLD_LOCAL) let eventsclass = unsafeBitCast(NSClassFromString("UIASyntheticEvents"), UIASyntheticEvents.Type.self) eventGenerator = eventsclass.sharedEventGenerator()
[ "math.stackexchange", "0002484195.txt" ]
Q: Euclid's proof that they are infinity prime numbers Euclid's proof that they are infinity prime numbers look more as a statement then a proof for me. For thing to be even worse, it's example used every time to show the basic proof you can find. If I have understood it good, in nutshell proof is: If this is a prime number it’s good, and we have a new one: N = (p0 · p1 · p2 · … · pn) If not, adding 1 we will create a new one: N = (p0 · p1 · p2 · … · pn)+1 Example: Let’s imagen we know only for first two primes 3 and 5. With this formula N = 3·5 = 15 (15 is not prime, you can divide it with 3 and 5) N = (3·5)+1 = 16 (it’s not prime) What I doing wrong? Here is explanation already given, but can someone do relation between actual explanation and example i posted. A: The argument is the following. Suppose you have already $n$ primes $p_{1}, \dots, p_{n}$. Then $$ A = p_{1} \cdot p_{2} \cdots p_{n} + 1 > 1 $$ is not divisible by $p_{1}, \dots, p_{n}$, as Euclidean division by any of them yields remainder $1$. Since every natural number greater than $1$ is a product of primes, there must be a prime $p$, distinct from $p_{1}, \dots, p_{n}$, which divides $A$. In your case, you have taken $n = 2$, $p_{1} = 3$, $p_{2} = 5$. You get $A = 16$, and the only choice for $p$ is $2$. Had you taken $n = 2$, $p_{1} = 5$ and $p_{2} = 7$, then $A = 36$ so you have either $p = 2$ or $p = 3$.
[ "stackoverflow", "0003542657.txt" ]
Q: Anything below froyo can't read method in 3rd party library I'm using the jexcel api in my android application. It works great on devices running Android 2.2, but any other device just gives a blank String when I try to get the contents of a cell. I've narrowed the thing thats not working to the Cell.getContents() method in the jexcel api. All android version below 2.2 are able to get the workbook, get the sheets, get the number of sheets, and they can get the cells, but when trying to get the contents within that cell, it return a blank string. Is there something wrong with the library, or is it an android problem A: My guess is that FroYo added in support for some new Apache Harmony class or method (JavaSE-compatible) that JExcel depends on. In earlier versions, JExcel happens to catch the exception that's thrown and quietly fail. However, this is just a guess. Since JExcel is open source, you could examine the source code to that method and see what turns up. Or, you could temporarily add the JExcel source code to your project (since I'm guessing you're using a JAR right now), and you'll probably get a compile-time error regarding the missing class or method. This is all a guess, though.
[ "stackoverflow", "0011330291.txt" ]
Q: Google Chrome breaks links with z-index: -1 So recently I've come across an issue with Chrome in which if I set a z-index of -1 to a position: relative; unordered list, the links become unclickable. See http://jsfiddle.net/raLnx/ in Chrome 20.0.1132.47m for an example. There is no issue if both ul sections are given a positive z-index, but I figured this is either a bug in chrome or there is a better way than setting something position: relative; when I don't need to. The css in question: ul.over { height: 40px; line-height: 40px; border-radius: 5px; background-color: #DDD; border-bottom: 2px solid #AAA; } ul.under { height: 35px; padding: 0 30px; background-color: #EEE; line-height: 35px; font-size: 90%; position: relative; bottom: 5px; z-index: -1; } Any ideas? A: The reason it happens is because your div #nav is now above your list/links. You will have to remove z-index from your list.
[ "stackoverflow", "0027115580.txt" ]
Q: ++ operator overload c++ Meaning I am new in C++ and I've got some questions. I saw operator ++ overloading at complex numbers and I cant understand: Why I create a tmp variable why my first operator is Complex & and second it's just Complex Why return *this;(i know cause of Complex& but why) if i used Complex without & what would happened?(i run it and its the same result) Don't look at comments it's Greek :) Complex & Complex::operator ++(){ r=r+1; return *this;//to this einai to pointer tou trexontos alla 8eloume dereference ara vazoume *this gia na epistrepsoume refernce// } Complex Complex::operator ++(int ){ Complex tmp(*this); operator ++(); return tmp;//ftiaxnoume ena tmp tou antikimenou pou exoume meta efarmozoume to operator++ kai epistrefoume to tmp// } A: the different signature (Complex& vs Complex) is because these operations i++ and ++i do different things. One returns a copy of the old value (the second one) by value, the first one returns a reference to the actual value if x - by reference The tmp variable is needed because you need to return the old value after incrementing the value (thats what x++ does) you need to return a reference to the current object - so return *this - this is a pointer to the current object; *this is the object
[ "stackoverflow", "0020115009.txt" ]
Q: How to fit multidimensional output using scikit-learn? I am trying to fit OneVsAll Classification output in training data , rows of output adds upto 1 . One possible way is to read all the rows and find which column has highest value and prepare data for training . Eg : y = [[0.2,0.8,0],[0,1,0],[0,0.3,0.7]] can be reduced to y = [b,b,c] , considering a,b,c as corresponding class of the columns 0,1,2 respectively. Is there a function in scikit-learn which helps to achieve such transformations? A: This code does what you want: import numpy as np import string y = np.array([[0.2,0.8,0],[0,1,0],[0,0.3,0.7]]) def transform(y,labels): f = np.vectorize(lambda i : string.letters[i]) y = f(y.argmax(axis=1)) return y y = transform(y,'abc') EDIT: Using the comment by alko, I made it more general be letting the user supply the labels to the transform function.
[ "stackoverflow", "0057884458.txt" ]
Q: Could not find a declaration file for module 'cloudinary' after cloudinary dependancy npm install I have installed Cloudinary sdk in my project but when trying to create a variable from the sdk I get the following error - the thing is that I already have installed the cloudinary sdk in my project, it is inside my "node_modules" inside functions it is for sure something that I am missing in the directory path that the IDE can't recognise, but I can't figure out what. UPDATE: Here is my list of project dependencies from package.json: "@google-cloud/pubsub": "^0.17.0", "aws-sdk": "^2.526.0", "cloudinary": "^1.15.0", "ffmpeg-static": "^2.0.0", "firebase-admin": "^8.5.0", "firebase-functions": "^3.2.0", "fluent-ffmpeg": "^2.1.2", "secure-compare": "^3.0.1" A: Found the answer. I consults out of 2 things - 1) I have made a mistake that when I have pointed to the variables created out of the cloudinary variables I re-referenced the "v2" variable, which is not necessary as I already declared the variable with "v2". 2) Visual studio code IDE is just...bad (to say the least). Even-tough everything is working right now, the error "could not find a file declaration..." persist. I have no explanation for this behaviour.
[ "stackoverflow", "0050986378.txt" ]
Q: Mixin as class decorator in TypeScript does not update class property Intro I have a project in TS that requires some classes to implement the following interface: interface IStylable { readonly styles: { [property: string]: string }; addStyles (styles: { [property: string]: string }): void; updateStyles (styles: { [property: string]: string }): void; removeStyles (styles: Array<string>): void; } To avoid boilerplate code I decided to create a Mixin and apply it in each class I need it. (I could use an abstract class but my problem requires multiple inheritance solution, something that is not offered by TS.) Bellow is the class implementation of IStylable interface: export class StylableClass implements IStylable { private readonly _styles: { [property: string]: string } = {}; // For each property provided in styles param, check if the property // is not already present in this._styles and add it. This way we // do not overide existing property values. public addStyles (styles: { [property: string]: string }): void { for (const [property, value] of Object.entries(styles)) { if (!this._styles.hasOwnProperty(property)) { this._styles[property] = value; } } } // For each property provided in styles param, check if the property // is already present in this._styles and add it. This way we // do add property values values that do not exist. public updateStyles (styles: { [property: string]: string }): void { for (const [property, value] of Object.entries(styles)) { if (this._styles.hasOwnProperty(property)) { this._styles[property] = value; } } } // For each property in styles param, check if it is present in this._styles // and remove it. public removeStyles (styles: Array<string>): void { for (const property of styles) { if (this._styles.hasOwnProperty(property)) { delete this._styles[property]; } } } public set styles (styles: { [property: string]: string }) { this.addStyles(styles); } public get styles (): { [property: string]: string } { return this._styles; } } For something I'm really excited about and looking forward is standardized of decorator specification in ES6. Typescript allow this experimental feature by setting the experimentalDecorators flag in tsconfig.json. I wanted the StylableClass to be used as a class decorator (@Stylable) to make the code cleaner, so I created a function that takes a class and transforms it to decorator: export function makeDecorator (decorator: Function) { return function (decorated: Function) { const fieldCollector: { [key: string]: string } = {}; decorator.apply(fieldCollector); Object.getOwnPropertyNames(fieldCollector).forEach((name) => { decorated.prototype[name] = fieldCollector[name]; }); Object.getOwnPropertyNames(decorator.prototype).forEach((name) => { decorated.prototype[name] = decorator.prototype[name]; }); }; } and used it like so: export const Stylable = () => makeDecorator(StylableClass); The problem Now it's time for Unit testing. I created a dummy class to apply my decorator and wrote a simple test for addStyles() method. @Stylable() class StylableTest { // Stylable public addStyles!: (styles: { [prop: string]: string; }) => void; public updateStyles!: (styles: { [prop: string]: string; }) => void; public removeStyles!: (styles: string[]) => void; public styles: { [property: string]: string } = {}; } describe('Test Stylable mixin', () => { it('should add styles', () => { const styles1 = { float: 'left', color: '#000' }; const styles2 = { background: '#fff', width: '100px' }; // 1 const styles = new StylableTest(); expect(styles.styles).to.be.an('object').that.is.empty; // 2 styles.addStyles(styles1); expect(styles.styles).to.eql(styles1); // 3 styles.addStyles(styles2); expect(styles.styles).to.eql(Object.assign({}, styles1, styles2)); }); }); The problem is that the second expect statement fails. After executing styles.addStyles(styles1); the styles.styles array is still empty when it should contain the styles1 object. When I debugged my code I found that the push statement in addStyles() method is executed as expected, thus the loop is not problematic, but the array is not updated after the execution of the method ends. Can you provide me a hint or a solution on what did I missed? The first thing I checked is maybe something is going wrong with the makeDecorator function but as long as I can execute the methods I cannot find some other clue to look for. A: The StylableClass mixin declares a property called styles. But the StylableTest creates a field name styles and assigns an empty object to it which nobody is going to use. You need to transfer the property descripts from the decorator to the target class, and remove the = {} from the styles in StylableTest: function makeDecorator(decorator) { return function (decorated) { var fieldCollector = {}; decorator.apply(fieldCollector); Object.getOwnPropertyNames(fieldCollector).forEach(function (name) { decorated.prototype[name] = fieldCollector[name]; }); Object.getOwnPropertyNames(decorator.prototype).forEach(function (name) { var descriptor = Object.getOwnPropertyDescriptor(decorator.prototype, name); if (descriptor) { Object.defineProperty(decorated.prototype, name, descriptor); } else { decorated.prototype[name] = decorator.prototype[name]; } }); }; } May I suggest a less error prone approach to mixins in typescript. This approach o having to redeclare all the mixin members will cause errors later down the road. At least avoid restating the type of the fields using type queries: @Stylable() class StylableTest { // Stylable public addStyles!: IStylable['addStyles'] public updateStyles!: IStylable['updateStyles'] public removeStyles!: IStylable['removeStyles'] public styles!: IStylable['styles'] }
[ "stackoverflow", "0062382784.txt" ]
Q: How to add Autodesk Forge Viewer Extensions to React? I want to add my Autodesk forge viewer extensions to React. Is it possible and how can i do this? Now i have a viewer which work in React, but extensions still working with pure js. A: https://forge-rcdb.autodesk.io/ is built using react, it has many forge viewer extensions. Github Repo: https://github.com/Autodesk-Forge/forge-rcdb.nodejs Here's an example of loading forge viewer extension in react project: https://github.com/Autodesk-Forge/forge-rcdb.nodejs/blob/89e2e0af1d87e3b948cb66bc88f54140c6e8a0e8/src/client/components/Viewer/Viewer.Configurator/Viewer.Configurator.js#L871
[ "superuser", "0000159745.txt" ]
Q: 3 Headed Display Ubuntu Wallpaper I got 3 display working in Linux. I have set it up so I have Xinerama and 3 different X sessions. So my 3 displays are not all the same size, two are 1680x1050 and then the other which is between the two is 2560x1600. So my issue is when I chose span, even if the image is larger than all 3 resolutions combined, the center monitor has bars at the top and the bottom because span scales the image it seems. Is there a way if I bypass the gui to have an image span all three monitors but with no scaling? Urgent! Please help! ;-) A: I came up with one option after a flashback to the 90s... From Terminal: gconf-editor The in Apps/Nautilus/Preferences uncheck "Show Desktop" Then in the gconf editor: display -window root ~/Pictures/KeswickCropped.bmp
[ "stackoverflow", "0043868302.txt" ]
Q: Does the 'break' keyword prevent the code from running that loop again in Python? Here is my code, in which I try to reference the walls list of tuples in the creation of the map list of tuples, which has the index [variable][2] as the property of being a wall or floor: map = [] walls = [(0,3), (0,4), (0,5), (0,7), (2,7), (3,7), (4,7), (5,7), (1,7), (5,6), (5,4), (2,3), (2,4), (3,5), (3,0), (3,1), (3,2), (7,0), (7,1), (7,5), (7,6), (7,7), (8,7)] for x in range(9): for y in range(9): for a in range(len(walls)): if walls[a][0] == x and walls[a][1] == y: map.append(tuple((x,y,"w"))) else: map.append(tuple((x,y,"_"))) break ---> [(0, 0, '_'), (0, 1, '_'), (0, 2, '_'), (0, 3, 'w'), (0, 4, '_'), (0, 5, '_'), (0, 6, '_'), (0, 7, '_'), (0, 8, '_'), (1, 0, '_'), (1, 1, '_'), (1, 2, '_'), (1, 3, '_'), (1, 4, '_'), (1, 5, '_'), (1, 6, '_'), (1, 7, '_'), (1, 8, '_'), (2, 0, '_'), (2, 1, '_'), (2, 2, '_'), (2, 3, '_'), (2, 4, '_'), (2, 5, '_'), (2, 6, '_'), (2, 7, '_'), (2, 8, '_'), (3, 0, '_'), (3, 1, '_'), (3, 2, '_'), (3, 3, '_'), (3, 4, '_'), (3, 5, '_'), (3, 6, '_'), (3, 7, '_'), (3, 8, '_'), (4, 0, '_'), (4, 1, '_'), (4, 2, '_'), (4, 3, '_'), (4, 4, '_'), (4, 5, '_'), (4, 6, '_'), (4, 7, '_'), (4, 8, '_'), (5, 0, '_'), (5, 1, '_'), (5, 2, '_'), (5, 3, '_'), (5, 4, '_'), (5, 5, '_'), (5, 6, '_'), (5, 7, '_'), (5, 8, '_'), (6, 0, '_'), (6, 1, '_'), (6, 2, '_'), (6, 3, '_'), (6, 4, '_'), (6, 5, '_'), (6, 6, '_'), (6, 7, '_'), (6, 8, '_'), (7, 0, '_'), (7, 1, '_'), (7, 2, '_'), (7, 3, '_'), (7, 4, '_'), (7, 5, '_'), (7, 6, '_'), (7, 7, '_'), (7, 8, '_'), (8, 0, '_'), (8, 1, '_'), (8, 2, '_'), (8, 3, '_'), (8, 4, '_'), (8, 5, '_'), (8, 6, '_'), (8, 7, '_'), (8, 8, '_')] The issue: Only one coordinate is checked and assigned 'w', while the rest are not. The point of logic where I see the issue would be the break statement. Does the break statement prevent the last nested for loop from running ever again. Should it not go: x=0, y=3, a=0, break ---> x=0, y=4, a=0, a=1, break --->... A: From python docs: The break statement, like in C, breaks out of the smallest enclosing for or while loop. Read further in here. Hopefully this will help you, Yahli.
[ "stackoverflow", "0034789452.txt" ]
Q: How to checkout specific files or directories with dulwich I have a working checkout function based on dulwich: def checkout(repo, ref=None): if ref is None: ref = repo.head() index = repo.index_path() tree_id = repo[ref].tree build_index_from_tree(repo.path, index, repo.object_store, tree_id) return [repo.object_store.iter_tree_contents(tree_id)] But how would I amend that to checkout an individual file or directory? Is there something that could replace the build_index_from_tree line? A: Inline the contents of build_index_from_tree(), then add an if statement to filter out any entry that does not have an entry.path that starts with your path: if subpath[-1] != "/": subpath += "/" if not isinstance(root_path, bytes): root_path = root_path.encode(sys.getfilesystemencoding()) for entry in object_store.iter_tree_contents(tree_id): if not validate_path(entry.path, validate_path_element_default): continue # new lines added here: if not entry.path.startswith(subpath): continue full_path = _tree_to_fs_path(root_path, entry.path[len(subpath):]) if not os.path.exists(os.path.dirname(full_path)): os.makedirs(os.path.dirname(full_path)) obj = object_store[entry.sha] build_file_from_blob(obj, entry.mode, full_path)
[ "stackoverflow", "0020637799.txt" ]
Q: Redirecting to subdomain from WebAPI controller - CORS required? Currently, my WebAPI controller does this: var newUrl = _adminService.Foo(bar); return Request.CreateResponse(HttpStatusCode.OK, newUrl); So the client receives a string, and then sets window.location with javascript. This seems like a hacky way to redirect via WebAPI. I found this post: Redirect from asp.net web api post action Which I've implemented: var newUrl = _adminService.Foo(bar); var response = Request.CreateResponse(HttpStatusCode.Moved); response.Headers.Location = new Uri(newUrl); return response; But now I get the following error in chrome (when navigating from localhost to the subdomain): XMLHttpRequest cannot load http://test.localhost:3806/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3806' is therefore not allowed access. Do I need to configure CORS for this? A: Do I need to configure CORS for this? Yes, you do need if your javascript is hosted on a different domain than your Web API.
[ "math.stackexchange", "0001620447.txt" ]
Q: Integrate and find closed form for $\int_0^\infty\frac{\sin x^n}{n\pi}dx$ I’m working on a practice exam for my analysis class, and I was asked to find a general form for $$\int_0^\infty\frac{\sin x^n}{n\pi}dx$$ When I first looked at this, my mind instantly went to the Dirchlet Integral. Its been some time and I haven’t been able to see the relation. A: This integral is kind of famous. It can be done with residues or real methods. It is probably on the site somewhere. It is more like what is known as a Fresnel integral. Write $$\frac{1}{\pi n}\int_{0}^{\infty}\sin(x^{n})dx$$ Let $t=x^{n}, \;\ t^{1/n}=x, \;\ dx=\frac{1}{n}t^{1/n-1}dt$ $$\frac{1}{n}\cdot \frac{1}{\pi n}\int_{0}^{\infty}t^{1/n-1}\sin(t)dt$$ By the Gamma function, we can write a double integral: $$\frac{1}{\pi n^{2}}\cdot \frac{1}{\Gamma(1-\frac{1}{n})}\int_{0}^{\infty}\int_{0}^{\infty}u^{-1/n}e^{-ut}\sin(t)dudt$$ switch integrals and integrate w.r.t t: $$\frac{1}{\pi n^{2}\Gamma(1-1/n)}\int_{0}^{\infty}\frac{1}{u^{1/n}(u^{2}+1)}du$$ Among other means, we can use the Beta function: $\beta(p,q)=\frac{\Gamma(p)\Gamma(q)}{\Gamma(p+q)}=\int_{0}^{\infty}\frac{y^{p-1}}{(1+y)^{p+q}}dy$ Thus, by using the sub $y=u^{2}$, we get: $$\frac{1}{2\pi n^{2}\Gamma(1-1/n)}\Gamma\left(\frac{1-n}{2}\right)\cdot \Gamma\left(\frac{n+1}{2}\right)$$ Using the reduction formulas for Gamma: $\Gamma(1/2-\frac{1}{2n})\Gamma(1/2+\frac{1}{2n})=\pi \sec(\frac{\pi}{2n})\to \frac{\pi \sec\left(\frac{\pi}{2n}\right)}{\Gamma(1-1/n)}=2\sin\left(\frac{\pi}{2n}\right)\Gamma(1/n)$, we can write: $$=\boxed{\frac{1}{\pi n^{2}}\cdot \Gamma(1/n)\sin\left(\frac{\pi}{2n}\right)}$$
[ "emacs.stackexchange", "0000045743.txt" ]
Q: How do I add custom hierarchical keybindings? I am looking for a compact way to store a lot of shortcut keybindings. This is my current idea, for which I'm looking for help how to add this into my emacs config: I would like to make F9 "my" key, that opens up a hierarchical menu of (global) keybindings. When pressing F9, I'd like a submenu to open that shows e.g.: o - org-mode submenu a - show org-mode agenda w - org-wiki submenu b - org-brain submenu If I press F9-a, I'd like to directly execute the M-x org-agenda command. But by pressing F9-w, I get a new submenu opened that e.g. shows this: # Org-wiki submenu i - Show Wiki index n - Add new Wiki page If my final keystroke sequence is F9-w-i, I want the command M-x org-wiki-index executed. Does something like this exist already? Is there a better solution? If no, how would I add something like this in my emacs config? /Edit: I think what I want is to write my custom version of the M-x org-agenda command. A: As @icarus suggested, hydra is the way to go here. Check out my solution that is similar to what you want here: https://github.com/jkitchin/scimax/blob/master/scimax-hydra.el there are submenus of keys that open new hydras. I have mine bound to f12, and then remapped caps lock to be f12. It is convenient for me.
[ "stackoverflow", "0036372941.txt" ]
Q: Two Dimentional Multi-Criterion Lookup I have a dataset that is structured as follows Metric Month Group 1 Group 2 Group 3 Group 4 Group 5 Total Metric 1 Jan-16 3 2 2 3 3 13 Metric 2 Jan-16 4 345 345 4 4 702 Metric 3 Jan-16 7 7 7 7 7 35 Metric 1 Feb-16 4 89 89 4 4 190 Metric 2 Feb-16 2 9 2 4 17 34 Metric 3 Feb-16 345 3 345 2 3 698 Metric 1 Mar-16 7 4 7 345 4 367 Metric 2 Mar-16 89 7 89 7 7 199 Metric 3 Mar-16 9 4 9 89 4 115 Metric 1 Apr-16 3 7 3 9 7 29 Metric 2 Apr-16 4 7 4 7 89 111 Metric 3 Apr-16 7 7 7 7 9 37 I have a dashboard for each metric. Below is an example dashboard for Metric 1. The objective is for the value for each month, group (e.g. Total, Group 1, etc.), and metric to populate the appropriate cell under each month. I assume this would require a multi-criterion lookup function but I'm unsure how to structure it. Thoughts? **Total** Jan-16 Feb-16 Mar-16 Apr-16 May-16 Metric 1 **Group 1** Jan-16 Feb-16 Mar-16 Apr-16 May-16 Metric 1 **Group 2** Jan-16 Feb-16 Mar-16 Apr-16 May-16 Metric 1 A: It can certainly be done with a combination of SUMIFS and INDEX/MATCH. If the data is in A1:H13 and the dashboard starts in J1, the formula is:- =SUMIFS(INDEX($C$2:$H$13,,MATCH($J1,$C$1:$H$1,0)),$B$2:$B$13,K2,$A$2:$A$13,$J3) starting in K3 and copied across and down as required. The idea is that it will match the Group in the cell two rows above, the Month in the same column and one row above, and the Metric in the same row and to the left. You could also put in Metric * if you wanted to combine all metrics.
[ "stackoverflow", "0031707969.txt" ]
Q: golang exception to rule "interface pointer can't implement interface" In golang.org's official FAQ, under pointers there is this quote: "The insight is that although a pointer to a concrete type can satisfy an interface, with one exception a pointer to an interface can never satisfy an interface" Out of curiosity, what is that exception to the above rule? i.e when can an interface pointer implement an interface? A: Just below it says: The one exception is that any value, even a pointer to an interface, can be assigned to a variable of empty interface type (interface{}). Even so, it's almost certainly a mistake if the value is a pointer to an interface; the result can be confusing.
[ "stackoverflow", "0043110437.txt" ]
Q: How to pass the repeat count to x command in GDB The x command can examine memory in GDB. Like x/4xg 0x60400 Now I am going to define my own x comand which examines memory with specified repeat count, like: define myXCommand set var &repeatCount=$arg0 x/(???)xg 0x60400 end I have tried many ways to pass the variant repeatCount to x command, but I failed finally. My problem is how to pass the repeat count to x command? Appreciated very much if anyone can help. A: A convenience variable can be used in most expressions, but the x command only allows the repeat count to be a string of digits, not an arbitrary expression. What you can do is use the eval command, which does a printf on its arguments and then runs the result as a command. define myXCommand set var $repeatCount=$arg0 eval "x/%dxg 0x60400", $repeatCount end
[ "stackoverflow", "0043029737.txt" ]
Q: How can i have many radio buttons on an image? (HTML, CSS) I want to have 8 radio buttons in one image. To be more specific i want to have an image of hawaai islands. Different radio button every island so i can choose one. Thank you very much A: You should use absolute position then. div { height:400px; width: 400px; background: #124578; position: relative; } #radio01 { position:absolute; left:0; top:50%; } #radio02 { position:absolute; left:calc(100% - 25px); top:25%; } #radio03 { position:absolute; left:50%; top:70%; } <div> <form action=""> <input type="radio" id="radio01" name="radio" /> <input type="radio" id="radio02" name="radio" /> <input type="radio" id="radio03" name="radio" /> </form> </div>
[ "craftcms.stackexchange", "0000010588.txt" ]
Q: Set Users' passwords When you create a new user in the craft backend CMS, it used to be possible to set (and change for existing users) the password. It appears recently (last 6 months+) that this feature has been removed, is there a simple way to re-instate this feature or is the only way to set the password the password re-set url feature? A: For security reasons, this was changed in Craft 2.3... Admins are no longer allowed to change other users’ passwords. But savvy admins can still pull it off... Simply click the gear icon in the right sidebar, and select "Copy password reset URL". Then, instead of sending that URL to the user, just use it yourself.
[ "stackoverflow", "0045503232.txt" ]
Q: Can't move node to its own tree using Alfresco's Javascript API I've just written a script using the Javascript API so I can use it as a Rule to a Space. Whenever a document enters in a space, it basically checks document's name to get the parent directory it will be stored in (document's name contains parent's folder name), then creates future parent directory (if it doesn't exist), and finally moves the document into it. I'm having troubles with this last step. Whenever I try to move the document into the recently created folder, I get the following error: Node has been pasted into its own tree. This is my code so far, which I think is pretty much auto-descriptive: var fileName= document.properties.name; var fields = fileName.split('.'); var parentName= fields[0]; var newNode=space.childByNamePath(parentName); if (newNode === null) { //create folder and move document into it newNode=space.createFolder(parentName); //works document.move(newNode); //I'm getting the error here }else{ //folder already exists, just move document into it document.move(newNode); //here too } If I comment out the document.move(newNode); lines everything else works fine. Parent folder is successfully created but obviously the document keeps stored at the root of the current space, which is not what I need. Indeed I need to move it into the actual folder. Am I doing something wrong? Any help would be much appreciated. Thanks. UPDATE: Indeed I found out that the move() call inside the if scope it's working if I comment out the other call inside the else scope. So the error is being thrown at the else move() call. Also if I remove the else clause and put just one move() call after if scope, it also produces the same error. A: You should run your rule as a background process, it will solve the problem ("Run rule in background" option).
[ "stackoverflow", "0058568218.txt" ]
Q: Datetime conversion format I converted the datetime from a format '2018-06-22T09:38:00.000-04:00' to pandas datetime format i tried to convert using pandas and got output but the output is o/p: 2018-06-22 09:38:00-04:00 date = '2018-06-22T09:38:00.000-04:00' dt = pd.to_datetime(date) expected result: 2018-06-22 09:38 actual result: 2018-06-22 09:38:00-04:00 A: There is timestamps with timezones, so if convert to UTC by Timestamp.tz_convert, times are changed: date = '2018-06-22T09:38:00.000-04:00' dt = pd.to_datetime(date).tz_convert(None) print (dt) 2018-06-22 13:38:00 So possible solution is remove last 6 values in datetimes: dt = pd.to_datetime(date[:-6]) print (dt) 2018-06-22 09:38:00
[ "math.stackexchange", "0003203038.txt" ]
Q: Find other factors of the euler function of $2^k-1$ where $k\ge 2$ is an integer, except $2$. Euler function of $x$ is denoted by $\varphi(x)$, which is defined in here (https://en.wikipedia.org/wiki/Euler%27s_totient_function ). When $k$ is prime. @egreg comments that there does not exist a formula to obtain $\varphi(2^k-1)$. @Dietrich Burde comments that there need not be other factors of $\varphi(2^k-1)$ different from $2$ and $k$. However, if $k$ is not prime, it seems that finding factors of $\varphi(2^k-1)$ is not obvious. Motivation ($k$ is prime.) Let $n=2^k-1$, where $k$ is prime. In $\mathbb{Z}_{n}$, the group $G=\langle 2 \rangle$ is of order $k$. Since the order of the multiplicative group $$\mathbb{Z}_{n}^*=\{ x \in \mathbb{Z}_{n} \mid \gcd(x,n)=1\}$$ is $\varphi(n)$, it should have $$k \mid \varphi(2^k-1).$$ Proposition 1: If $k$ is prime, then $2 \mid \varphi(2^k-1)$ and $k \mid \varphi(2^k-1)$. Problem Find other factors of $\varphi(2^k-1)$ where $k\ge 2$ is an integer, except $2$. Or proof some conjectures below. 3.My trying($k$ is not prime.) [ <k, EulerPhi(2^k-1)> : k in [2..200] | (EulerPhi(2^k-1) mod 2 ne 0) or ( EulerPhi(2^k-1) mod k ne 0) ]; By the above magma program, it seems that $2$ and $k$ are two factors of $\varphi(2^k-1)$ for $2\le k \le 200$. Proposition 2: $2 \mid \varphi(2^k-1)$ for $k\ge 2$. Proof. Note that $2^k-1$ is odd. It follows that $\varphi(2^k-1)$ is even. QED. For $k$ is not prime, it only has $2^k\equiv 1 \pmod{2^k-1}$ which is not sufficient to show that the group $G=\langle 2 \rangle$ is of order $k$. conjecture 1: $k \mid \varphi(2^k-1)$ for $k\ge 2$. Moreover, by the following magma program, it conjectures that $3\mid \varphi(2^k-1)$ if $5 \mid k$ or $7 \mid k$. It would be better if the sufficient and necessary condition of $3 \mid \varphi(2^k-1)$ can be given. conjecture 2: $3\mid \varphi(2^k-1)$ if $5 \mid k$ or $7 \mid k$. [ <k, Factorization(EulerPhi(2^k-1))> : k in [5..500 by 5] | (EulerPhi(2^k-1) mod 2 ne 0) or ( EulerPhi(2^k-1) mod 3 ne 0) ]; [ <k, Factorization(EulerPhi(2^k-1))> : k in [7..210 by 7] | (EulerPhi(2^k-1) mod 2 ne 0) or ( EulerPhi(2^k-1) mod 3 ne 0) ]; A: Conjecture 3 is clearly true, and here is a generalization: if $d \mid k$ and $2^d-1$ is a Mersenne prime, then $2^d - 2$ divides $\varphi(2^k -1)$. Proof: if $d \mid k$ then there exists $l \in \mathbb N$ such that $k = dl$, therefore $$\varphi(2^k - 1) = \varphi \left( (2^d)^l - 1 \right) = \varphi \left( (2^d - 1) \sum_{i=0} ^{l-1} (2^d)^i \right) = \varphi(2^d - 1) \ \varphi \left( \sum_{i=0} ^{l-1} 2^{di} \right) = (2^d - 2) \ \varphi \left( \sum_{i=0} ^{l-1} 2^{di} \right) \ .$$ Now, notice that if $d \in \{5,7\}$ then $2^d - 2 \in \{30,126\}$, and these numbers are both divisible by $3$.
[ "stackoverflow", "0056636318.txt" ]
Q: Using pandas to join on multiple soft keys and multiple hard keys with different names Is it possible to use pandas to join on multiple soft keys e.g when we allow tolerance range for a match and multiple hard keys that are named differently in both tables? It seems that pandas.merge_asof allows only to join on one soft key and does not allow to specify hard key names separately for left and right tables (in case they are differently named and renaming isn't easy to process). Consider the following two datasets table1: soft keys: sk1, sk2 hard keys: x, y sk1,sk2,x,y,val1 10,100,10,15,1 20,200,20,25,2 30,300,10,10,3 table2: soft keys: sk1,sk2 hard keys: k1,k2 sk1,sk2,k1,k2,val2,x,y 15,110,10,15,3,1,1 23,230,20,25,5,2,2 34,330,10,10,-1,3,3 I would need something equivalent to soft_merge(t1, t2, left_by=["x","y"], right_by=["k1","k2"], on=[sk1, sk2], tolerance=[5,15]) to get output (showed vals only for clarity): val1 | val2 1 | 3 I understand that instead of left_by and right_by for hard keys we can just use by and rename columns, but this might not be easily supportable by a system since other system components might rely on old namings. Is there any clean and nice way of achieving it without multiple naming-renaming? But the problem of joining on multiple soft keys still remain unclear ... A: Implement the tolerances after an exact merge: m = df1.merge(df2, left_on=["x","y"], right_on=["k1","k2"]) mask = (m.sk1_x - m.sk1_y).abs().le(5) & (m.sk2_x - m.sk2_y).abs().le(15) m.loc[mask, ['val1', 'val2']] # val1 val2 #0 1 3 This doesn't ensure a 1:1 merge, and will give all combinations that achieve that tolerance. If you need the "nearest" match you will need to specify some distance formula and keep only the closest. Here I use the total absolute distance. Assuming val1 is a unique key: m['dist'] = (m.sk1_x - m.sk1_y).abs() + (m.sk2_x - m.sk2_y).abs() m.sort_values('dist').loc[mask].drop_duplicates('val1')
[ "stackoverflow", "0009901825.txt" ]
Q: custom setter for double I have the following property: @property (nonatomic, assign) double lastSynced; and here's my custom setter: -(void)setLastSynced:(double)newLastSynced { if (lastSynced != newLastSynced){ lastSynced = newLastSynced; [[NSUserDefaults standardUserDefaults] setDouble:lastSynced forKey:kSettingLastSyncedKey]; [[NSUserDefaults standardUserDefaults] synchronize]; } } I am not sure why my custom setter is not called when I am setting the lastSynced? I have it synthesized as @synthesized lastSynced. A: Have you tried explicitly declaring your setter? @property (nonatomic, assign, setter=setLastSynched:) double lastSynced;
[ "mathematica.stackexchange", "0000006745.txt" ]
Q: How do you check if there are any equal arguments(even sublist) in a list? I would like to set up a function which has to return True if at least two arguments of a given List are equal. So if I give {1,4,6,2} to the function it has to return False (since none of his arguments are equal) and the same would happen if I gave {{1,2,3},{2,3,4}}, while if I gave {1,2,3,1,4} or {{1,2,3},{2,0,0},{1,2,3},{2,1,2}} it has to return True. I know this is a very simple problem and i think you can easily tell me a convenient way to achieve that. A: As it happens there is a built-in function that already does this: Signature. If any two elements of list are the same, Signature[list] gives 0. dupeQ = 0 === Signature@# &; I believe this is the "canonical" answer. It is fast on both packed arrays and unpacked lists. A: If there are repeated elements in the list, then calling Union[] on it will shorten it so that this element only appears once, so a simple implementation would be to test these lengths: test[list_] := Length[Union[list]] != Length[list] If you wanted to know which elements where repeated, you this could be accomplished by using Gather[] to collect identical elements, and picking out which groups have more then one element. repeats[list_] := Select[Gather[list], Length[#] > 1 &][[1 ;;, 1]] Note, I'm using Union rather then DeleteDuplicates[] since (as Mr. Wizard corrected me) it is faster. I can't say why except that DeleteDuplicates[] retains the order of elements which may require slightly more bookkeeping. And in this case we don't care about the book keeping. Naturally if you really needed something really speedy, a better solution exists which doesn't search through the entire list, but stops if just a single duplicate is found, Mr. Wizards Answer is just such an function, since Signature exits early if duplicates exist, though it becomes slower if no duplicates are present, it's a trade off. A: duplicatesQ = # != DeleteDuplicates[#] & Usage: duplicatesQ[{1, 4, 6, 1}] (* ===> True *) duplicatesQ@{1, 4, 6, 2} (* ==> False *) duplicatesQ@{{1, 2, 3}, {2, 0, 0}, {1, 2, 3}, {2, 1, 2}} (* ==> True *) duplicatesQ /@ {{1, 2, 3}, {2, 0, 0}, {1, 2, 3}, {2, 1, 2}} (* ==> {False, True, False, True} ) or (to also get the duplicate elements and their count when there are duplicate elements) dups = (Select[Tally[#], Last[#] > 1 &] /. {} -> "None") & Usage: dups /@ {{1, 2, 3}, {2, 0, 0}, {1, 2, 3}, {2, 1, 2}} (* ==> {"None", {{0, 2}}, "None", {{2, 2}}} *) dups[{{1, 2, 3}, {2, 0, 0}, {1, 2, 3}, {2, 1, 2}}] (* ==> {{{1, 2, 3}, 2}} *)
[ "stackoverflow", "0035970898.txt" ]
Q: GCD sync serial main_queue -(void)test1{ dispatch_queue_t queue = dispatch_get_main_queue(); NSLog(@"start"); dispatch_sync(queue, ^{ NSLog(@"%@",[NSThread currentThread]); }); } -(void)test2{ dispatch_queue_t queue = dispatch_queue_create("com.yaoye.serial", DISPATCH_QUEUE_SERIAL); NSLog(@"start"); dispatch_sync(queue, ^{ NSLog(@"%@",[NSThread currentThread]); }); } Test1 and test2 are executed in the main thread Test1 example: the main thread is blocked waiting for synchronization function, block into the main thread of the runloop cannot be executed, lead to deadlock. Test2 example: the main thread waiting for synchronization function is blocked,block into the main thread of the runloop, but no deadlock.<2016-03-14 13:55:06.730 GCD[54320:12111593] <NSThread: 0x7fef4ac08810>{number = 1, name = main}> queation: Why not is test2 deadlock? A: because test1 uses the same main queue, whereas test2 uses a different queue
[ "stackoverflow", "0059499688.txt" ]
Q: Executing CMD commands in Powershell IDE lets shell idle Im making a powershell script that lets me install a certain software and i cant use certain powershell commands because i have to execute the script on multiple environments (PS 2-5.1) So i try to unzip files with this command because all the clients have 7zip and Windows installed. cmd.exe --% 7z x C:\ProgramFiles\OpenSSH-Win64.zip' But the ouput is simply: (sorry for the german) Microsoft Windows [Version 10.0.18362.356] (c) 2019 Microsoft Corporation. Alle Rechte vorbehalten. And the rest of the scripts is not being executed... its in some idle state which I can interrupt with CTRL+C Am i missing something? Why is the command not being executed and the script continued? Thanks for the help :) Further Information: CMD Output Powershell Output A: Try: Invoke-Command [path to 7z.exe] x 'C:\ProgramFiles\OpenSSH-Win64.zip' If that doesn't work, try Invoke-Command [path to 7z.exe] --% x C:\ProgramFiles\OpenSSH-Win64.zip' You can use & instead of Invoke-Command
[ "stackoverflow", "0048395565.txt" ]
Q: ReactJs: TypeError: Cannot read property 'PropTypes' of undefined I'm using react-router v3.2.0 and this is my app.js, error is showing on line router: PropTypes.object in chrome and in edge it shows error as TypeError: Unable to get property 'object' of undefined or null reference at class App extends React.Component , btw I am new to react import React, { PropTypes } from 'react'; import { Router } from 'react-router'; import './App.css'; class App extends React.Component { static contextTypes = { router: PropTypes.object } static propTypes = { history: PropTypes.object.isRequired, routes: PropTypes.element.isRequired }; get content() { return ( <Router routes={this.props.routes} history={this.props.history} /> ) } render () { return ( <div className="App"> <div style={{ height: '100%' }}> <h2>Welcome to Vavavoom!</h2> {this.content} </div> </div> ) } } export default App; A: Don't know why but changing version of react-router": "^3.2.0 to react-router": "^3.0.0 and react-dom": "^16.2.0 to react-dom": "^15.3.2 solved my issue
[ "stackoverflow", "0004717250.txt" ]
Q: extracting unique values between 2 sets/files Working in linux/shell env, how can I accomplish the following: text file 1 contains: 1 2 3 4 5 text file 2 contains: 6 7 1 2 3 4 I need to extract the entries in file 2 which are not in file 1. So '6' and '7' in this example. How do I do this from the command line? many thanks! A: $ awk 'FNR==NR {a[$0]++; next} !($0 in a)' file1 file2 6 7 Explanation of how the code works: If we're working on file1, track each line of text we see. If we're working on file2, and have not seen the line text, then print it. Explanation of details: FNR is the current file's record number NR is the current overall record number from all input files FNR==NR is true only when we are reading file1 $0 is the current line of text a[$0] is a hash with the key set to the current line of text a[$0]++ tracks that we've seen the current line of text !($0 in a) is true only when we have not seen the line text Print the line of text if the above pattern returns true, this is the default awk behavior when no explicit action is given A: Using some lesser-known utilities: sort file1 > file1.sorted sort file2 > file2.sorted comm -1 -3 file1.sorted file2.sorted This will output duplicates, so if there is 1 3 in file1, but 2 in file2, this will still output 1 3. If this is not what you want, pipe the output from sort through uniq before writing it to a file: sort file1 | uniq > file1.sorted sort file2 | uniq > file2.sorted comm -1 -3 file1.sorted file2.sorted There are lots of utilities in the GNU coreutils package that allow for all sorts of text manipulations. A: I was wondering which of the following solutions was the "fastest" for "larger" files: awk 'FNR==NR{a[$0]++}FNR!=NR && !a[$0]{print}' file1 file2 # awk1 by SiegeX awk 'FNR==NR{a[$0]++;next}!($0 in a)' file1 file2 # awk2 by ghostdog74 comm -13 <(sort file1) <(sort file2) join -v 2 <(sort file1) <(sort file2) grep -v -F -x -f file1 file2 Results of my benchmarks in short: Do not use grep -Fxf, it's much slower (2-4 times in my tests). comm is slightly faster than join. If file1 and file2 are already sorted, comm and join are much faster than awk1 + awk2. (Of course, they do not assume sorted files.) awk1 + awk2, supposedly, use more RAM and less CPU. Real run times are lower for comm probably due to the fact that it uses more threads. CPU times are lower for awk1 + awk2. For the sake of brevity I omit full details. However, I assume that anyone interested can contact me or just repeat the tests. Roughly, the setup was # Debian Squeeze, Bash 4.1.5, LC_ALL=C, slow 4 core CPU $ wc file1 file2 321599 321599 8098710 file1 321603 321603 8098794 file2 Typical results of fastest runs awk2: real 0m1.145s user 0m1.088s sys 0m0.056s user+sys 1.144 awk1: real 0m1.369s user 0m1.324s sys 0m0.044s user+sys 1.368 comm: real 0m0.980s user 0m1.608s sys 0m0.184s user+sys 1.792 join: real 0m1.080s user 0m1.756s sys 0m0.140s user+sys 1.896 grep: real 0m4.005s user 0m3.844s sys 0m0.160s user+sys 4.004 BTW, for the awkies: It seems that a[$0]=1 is faster than a[$0]++, and (!($0 in a)) is faster than (!a[$0]). So, for an awk solution I suggest: awk 'FNR==NR{a[$0]=1;next}!($0 in a)' file1 file2
[ "stackoverflow", "0019301023.txt" ]
Q: BlocksKit crashing on Open In Dialogue I have a view controller opening an 'Open-In' dialogue via a bar button item. Calling code: UIDocumentInteractionController *docInteraction = [[UIDocumentInteractionController alloc] init]; docInteraction.URL = location; docInteraction.delegate = self; if ([docInteraction presentOpenInMenuFromBarButtonItem:self.openInButton animated:YES]) self.openInController = docInteraction; Dismissal code: UIDocumentInteractionController *openIn = self.openInController; if (openIn) { [openIn dismissMenuAnimated:animated]; self.openInController = nil; popupsDismissed = YES; } Sometime after the code is dismissed, the app crashes with this exception: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[A2DynamicUIPopoverControllerDelegate popoverController:animationCompleted:]: unrecognized selector sent to instance 0x1f82b4f0' This is a BlocksKit defined interface, but I'm not using a BlocksKit class in thie particular case. 0x1f82b4f0 is a <A2DynamicDelegate: 0x1f82b4f0; protocol = UIPopoverControllerDelegate> but why BlocksKit is involved here at all is a mystery. Can someone give me some insight on how to fix the exception? A: BlocksKit is a bit of a red herring. The dismissal code is deallocating the UIDocumentInteractionController too early here: self.openInController = nil; At the earliest, the deallocation should happen after the -documentInteractionControllerDidDismissOpenInMenu: delegate callback method.
[ "stackoverflow", "0016031228.txt" ]
Q: Getting the same coordinates from UIScrollView whether it's zoomed or not Is it possible to get the same coordinates from UIScrollView whether it's zoomed or not. That is, For example, consider a plain screen of 320.0F and 480.0F. Tap on a point; view will give me something like (60.0F, 80.0F). Zooming-in or zooming-out on the view so that it will have either bigger or smaller zoom scale but making sure the zoomed area to contain the point that was tapped which was (60.0F, 80.0F) according to previous zoom scale. Tap on the point again, the view will give me different coordinate value. The Thing is, I want to have the same coordinate value whether the view is zoomed or not. The idea is simple. I want to show images zoomed & interactive without changing its coordinate. Considering an UIScrollView applied of the idea with its height of 1.0 and width of 0.66, I think there would be some pros programming this way, when making an interactive app without using OpenGL, cocos2d or whatever 3D engines out there. Do you guys have any idea if it's supported or not? Either case, please don't wait any second to reply. Thanks A: You can calculate it by yourself using content size as follows, x = (original_Width/ width_after_zooming) * point.x y = (original_height/ height_after_zooming) * point.y
[ "stackoverflow", "0010937108.txt" ]
Q: Android, trying to call a new intent from a touch event I'm trying to make a app that when the screen is touch it will call up a new intent. I have code that catches the touch event in the view class. When I try to create a new intent, Intent(this, cYesNoDisplay.class);, i get a error saying the constuctor is undefined, I'm assuming the constructor is not defined in the view base class, but the Activity class? I'm confused about how to do this, is there a way for my View class that is a member of the intent class, to call it some how???? I figure there must be a wy to do this, still learning Java. Ted A: Your assesment about the View class that you are inside of being the problem is correct. In order to get it working do this: Intent i = new Intent(NameOfYourActivity.this, cYesNoDisplay.class); replace [NameOfYourActivity] with the name of the activity that you are inside of. EDIT: I might have misunderstood what you were doing. If you have actually built your own View class and are overriding onTouch() you actually need to do it a little bit differently. If you don't already have it add: Context ctx; to your classes declarations. in your constructor alter it to store the context that gets passed in as a parameter in the ctx reference that you declared. public [ClassName] (Context c){ this.ctx = c; } Then inside the onTouch() do it like this: Intent i = new Intent(ctx, cYesNoDisplay.class); ctx.startActivity(); EDIT again: The reason you have to use ctx.startActivity(i); is that startActivity() is a method of Context. Since Activity is a Context you don't have to put anything in front of it when you call it from inside an activity. But when you are "inside" of a different class you have to use a reference to a Context to call the method.
[ "stackoverflow", "0033074762.txt" ]
Q: How to split HTML text ignoring spaces in tags I have html text like so: myHTML = 'I like <a class="thing1 thing2">this thing</a>' myHTMLarray = myHTML.Split(' ') >>>['I','like','<a','class="thing1','thing2">this','thing</a>'] I need to ignore the spaces in tags (anything between '<' and '>'). My desired result would be: >>>['I','like','<a class="thing1 thing2">this','thing</a>'] Ideally, I would like to ensure that exactly one word from the text is in each element of the list. Thus break tags or span tags without text other than a space would get included with the previous word. A: Basically you want to ignore spaces inside tags. To do that, you need to keep track of beginning and closing tag angle brackets and to detect spaces occuring elsewhere, but not between the brackets. Once we have only significant spaces, we can detect space/word and word/space boundaries and extract all words using slices. def mysplit(html): in_tag = False in_word = False for i, ch in enumerate(html): if ch == '<': in_tag = True elif ch == '>': in_tag = False space = ch.isspace() and not in_tag if not in_word and not space: in_word = True begin = i elif in_word and space: in_word = False yield html[begin:i] if in_word: yield html[begin:] testhtml = 'I like <a class="thing1 thing2">this thing</a>' print(list(mysplit(testhtml))) # prints: ['I', 'like', '<a class="thing1 thing2">this', 'thing</a>'] Edit: I made a small change to the code posted originally to increase readability a little bit.
[ "stackoverflow", "0027650755.txt" ]
Q: Swig typemaps with smart pointers I have the following c++ class: class Entity : public Watchable { public: [...] std::string value() const { return "Entity::value()"; } }; Entity* create_entity_pointer() { return new Entity(); } watch_ptr<Entity> create_entity_watch_pointer() { return watch_ptr<Entity>(new Entity()); } ... and the following SWIG typemap declaration: %typemap(out) std::string Entity::value { $result = PyString_FromString("Typemapped value"); } The watch_ptr class is exposed to Python and I declare all of the possible types that can be wrapped: %template(EntityWatchPtr) watch_ptr<Entity>; This works as expected when calling the attribute function on an Entity* from Python. However, SWIG ignores the typemap when called on a watch_ptr<Entity>. My python script is as below: from module import * player1 = create_entity_pointer() print(player1) print(player1.value()) player2 = create_entity_watch_pointer() print(player2) print(player2.value()) This produces the following output: <module.Entity; proxy of <Swig Object of type 'Entity *' at 0x100b15ba0> > Typemapped value <module.EntityWatchPtr; proxy of <Swig Object of type 'watch_ptr< Entity > *' at 0x100b613c0> > Entity::value() How can I get the typemap working with smart pointers? I have put the full source code online: https://github.com/kermado/SwigSmartPtrs A: So after some experimentation, it seems that the typemaps must be specified before the SWIG template declarations. In other words, I needed to declare: %template(EntityWatchPtr) watch_ptr<Entity>; before the typemap: %typemap(out) std::string Entity::value { $result = PyString_FromString("Typemapped value"); } in my SWIG interface file. The output of my program is then: <module.Entity; proxy of <Swig Object of type 'Entity *' at 0x10b7b3ba0> > Typemapped value <module.EntityWatchPtr; proxy of <Swig Object of type 'watch_ptr< Entity > *' at 0x10b7ff3c0> > Typemapped value
[ "stackoverflow", "0024359235.txt" ]
Q: Getting NullPointerException while sending data from activity to fragment I have implemented the fragment in android. Now we try to send the data from activity to the fragment. But while sending the data we are getting the NullPointerException in *onCreateView* method of fragment. Following code of Activity. setContentView(R.layout.fragment_1); FragmentManager fm = getFragmentManager(); FragmentTranstction ft = fm.beginTransaction(); Fragment1 f1 = new Fragment1(); String text1 = "prakash"; Bundle bundle = new Bundle(); bundle.putString("sessionName", text1); f1.setArguments(bundle); ft.add(R.id.frag1, f1); ft.commit(); Following code of Fragment: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String strtext = this.getArguments().getString("sessionName"); TextView sessionTitle = (TextView) getView() .findViewById(R.id.session1); sessionTitle.setText(strtext); return inflater.inflate(R.layout.fragment_1, container, false); } what is the mistake i did, because of that i am getting NullPointerException, please help A: Try below code:- @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_1, container, false); String strtext = this.getArguments().getString("sessionName"); TextView sessionTitle = (TextView) view.findViewById(R.id.session1); sessionTitle.setText(strtext); return view; } your not getting view and try to set value on textview.
[ "stackoverflow", "0014080922.txt" ]
Q: One filter is reseting the other. can't apply both of them I'm using 2 filters on one image. The problem is simple to understand, if I'll move one slider the filter will apply fine but when I'll move the other slider the picture will reset to the original _tempImage. I've tried replacing _justNowImage.image = quickFilteredImage; with _tempImage = quickFilteredImage; but the result is a filter that is going crazy. Thanks - (IBAction)sharpenSliderChanged:(id)sender { GPUImageSharpenFilter *sharpenFilter = [[GPUImageSharpenFilter alloc] init]; [sharpenFilter setSharpness:sharpenSlider.value]; UIImage *quickFilteredImage = [sharpenFilter imageByFilteringImage: _tempImage]; _justNowImage.image = quickFilteredImage; } - (IBAction)exposureSliderChanged:(id)sender { GPUImageExposureFilter *exposureFilter = [[GPUImageExposureFilter alloc] init]; [exposureFilter setExposure:exposureSlider.value]; UIImage *quickFilteredImage = [exposureFilter imageByFilteringImage: _tempImage]; _justNowImage.image = quickFilteredImage; } A: UIImage *quickFilteredImage = [exposureFilter imageByFilteringImage: _tempImage]; you are applying different filter to the original image only ..i.e _tempImage add these lines to end of both methods _tempImage = quickFilteredImage
[ "stackoverflow", "0052989660.txt" ]
Q: Pandas, python: How to one-hot-encode a column that contains an array of strings I'm wondering how to one-hot-encode a column containing an array of strings. I'm trying to get from df to df2: import pandas as pd # This is the original data frame df = pd.DataFrame({'menu': [['Italian', 'Greek'], ['Japanese'], ['Italian','Greek', 'Japanese']], 'price': ['$$', '$$', '$']}) df.head() # This is the desired result df2 = pd.DataFrame({'menu': [['Italian', 'Greek'], ['Japanese'], ['Italian','Greek', 'Japanese']], 'price': ['$$', '$$', '$'], 'Italian': [1,0,1], 'Greek': [1,0,1], 'Japanese': [0,1,1] }) df2.head() A: Use MultiLabelBinarizer with join: from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() df = df.join(pd.DataFrame(mlb.fit_transform(df['menu']),columns=mlb.classes_)) print (df) menu price Greek Italian Japanese 0 [Italian, Greek] $$ 1 1 0 1 [Japanese] $$ 0 0 1 2 [Italian, Greek, Japanese] $ 1 1 1 A: You can use pd.get_dummies, pd.apply, DataFrame.join and Series.stack df.join(pd.get_dummies(df.menu.apply(pd.Series).stack()).sum(level=0)) Output: menu price Greek Italian Japanese 0 [Italian, Greek] $$ 1 1 0 1 [Japanese] $$ 0 0 1 2 [Italian, Greek, Japanese] $ 1 1 1
[ "stackoverflow", "0032851107.txt" ]
Q: android checkbox is checked always true I defined a checkbox and assigned no value to it. Every time I click on it and print the value of checkbox, it shows true every time. I put the result in the SharedPreferences and then retrieved it. Why is it always true? public class CallAndSms extends Activity{ static SQLiteDatabase myDB= null; static Context context ; static ListView lv; static CallAndSmsAdaptor adapter; static ArrayList<String> AllData= new ArrayList<String>(); CheckBox save; static SharedPreferences preferences; SharedPreferences.Editor editor=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sms_call); preferences = getSharedPreferences("modes",Context.MODE_PRIVATE); editor = preferences.edit(); save= (CheckBox) findViewById(R.id.save); save.setChecked(preferences.getBoolean("save", true)); context=this; save.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { if ( save.isChecked()){ Log.i("save save", save.isChecked()+""); editor.putBoolean("save", true); } else {editor.putBoolean("save", false);} Log.i("pref", preferences.getBoolean("save", true)+""); } }); } } A: You never apply() (or commit()) your Preference changes. Therefore, you always retrieve the default value.
[ "stackoverflow", "0022250771.txt" ]
Q: Should I sign (with a public/private key) a form based authentication (no SSL)? I want to do a form based authentication. Should I sign (with a public/private key) a form based authentication (with no SSL)? I know it will not avoid a middle man attack, but at least it will secure the value of the password if I hide it in the signature. Is it useless to sign a form authentication? What are the best ways to authenticate without SSL? Do places like Heroku provide SSL for free? I am just playing around and trying to learn cool stuff, don't want to pay :( [UPDATE]: In a very concise way I want to start and maintain a simple session with minimal security through HTTP. How can I do that? The main requirement is to avoid an unauthenticated user from doing requests to the REST API that might change something on the server. A: Assuming that you own the client and the server, and hence can trivially share a secret between them (i.e. some number of random bytes), and notwithstanding the issues of keeping that secret secret, then, assuming that you're using REST such that HTTP request parameters are in the URL and not in the body: Invent a shared secret. We'll call this K. For example, generate 128 random bits: dd if=/dev/random bs=16 count=1 | od -t x1 (Are 128 bits necessary / sufficient? Depends on your requirements...) With each request: Generate a nonce N. This is either: A random number. A timestamp: seconds-since-epoch / time-window-size We'll come back to time window size. Add the nonce as a request parameter: http://foo.com/blah/blah?x=y@mood=dismal?N=0x123456789abcdef Compute a string S containing: The HTTP method, e.g. GET, POST. The complete URL. Compute an HMAC where: K is the key The text (i.e. stuff being HMACed) is S. Append the HMAC as a request parameters. On the server: Strip the HMAC from the request. Extract N from the request. Validate N (see below). Compute S as above. Find the client's K. Compute the HMAC as above. Compare computed HMAC with the one from the request. That means that: I have to know K to send a request. An attacker can't modify the request URL in flight, since that would invalidate the HMAC. However, an observer can capture and replay the request. That's where the nonce comes in: If you use a time-based nonce then The request can be replayed within the time window. The time window must be large enough to accommodate clock differences between client and server, and the network latency. "Validation" means that the server must check the timestamp to ensure that it's "now". If you use a random nonce then the server must remember historic nonces and reject any new requests with previously-seen nonces. Better: use a time window /and/ a random number. The server then just remembers nonces within the current time window. Of course, this needs synchronised clocks and a decent source of random numbers, and doesn't provide confidentiality...
[ "stackoverflow", "0012098546.txt" ]
Q: Scroll issue in Expandable List View I am using an expandable list view . When i click on a parent , it displays the child information properly . However , when I scroll downwards with my child still collapsed , I get an error -bad request for field slot 0,-1 numrows=3 numcolumns=3 . When I scroll up , there is no problem .Or if my child is not collapsed , then there is no problem in scrolling anywhere. MY code for simplecursortree adapter :- Cursor cursor = db.rawQuery("SELECT _id,words from keywords", null); startManagingCursor(cursor); SimpleCursorTreeAdapter mAdapter = new SimpleCursorTreeAdapter(TestActivity.this, cursor, R.layout.exprow, new String[] { DbHandler.D_WORDS}, new int[] { R.id.textText}, R.layout.row,new String[] {DbHandler.C_STATUS,DbHandler.C_CREATED_AT,DbHandler.C_USER}, new int[] {R.id.textStatus,R.id.textCreatedAt,R.id.textUser}) { @Override protected Cursor getChildrenCursor(Cursor groupCursor) { dbhandler=new DbHandler(TestActivity.this); SQLiteDatabase db = dbhandler.getReadableDatabase(); String get=groupCursor.getString(1); Log.d("Post Operation", "Getting cursor for keyword = " +get); String sql="SELECT status,created_at,user from tweets where words='"+get+"'" ; Cursor cursor = db.rawQuery(sql, null); startManagingCursor(cursor); Log.d("TestActivity","Cursor got count"+cursor.getCount()); db.close(); return cursor; } }; A: I solved this by adding an _id in my sql query inside getChildrenCursor . I thought the _id just has to be present in the table .
[ "math.stackexchange", "0001497968.txt" ]
Q: Determine skewness if only mode and median given? For a given set of data the mean is 10.5 and the mode is 9. What c an we deduce about the skewness of the data? A The data is positively skewed. B The data is negatively skewed. C The data is symmetrical. D We cannot deduce anything about the skewness. Answer: D I dont know why the answer is D. My book says. mode = median = mean for a symmetrical data set mode < median < mean for a positively skewed data set mode > median > mean for a negatively skewed data set As you can see the mean is greater than the mode. Then the answer should be A. Looking forward to your answers. A: Does you book have the three rules mode = median = mean for a symmetrical data set mode < median < mean for a positively skewed data set mode > median > mean for a negatively skewed data set or did you find them somewhere else? According to the section in Wikipedia the rules are wrong. If you found them in your book then the book is obviously inconsistent. I do believe that the answer would be D because the skewness is heavily weighed to measure the tails of the distribution. There are just a lot of really weird probability distributions that could be postulated. Think of a broad Gaussian distribution with a mean of 9 mixed with a very very narrow Gaussian which has a mean 11. The tails are dominated by the Gaussian with mean 9. This sort of splits hairs because with sufficient measurement precision the slight skewness could be detected. For an experimentally determined distribution though the skewness could easily be within the noise limits of the measurements.
[ "homebrew.stackexchange", "0000015818.txt" ]
Q: Mash Boiler – What's a good boiler? i'm new to the brewing game and am currently waiting for a few whole grain brews to come of age. One thing i'd like to do is purchase a larger mash boiler and dedicate a bit of space in the shed for my 'micro-brewery'. What makes a good boiler? Where should I start? Any suggestions would be gratefully received! Rik A: Many people use propane turkey fryer setups, consisting of a large propane burner and kettle. The kettle is usually around 6.5-7 gal. so it's barely big enough for a 5 gal. batch, but it works. I won awards for beer made with one. The kettles are often AL, but don't let that throw you. It's perfectly fine and safe.
[ "stackoverflow", "0010775893.txt" ]
Q: is it any difference between executing class from project and class from class library? Assume I have some class in my project. Now I create another "Class library" and move this class there. So to instatiate this class now extra dll (class library dll) need to be loaded. I understand that now I have a little bit another program because now .net need to read two files (original exe file + class library dll file) instead of just one exe file. But other than that are there any difference? After the program is loaded is it important where this class was located originally (exe or dll)? Will I have absolutely the same program in memory? In particular I'm interested if I can introduce any delays at runtime moving my class to class library? This question is result of my previous question how to separate several "a little bit connected" projects? A: After the DLL is loaded into the memory space of your process, there should be no difference in performance compared to if the same code had been included in your EXE project instead. In fact, you will probably see a performance gain over the long run by having common code in a dedicated place. If you tend to put common code into your main projects, you are likely to end up with substantial duplication of code, leading to both maintenance headaches and ultimately a larger memory footprint for your more complex applications).
[ "magento.stackexchange", "0000156201.txt" ]
Q: Magento2 : Reviews error message while submit the review its getting "We can't post your review right now" instead of "You submitted your review for moderation".Why it is showing . Is it backend setting? A: you need to check this file. <?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Review\Controller\Product; use Magento\Review\Controller\Product as ProductController; use Magento\Framework\Controller\ResultFactory; use Magento\Review\Model\Review; class Post extends ProductController { /** * Submit new review action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { $resultRedirect->setUrl($this->_redirect->getRefererUrl()); return $resultRedirect; } $data = $this->reviewSession->getFormData(true); if ($data) { $rating = []; if (isset($data['ratings']) && is_array($data['ratings'])) { $rating = $data['ratings']; } } else { $data = $this->getRequest()->getPostValue(); $rating = $this->getRequest()->getParam('ratings', []); } if (($product = $this->initProduct()) && !empty($data)) { /** @var \Magento\Review\Model\Review $review */ $review = $this->reviewFactory->create()->setData($data); $review->unsetData('review_id'); $validate = $review->validate(); if ($validate === true) { try { $review->setEntityId($review->getEntityIdByCode(Review::ENTITY_PRODUCT_CODE)) ->setEntityPkValue($product->getId()) ->setStatusId(Review::STATUS_PENDING) ->setCustomerId($this->customerSession->getCustomerId()) ->setStoreId($this->storeManager->getStore()->getId()) ->setStores([$this->storeManager->getStore()->getId()]) ->save(); foreach ($rating as $ratingId => $optionId) { $this->ratingFactory->create() ->setRatingId($ratingId) ->setReviewId($review->getId()) ->setCustomerId($this->customerSession->getCustomerId()) ->addOptionVote($optionId, $product->getId()); } $review->aggregate(); $this->messageManager->addSuccess(__('You submitted your review for moderation.')); } catch (\Exception $e) { $this->reviewSession->setFormData($data); $this->messageManager->addError(__('We can\'t post your review right now.')); } } else { $this->reviewSession->setFormData($data); if (is_array($validate)) { foreach ($validate as $errorMessage) { $this->messageManager->addError($errorMessage); } } else { $this->messageManager->addError(__('We can\'t post your review right now.')); } } } $redirectUrl = $this->reviewSession->getRedirectUrl(true); $resultRedirect->setUrl($redirectUrl ?: $this->_redirect->getRedirectUrl()); return $resultRedirect; } } in 2 cases it can fail ( as per error message shared ) as you can see from code. Just debug, do some print_r to check and fix
[ "math.stackexchange", "0001698125.txt" ]
Q: Prove that $\gcd(30m + 5, 11m + 4)|65$ and find the least value of $m \in \mathbb{N}$ such that $\gcd(30m + 5, 11m + 4) = 65$ I have been having trouble with this question for a long time, I just can't seem to see the "trick" that I know is looking me dead in the face. Any nudges in the right direction would be helpful! $$\gcd(30m + 5, 11m + 4)|65 \text{ and find the least value of } m \in \mathbb{N}$$ such that $$\gcd(30m + 5, 11m + 4) = 65$$ A: @The_Big_Cat After working on it for an hour I finally got it. The proof basically uses the fact that $$\gcd(a,b) = \gcd(a, b+ka) = \gcd(a, b-ka)$$ I am using $(a, b)$ for $\gcd(a, b)$ from here. We have to prove that $\gcd(30m+5, 11m+4)|65$. Let $d = (30m+5, 11m+4)$. $$(30m+5, 11m+4)$$ $$= (30m+5 - 3\cdot (11m+4), 11m + 4)$$ $$=(3m+7, 11m+4)$$ $$=(3m+7, 2m-17)$$ $$=(m+24,2m-17)=(m+24, m-41)$$ $$=(m+24-1\cdot (m-41), m-41)$$ $$=(65, m-41)$$ Now we know that $d|65 \implies d| \gcd(30m+5, 11m+4) $. And we have proved the proposition. Now for the second question. We want $d=65$. Consider the fact that every number divides 0. So if we choose $m=41$ then $\gcd(65, 41-41) = 65$. Hence, 41 is the smallest such number. Hope you found the answers useful.
[ "stackoverflow", "0022250352.txt" ]
Q: Programmatically create a django group with permissions In the Admin console, I can add a group and add a bunch of permissions that relate to my models, e.g. api | project | Can add project api | project | Can change project api | project | Can delete project How can I do this programmatically. I can't find any information out there on how to do this. I have: from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? UPDATE: Thanks for the answer you provided. I was able to use that to work out what I needed. In my case, I can do the following: new_group, created = Group.objects.get_or_create(name='new_group') proj_add_perm = Permission.objects.get(name='Can add project') new_group.permissions.add(proj_add_perm) A: Use below code from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) A: I needed to create a default set of groups and permission (view only) for those groups. I came up with a manage.py command that may be useful to others (create_groups.py). You can add it to your <app>/management/commands dir, and then run via manage.py create_groups: """ Create permission groups Create permissions (read only) to models for a set of groups """ import logging from django.core.management.base import BaseCommand from django.contrib.auth.models import Group from django.contrib.auth.models import Permission GROUPS = ['developers', 'devops', 'qa', 'operators', 'product'] MODELS = ['video', 'article', 'license', 'list', 'page', 'client'] PERMISSIONS = ['view', ] # For now only view permission by default for all, others include add, delete, change class Command(BaseCommand): help = 'Creates read only default permission groups for users' def handle(self, *args, **options): for group in GROUPS: new_group, created = Group.objects.get_or_create(name=group) for model in MODELS: for permission in PERMISSIONS: name = 'Can {} {}'.format(permission, model) print("Creating {}".format(name)) try: model_add_perm = Permission.objects.get(name=name) except Permission.DoesNotExist: logging.warning("Permission not found with name '{}'.".format(name)) continue new_group.permissions.add(model_add_perm) print("Created default group and permissions.") A: Inspired by radtek's answer I created a bit better version (in my opinion). It allows specifying model as object (instead of string) and specifying all configuration in one dictionary (instead of several lists) # backend/management/commands/initgroups.py from django.core.management import BaseCommand from django.contrib.auth.models import Group, Permission from backend import models GROUPS_PERMISSIONS = { 'ConnectionAdmins': { models.StaticCredentials: ['add', 'change', 'delete', 'view'], models.NamedCredentials: ['add', 'change', 'delete', 'view'], models.Folder: ['add', 'change', 'delete', 'view'], models.AppSettings: ['view'], }, } class Command(BaseCommand): def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) help = "Create default groups" def handle(self, *args, **options): # Loop groups for group_name in GROUPS_PERMISSIONS: # Get or create group group, created = Group.objects.get_or_create(name=group_name) # Loop models in group for model_cls in GROUPS_PERMISSIONS[group_name]: # Loop permissions in group/model for perm_index, perm_name in \ enumerate(GROUPS_PERMISSIONS[group_name][model_cls]): # Generate permission name as Django would generate it codename = perm_name + "_" + model_cls._meta.model_name try: # Find permission object and add to group perm = Permission.objects.get(codename=codename) group.permissions.add(perm) self.stdout.write("Adding " + codename + " to group " + group.__str__()) except Permission.DoesNotExist: self.stdout.write(codename + " not found")
[ "writers.stackexchange", "0000023311.txt" ]
Q: A question about agents and multiple submissions I very recently finished my first sci-fi novel and sent out agent queries, and fortune has smiled on me. Out of four responses, one was a request for the full manuscript, which was sent about a week ago. The last one I received late Friday, was from someone at the Donald Maas agency requesting a partial. She also asked as a courtesy whether I'd sent it to anyone else. I intend to be honest, but just how honest should I be? Should I mention the full manuscript sent to another largish agency? Do you think this would work in my favor, or will it encourage her to give my work a pass? The bottom line is, what do you think is the logic behind their question? A: Agents are on commission as are you. Her question isn't entirely fair because it is generally assumed if you have no prior commitments with an agent or publisher, you may already have put out dozens of queries. However, since she asked, I would give a brief, complete, and honest answer without using specific brokerage names. Dear Diane: On Friday, June 10, 2016, you requested a partial manuscript to HEARTLESS. Attached is that manuscript. You also wished to know if there were other agents having requested and received submissions. As of Monday, June 13, 2016, I have communicated directly with four agencies including yourself and submitted one complete manuscript. That manuscript was sent electronically Monday, June 6, 2016. Thank you for your time and interest. I look forward to hearing from you., Malebranche male@branche.edu 503-555-1212, I would put no more no less. As to the logic, she's probably just trying to plan her month. An agent who's just decided to read your book needs to reserve a full day of time for, say, every 40,000 words. An agent listed anywhere online as accepting submissions receives at least 15 queries a day.* Try not to let her logic psych you out; it is irrelevant in consideration of supply and demand. If you've gotten this far, congratulations, you've done better than 99%+ of aspiring authors. This information was taken from Jane Friedman's blog on publishing. She is an agent of the finest quality.
[ "stackoverflow", "0010501422.txt" ]
Q: SideBySide Registration-Free COM fail while loading i'm trying to create a C# COM Server which is used by a Delphi App without a COM-Registration. The process is descried on a ms blog - Registration-Free Activation of .NET-Based Components: A Walkthrough I created the necessarily manifest files and i linked them to the assemblies. The App Manifest: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity type="win32" name="Vorg" version="1.0.0.0" /> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" publicKeyToken="6595b64144ccf1df" language="*" processorArchitecture="x86"/> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Vorg.WpfClient" version="1.0.0.0" /> </dependentAssembly> </dependency> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> and the assembly manifest: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity type="win32" name="Vorg.WpfClient" version="1.0.0.0" /> <clrClass clsid="{69A72676-8EA7-3C38-BFBC-F0DFE745C329}" progid="Vorg.WpfClient" threadingModel="Both" name="KundM.Vorg.WpfClient.VorgComClient"> </clrClass> </assembly> those are working fine (i think). sxs does not report any errors. clsid is also correct for the com-class. but when starting the app, it is crashing by an ole exception 0x8013101b. removing the manifests and running the app results of curse in a class not found exception. having the com-class registered the app starts normal without any errors. the exception maybe says something like "wrong framework versions". i tried to specify the runtime in the class manifest. but that didn't solve the problem. what causes the exception? how can i solve that problem? A: Solved. The program Fuslogvw.exe gave me the right direction. this tool shows the loading process of assemblies. to enable it you need to create a reg key. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion dword ForceLog=1 the report is generated there showed me this (sorry german framework): LOG: DisplayName = vorg.wpfclient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null (Fully-specified) === LOG: Diese Bindung startet im default-Load-Kontext. LOG: Der Assembly-Download wurde durchgeführt. Datei-Setup wird begonnen: E:\work\VOrg\bin\vorg.wpfclient.dll. LOG: Die von der Quelle ausgeführte Setup-Phase beginnt. LOG: Der Assemblyname ist: Vorg.WpfClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=174d633867192b66. WRN: Der Vergleich des Assemblynamens führte zum Konflikt: PUBLIC KEY TOKEN. ERR: Der Assemblyverweis entsprach nicht der gefundenen Assemblydefinition. ERR: Das Setup der Assembly konnte nicht abgeschlossen werden (hr = 0x80131040). Die Suche wurde beendet. i did not specified the public key token in the manifests. now i do! the schemafile for manifests from microsoft is wrong! it shows version and some other attributes as optional. i also specified the runtime within the com manifest. it is also possible to specify the framework version by a app.config file. Registration Free COM/.Net interop In-Process Side-by-Side Execution
[ "stackoverflow", "0021151419.txt" ]
Q: Adjust custom view's reported size to include drawn graphics I have a custom view class (call it FooView) that I use as the root element of an xml layout. FooView, in its onDraw(), uses canvas to draw a shape at the bottom edge of FooView. I think that in order for FooView to not cut off the shape, I need to override its onMeasure and do something that modifies FooView's reported height so that it now includes that of the the drawn shape. Is that correct? And if so, what do I need to do? Thanks! A: Yes, if you're creating a custom View, you'll need to override onMeasure() and provide the size that you need it to be. So, in the method signature for onMeasure, you'll get two parameters: widthMeasureSpec heightMeasureSpec You should use the MeasureSpec class to get the restrictions you should respect when sizing the View. /* * This will be one of MeasureSpec.EXACTLY, MeasureSpec.AT_MOST, * or MeasureSpec.UNSPECIFIED */ int mode = MeasureSpec.getMode(measureSpec); //This will be a dimension in pixels int pixelSize = MeasureSpec.getSize(measureSpec); If you get MeasureSpec.EXACTLY, then you should use the pixelSize value for your measured width, no matter what. If you get MeasureSpec.AT_MOST, you should just make sure that you set the measured width no greater than pixelSize. If you get MeasureSpec.UNSPECIFIED, you can take as much room as you need. I usually just interpret this as WRAP_CONTENT. So your onMeasure() method may look something like this: @Override protected void onMeasure (int widthSpec, int heightSpec) { int wMode = MeasureSpec.getMode(widthSpec); int hMode = MeasureSpec.getMode(heightSpec); int wSize = MeasureSpec.getSize(widthSpec); int hSize = MeasureSpec.getSize(heightSpec); int measuredWidth = 0; int measuredHeight = 0; if (wMode == MeasureSpec.EXACTLY) { measuredWidth = wSize; } else { //Calculate how many pixels width you need to draw your View properly measuredWidth = calculateDesiredWidth(); if (wMode == MeasureSpec.AT_MOST) { measuredWidth = Math.min(measuredWidth, wSize); } } if (hMode == MeasureSpec.EXACTLY) { measuredHeight = hSize; } else { //Calculate how many pixels height you need to draw your View properly measuredHeight = calculateDesiredHeight(); if (hMode == MeasureSpec.AT_MOST) { measuredHeight = Math.min(measuredHeight, hSize); } } setMeasuredDimension(measuredWidth, measuredHeight); }
[ "math.stackexchange", "0001565948.txt" ]
Q: Analysis: Show that this series converges, determine the limit. The series in question is $$\sum_{n=2}^{\infty}\frac{2}{n^2-1}.$$ A: We observe that $\frac{2}{n^2-1} = \frac{2}{(n-1)(n+1)}.$ Using partial fractions we see that $\frac{2}{(n-1)(n+1)}=\frac{1}{n-1}-\frac{1}{n+1}.$ Now we compute the $k$-th partial sum: $$S_k=\sum_{n=2}^{k}\frac{2}{n^2-1}=\sum_{n=2}^{k}(\frac{1}{n-1}-\frac{1}{n+1})=1-\frac{1}{3}+\frac{1}{2}-\frac{1}{4}+\frac{1}{3}-\frac{1}{5}+\space...\space+\frac{1}{k-1}+\frac{1}{k+1}=1+\frac{1}{2}-\frac{1}{k}-\frac{1}{k+1}$$ Hence $$\sum_{n=2}^{k}\frac{2}{n^2-1}=\lim_{k\rightarrow \infty}S_k=\lim_{k\rightarrow \infty}(1+\frac{1}{2}-\frac{1}{k}-\frac{1}{k+1})=1+\frac{1}{2}=\frac{3}{2}$$
[ "ru.stackoverflow", "0000898297.txt" ]
Q: Замены бита в 8-битном числе Нужно заменить один бит (с 0 на 1 и наоборот) на выбор в фиксированном 8-битном числе: 10011010 Выбирается число от 1 до 8. Например, при выборе 5 выводится 10010010 (5 бит изменился с 1 на 0) К тому же нужно создать строку для вывода числа (int) в 8-битном формате: String.format("%8s", Integer.toBinaryString(meinInteger)).replace(' ', '0'); A: Получаем позицию 1-8 (place). Откуда её брать и нужно ли её проверять на валидность значения - остаётся за рамками вопроса. В примере просто читается число из консоли Записываем исходное число (number). Для удобства его можно задать бинарным литералом. Хранить ли его в виде int или byte - в данном случае не важно Инвертируем (0 -> 1, 1 -> 0) нужный бит. Для этого можно воспользоваться xor-ом с соответствующей степенью двойки. Степень двойки можно получить из единицы побитовым сдвигом влево на нужное количество позиций. Номера битов считаются справа налево, начиная с нуля, поэтому сдвиг делается не на place или place - 1, а на 8 - place Получаем результирующую строку с помощью указанной в вопросе конструкции Пример итогового кода: Scanner scanner = new Scanner(System.in); int place = scanner.nextInt(); int number = 0b10011010; number ^= 1 << (8 - place); String result = String.format("%8s", Integer.toBinaryString(number)).replace(' ', '0'); System.out.println(result); При вводе 5 вывод: 10010010
[ "stackoverflow", "0023546902.txt" ]
Q: How to use dojo/store/JsonRest to work ArcGIS Rest Service I am receiving the following error when attempting to connect to a sample rest service provided the the Arcgis Javascript API docs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://bcgphp' is therefore not allowed access. Following the dojo docs I have setup my dojo/store as follows. var jsonStore = new JsonRest({ target: "//sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/" }); jsonStore.get(5); I have also tried passing in some headers per the dojo docs, which returned the same error as the code above. var jsonStore = new JsonRest({ target: "//sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/", headers: {'X-Requested-With': 'XMLHttpRequest'} }); jsonStore.get(5); When I use the Arcgis Javascript to Query I am able to make this request with the following code provided in this demo This does not cause any cross domain issues. var queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5"); var query = new Query(); query.returnGeometry = false; query.outFields = [ "SQMI", "STATE_NAME", "STATE_FIPS", "SUB_REGION", "STATE_ABBR", "POP2000", "POP2007", "POP00_SQMI", "POP07_SQMI", "HOUSEHOLDS", "MALES", "FEMALES", "WHITE", "BLACK", "AMERI_ES", "ASIAN", "OTHER", "HISPANIC", "AGE_UNDER5", "AGE_5_17", "AGE_18_21", "AGE_22_29", "AGE_30_39", "AGE_40_49", "AGE_50_64", "AGE_65_UP" ]; queryTask.execute(query, showResults); function showResults (results) { console.log(results); } I would really like to use the dojo.store if possible so that I can structure my app using the MVC technique provided by Dojo A: dojo/store/JsonRest expects the server to adhere to a specific protocol, but ArcGIS services have their own specification. See the Implementing a REST Server section of the JsonRest docs. So regardless of any CORS issues, I don't think is possible to point dojo/store/JsonRest at an ArcGIS Online service w/o wrapping it in some RESTful service that adheres to the protocol the JsonRest store expects. Depending on the number of records in your service and how often you will need to write back to the server, you might try pulling all the records you need into a dojo/store/Memory store using the QueryTask when the page loads. I've worked on a project where we successfully used that technique.
[ "stackoverflow", "0029550705.txt" ]
Q: Is it possible to send a value to php file whilst performing a jquery GET request I am making a GET request in jQuery to a PHP file and need to send a variable to the PHP for use in the query. Is this possible? I want to grab the emailAddress variable in the php. function getData(){ var emailAddress = "myemail@gmail.com"; $.getJSON('myfile.php', function(data){ $.each(data, function(key, val) { $("#userAge").val(val.age); }); }); } So in the PHP i want to be able to select all that have the email address that I have passed in. I have to use jQuery and PHP as i am developing a hybrid app in PhoneGap that cant use PHP directly. Thanks. A: The optional second argument is used for passing parameters: $.getJSON('myfile.php', { email: emailAddress }, function(data) { $.each(data, function(key, val) { $("#userAge").val(val.age); }) }); In the PHP script use $_GET['email'] to get the email address.
[ "stackoverflow", "0038121014.txt" ]
Q: PostgreSQL: Find permission for element, traverse up to root Here is the DB Structure I'm using Item ---- ID [PK] Name Desc Links ----- ID [FK] LID [FK] -- Link ID LType -- Link Type (Parent, Alias) Permission ---------- ID [FK] CanRead CanWrite CanDelete Let's assume, we have the below data in the table Item Table ----------- ID Name Desc ================= 0 Root Base Item 1 One First 2 Two Second 3 Three Third 4 Four Forth 5 Five Fifth 6 Six Sixth Links Table ----------- ID LID LType ================== 1 0 Parent 2 0 Parent 3 1 Parent 4 2 Parent 5 4 Parent 6 5 Parent 0 |- 1 | |- 3 |- 2 |- 4 |- 5 |- 6 Permission Table ----------------- ID CanRead CanWrite CanDelete ===================================== 0 T T T 2 T F F 5 T T F 6 F F F Question is, if I want the permission for 6, I can directly query Permission table and get the Read/Write/Delete value. However if I want the permission for 4, it is not present in permission table, so I need to find the parent, which is 2, since I have the permission for 2 I can return it. More tricky, If I want the permission for 3, I check in permission table, it is not present, see for the parent (1), which is not present, go for it's parent which is (0-Root), and return the value. This can be for any level, imagine we do not have records 2, 5, 6 in permission table, so when I lookup for 6, then I need to traverse all the way up to root to get the permission. Note: We always have the permission present for Root. I want this to be done in DB layer than application layer, so any help in writing SQL query (recursive) or Stored Procedure would be great. Thanks!! A: You can use a RECURSIVE CTE for this: WITH RECURSIVE Perms(ID, Name, ParentID, CanRead, CanWrite, CanDelete) AS ( SELECT i.ID, i.Name, l.LID AS ParentID, p.CanRead, p.CanWrite, p.CanDelete FROM Item AS i LEFT JOIN Permission AS p ON i.ID = p.ID LEFT JOIN Links AS l ON i.ID = l.ID ), GET_PERMS(ID, ParentID, CanRead, CanWrite, CanDelete) AS ( -- Anchor member: Try to get Read/Write/Delete values from Permission table SELECT ID, ParentID, CanRead, CanWrite, CanDelete FROM Perms WHERE ID = 3 UNION ALL -- Recursive member: terminate if the previous level yielded a `NOT NULL` result SELECT p.ID, p.ParentID, p.CanRead, p.CanWrite, p.CanDelete FROM GET_PERMS AS gp INNER JOIN Perms AS p ON gp.ParentID = p.ID WHERE gp.CanRead IS NULL ) SELECT CanRead, CanWrite, CanDelete FROM GET_PERMS WHERE CanRead IS NOT NULL The RECURSIVE CTE terminates when a Permission record has been retrieved from the database. Demo here
[ "stackoverflow", "0063416229.txt" ]
Q: How can I display my products from the cart? I am using Melihovv ShoppingCart. I want to display all products inside cart but I couldn't. It shows the page but the products are not displaying. Here is my code public function store(Request $request) { $cartItem = Cart::add($request->id, $request->name, $request->price, 1); return view('pages.cart')->with([ 'cartItem' => $request->cartItem ]); } And here is my view: @if (!empty($cartItem) && count($cartItem) > 0) @foreach ($cartItem as $product) {{ $product }} @endforeach @endif A: to display the content of the cart, I think you should use Cart::content()
[ "stackoverflow", "0044215118.txt" ]
Q: Minimalistic Clean Responsive Layout in CSS3 Flexbox: Desktop <> Mobile toggle I am trying to achieve a simple clean minimalistic responsive layout in CSS3 Flex, where: A) in the desktop mode the body contains three vertical elements side by side "all in one row", and; B) an alternative vertical oriented mobile version mode where the body contains the elements as rows on top of eachother, "all in one column". But my code is broken somewhere as I dont see the mobile version kicking in when resizing the the window to narrow vertical orientation. What am I missing? *{ margin: 0; padding: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body { display: flex; min-height: 100vh; flex-direction: row; flex: 1; background: yellow; } main { flex: 2; background: tomato; } nav { flex: 1; background: tan; } aside { flex:1; background: thistle; } /* FOR MOBILE PHONES */ @media only screen and (orientation: vertical) and (max-width: 768px) { body{ flex-direction: column; } main { background: crimson; /* test to see if mobile mode is activated */ } } <body> <main>content</main> <nav>nav</nav> <aside>aside</aside> </body> A: orientation: can be portrait or landscape: body { display: flex; min-height: 100vh; flex-direction: row; flex: 1; background: yellow; } main { flex: 2; background: tomato; } nav { flex: 1; background: tan; } aside { flex: 1; background: thistle; } /* FOR MOBILE PHONES */ @media only screen and (orientation: portrait) { body { flex-direction: column; } main { background: crimson; } } <body> <main>content</main> <nav>nav</nav> <aside>aside</aside> </body>
[ "stackoverflow", "0020925755.txt" ]
Q: Configuring OpenSessionInView filter with Spring Hibernate Application I am working on a Spring Hibernate web application Earlier I was loading the Spring Configuration with just dispatcher-servlet.xml without using the ContextLoaderListener but when I implement the OpenSessionInView pattern I have to provide a ContextLoaderListener in web.xml and create a new applicationContext.xml & move the hibernate configuration from dispatcher-servlet.xml to applicationContext.xml. I have some doubts regarding this change. Below is the code which is working fine. web.xml <display-name>PetClinic</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/forms/*</url-pattern> </servlet-mapping> <filter> <filter-name>hibernateFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>/forms/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> dispatcher-servlet.xml <context:component-scan base-package="com.petclinic"/> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages"/> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/view/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> applicationContext.xml <context:annotation-config /> <!-- <context:property-placeholder> XML element automatically registers a new PropertyPlaceholderConfigurer bean in the Spring Context. --> <context:property-placeholder location="classpath:database.properties" /> <!-- enable the configuration of transactional behavior based on annotations --> <tx:annotation-driven transaction-manager="hibernateTransactionManager"/> <!-- Creating DataSource --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${database.driver}" /> <property name="url" value="${database.url}" /> <property name="username" value="${database.user}" /> <property name="password" value="${database.password}" /> </bean> <!-- To persist the object to database, the instance of SessionFactory interface is created. SessionFactory is a singleton instance which implements Factory design pattern. SessionFactory loads hibernate.cfg.xml and with the help of TransactionFactory and ConnectionProvider implements all the configuration settings on a database. --> <!-- Configuring SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>com.petclinic.Owner</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> </props> </property> </bean> <!-- Configuring Hibernate Transaction Manager --> <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> A. Can anyone tell me the reason for creating a new applicationContext.xml and moving the hibernate code to it? Why not just let the code be in dispatcher-servlet.xml? B. To use filters in Spring do we need a ContextLoaderListener, without it won't the filter work? A: This is because the spring application has usually two contexts: a root context and a per servlet dispatcher context. The idea behind this is that an application can have multiple servlet contexts with beans such as the controllers, and each servlet context has an isolated parent root context where beans common to all the application are available. The beans from the root context such as the session factory can be injected in the servlet context beans (such as the controllers), but not the other way around. The OpenSessionInViewFilter retrieves the session factory from the common root application context (applicationContext.xml) because it cannot know upfront in which servlet context to look. The code of OpenSessionInViewFilter calls lookupSessionFactory, which in turn ends up calling this code: /** * Find the root WebApplicationContext for this web application, which is * typically loaded via {@link org.springframework.web.context.ContextLoaderListener}. * <p>Will rethrow an exception that happened on root context startup, * to differentiate between a failed context startup and no context at all. * @param sc ServletContext to find the web application context for * @return the root WebApplicationContext for this web app, or {@code null} if none * @see org.springframework.web.context.WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE */ public static WebApplicationContext getWebApplicationContext(ServletContext sc) { return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); } So this answers question A: OpenSessionInViewFilter needs to find the session factory in the root application context, and this explains why you need to move the session factory from the servlet context (dispatcher-servlet.xml) into the root context (applicationContext.xml). For question B, not all filters of the applictaion have this problem, this is specific of filters that need access to some spring bean and they need to know in which context to look.
[ "stackoverflow", "0008879423.txt" ]
Q: Using nth-child to style item 4 and onwards I have a list item where I'd like the 4th item and onwards to have a different background-color. I've tried the following: li:nth-child(4) { background-color:blue; } This styles only the 4th item. I then tried the following in the hope that it would style 4th item and onwards, but it didn't work: li:nth-child(4+) { background-color:blue; } How can I get this to work without having to specify 4th, 5th, 6th, 7th etc...? A: Use :nth-child(n+5) (CSS indexes start at 1). Demo: http://jsfiddle.net/nTZrg/1/ li:nth-child(n+5) { background-color:blue; }
[ "stackoverflow", "0042125550.txt" ]
Q: Nested flex containers with inner scroll bar and snug/covering lower container I have a nested structure of flexbox containers, where an inner container needs to show potentially large content in a scrollable pane. However, sometimes the content is small. There's an additional container that needs to be always visible, and that I'd like to have just below the scrollable content, i.e. not far down at the bottom unless the scrollable pane content "pushes" it down - the viewport can be much larger than the content. What I have right now does everything except have the "Right bottom" come up when the "Right top content" is small: JsFiddle: https://jsfiddle.net/u6dou3wf/10/ .main { display: flex; height: 200px; } .left { flex: 1 1 0; background: red; } .right { flex: 0 0 0; display:flex; flex-direction: column; background: green; padding: 4px; } .right-top-wrapper { flex: 1 1 0; overflow-x: auto; overflow-y: scroll; background: blue; } .right-top-content { margin: 4px; height:100px; width:100px; background: pink; } .right-bottom { flex: 0 0 0; background: yellow; margin: 4px; } <div class="main"> <div class="left"> Left content </div> <div class="right"> <div class="right-top-wrapper"> <div class="right-top-content"> Right top content </div> </div> <div class="right-bottom"> Right bottom </div> </div> </div> How can I get the "Right bottom" to be snugly below the "Right top content", i.e. get the blue section to shrink if the pink section is small, and then grow to whatever size is available inside the green (minus yellow) if the pink section is large? I have tried .right-top-wrapper { flex: 0 1 0; } but then it shrinks to nothing (a consequence of overflow-y: scroll or auto, which I have to have to allow large "Right top content"). A: Your blue container (.right-top-wrapper) is set to flex: 1 1 0. This breaks down to: flex-grow: 1 flex-shrink: 1 flex-basis: 0 It's the flex-grow: 1 that's forcing the element to consume all available space in the column, leaving the content (pink box) behind, and pinning the yellow "Right bottom" box to the bottom. You wrote: I have tried .right-top-wrapper { flex: 0 1 0; } but then it shrinks to nothing (a consequence of overflow-y: scroll or auto, which I have to have to allow large "Right top content"). No, it's a consequence of flex-basis: 0, which translates to height: 0. Without flex-grow: 1 to expand the height like before, the box has a zero height. Try this instead: .right-top-wrapper { flex: 0 1 auto; } Now flex-grow is disabled and the box takes the height of the content. You also need to release the fixed height on the pink box so it expands along with the blue container. .right-top-content { /* height: 100px */ min-height: 100px; /* new */ } revised fiddle (little content) revised fiddle (lots of content)
[ "stackoverflow", "0044359953.txt" ]
Q: Are global variables in C++ stored on the stack, heap or neither of them? I have an exam on tuesday and I've noticed that, this question is one that my teacher asks a lot in his texts. Initially I was pretty sure that the correct answer had to be "None of them", since global variables are stored in the data memory, but then I've found this book from Robert Lafore, called "Object Oriented Programming in C++" and it clearly states that, according to the C++ standard, global variables are stored on the heap. Now I'm pretty confused and can't really figure out what's the correct answer to the question that has been asked. Why would global variables be stored on the heap? What am I missing? Thanks in advance. EDIT: Link to the book - page 231 A: Here is what the book says on page 205: If you’re familiar with operating system architecture, you might be interested to know that local variables and function arguments are stored on the stack, while global and static variables are stored on the heap. This is definitely an error in the book. First, one should discuss storage in terms of storage duration, the way C++ standard does: "stack" refers to automatic storage duration, while "heap" refers to dynamic storage duration. Both "stack" and "heap" are allocation strategies, commonly used to implement objects with their respective storage durations. Global variables have static storage duration. They are stored in an area that is separate from both "heap" and "stack". Global constant objects are usually stored in "code" segment, while non-constant global objects are stored in the "data" segment.
[ "math.stackexchange", "0001216775.txt" ]
Q: How do we know Euclid's sequence always generates a new prime? How do we know that $(p_1 \cdot \ldots \cdot p_k)+1$ is always prime, for $p_1 = 2$, $p_2 = 3$, $p_3 = 5$, $\ldots$ (i.e., the first $k$ prime numbers)? Euclid's proof that there is no maximum prime number seems to assume this is true. A: That's not true. Euclid's proof does not conclude that this expression is a new prime, it concludes that there exists primes that were not in our original list, that lie between the $k'th$ prime and $p_{1}p_{2}...p_{k} + 1$ (including $p_{1}p_{2}...p_{k} + 1$). Among those extra primes that must exist, $p_{1}p_{2}...p_{k} + 1$ may be one of them, or it may not be. It doesn't matter, either way, there are more primes than listed in our initial list. We have a counter example as soon as $2*3*5*7*11*13 + 1$. A: Euclid's proof does not deduce that $\,N = 1+p_1\cdots p_k\,$ is prime. Rather, Euclid's proof deduces that $\,N\,$ is coprime to all $\,p_i,\,$ so the prime factors of $\,N\,$ cannot include any $\,p_i.\,$ But since $\,N> 1\,$ it has some prime factor $\,p\,$ (e.g. its least factor $> 1),\,$ which yields a prime $p$ distinct from all $\,p_i$ The key idea is not that Euclid's sequence $\ f_1 = 2,\,\ \color{#0a0}{f_{n}} = \,\color{#c00}{\bf 1} + f_1\cdots f_{n-1}$ is an infinite sequence of primes but, rather, that it is an infinite sequence of coprimes, i.e. $\,{\rm gcd}(f_n,f_k) = 1\,$ when $\,n>k,\,$ since then any common divisor of $\,\color{#0a0}{f_n},\,\color{#b0f}{f_k}\,$ must divide $\ \color{#c00}{\bf 1} = \color{#0a0}{f_n} - f_1\cdots \color{#b0f}{f_k}\cdots f_{n-1}.$ Any infinite sequence $\,f_n > 1 \,$ of coprimes yields an infinite sequence of distinct primes $\, p_n $ obtained by choosing $\,p_n$ to be any prime factor of $\,f_n,\,$ e.g. the least prime factor. Remark $\ $ This misunderstanding often arises from reading a proof of Euclid's result reformulated to be by contradiction (which was not used by Euclid). In one form, it can be deduced that if there are only finitely many primes $\,p_1,\ldots p_k,\,$ then $\,n = 1+p_1\cdots p_k\,$ is prime, because $\,n > 1\,$ has no smaller prime factors. But this does not imply that $\,n\,$ is actually prime because the deduction depends on the hypothesis that there are only finitely many primes, which is false in the (actual) natural numbers $\,\Bbb N.\,$ Because the proof by contradiction is carried out in the hypothetical universe "$\Bbb N$ with finitely many primes", one cannot apply any of its conclusions to the (actual) universe $\Bbb N.\,$ It is the nature of proofs by contradiction that one can deduce all sorts of nonintuitive results. When this occurs in a universe like $\,\Bbb N\,$ where we have very strong intuition, it can be quite challenging to keep things straight.
[ "askubuntu", "0001020644.txt" ]
Q: Are Snaps installed system wide, or per user? Are Snaps installed system wide, or are they only installed for the user who is logged in, and installing them? on Ubuntu 18.04? I don't see any option like Flatpak's --user to install Snaps for a single user. And what is the command to install a Snap for a single user? A: Installed snaps are available to all users.
[ "stackoverflow", "0000544626.txt" ]
Q: Mistaken mass deletes and updates -- design error? Why didn't the designers of SQL require a keyword (e.g. "All") for any Update or Delete statements that don't have a Where clause? Was it just an oversight on their part? They would have saved so much grief (not to mention jobs!) if they had done that! A: After making this mistake I've religiously gotten into the habit of typing BEGIN TRANSACTION; -- Select Blah -- Some Sql here that changes Blah -- Select Blah ROLLBACK TRANSACTION; then running it, making sure the rows affected count looks sane, staring at the Sql some more, then replacing ROLLBACK with COMMIT and running it for good. It only takes 15 extra seconds and saves me some heartburn, especially on complex UPDATE...FROM type queries. And indeed, I agree, there should have been an ALL keyword or some such to prevent flub ups like this. Or, a built in option in your Sql query environment that acts like the cash registers when I'd have a finger spasm and double-punch the screens at Taco Bell: "Did you REALLY mean 99 tacos?" A: There are so many other really easy ways to corrupt your SQL data that trying to catch any one of them is really just a waste of time. An UPDATE without a WHERE is just as bad (arguably worse). Leaving off a clause or two in a SELECT joining multiple tables could cause it to print to your console, instead of one row, a trillion. Work on replicated slaves when possible. When you can't, make sure backups are available that won't be instantly corrupted by updates. And when typing UPDATE or DELETE queries, type slowly and carefully and always stare at it for a few seconds before you type the closing semicolon.
[ "unix.stackexchange", "0000531607.txt" ]
Q: explanation of PS1 in bashrc PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ' I tried experimenting with this line a lot and was able to get a few characters, but I still don't get the complete meaning of the line. Can anyone please provide a detailed explanation of the line? I got what I could from this resource A: ${debian_chroot:+($debian_chroot)} -- checks if the variable debian_chroot is set, and expands to its value in parenthesis if it is. Debian's bashrc sets the variable earlier, I never use it so, I don't remember how its set. ${var:+word} is a standard parameter expansion. \[ .. \] -- marker for non-printing characters, namely the color codes here. Bash needs these to calculate the length of the prompt so that the UI works properly \033[01;32m -- (that's ESC, backslash, etc.) terminal control code to set the output color (check any source on that for the meaning of the numbers) \u@\h -- username, literal @, hostname \w -- current working directory \$ -- a dollar sign, unless you're root, in which case a hash sign # Note that there's a trailing space before the ending quote. Without it, the cursor would right against the dollar sign, which looks ugly. See Bash's manual for a reference on the backslash-codes it interprets in prompts.
[ "stackoverflow", "0054257818.txt" ]
Q: Need button to float to bottom of card pug/css I have a card with text, an image, and a contact button. I need the button to float to the bottom of the card regardless of how much text is in each card so all cards have a uniform contact button in the bottom position. How one currently looks: pug code: .column.is-one-third .card img(src='../images/results.png', class="teamImage") .h3.is-3.title John Doe .p.title Director .p Synth polaroid bitters chillwave pickled. Vegan disrupt tousled, |Portland keffiyeh aesthetic food truck sriracha cornhole singleorigin |coffee church-key roof party. Leggings ethical |McSweeney's, normcore you probably haven't heard of them |Marfa organic squid. .button Contact css: .card { background-color: white; box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); color: #404040; max-width: 100%; text-align: justify; position: relative; } .button { border: none; outline: 0; display: inline-block; padding: 8px; color: white; background-color: rgb(5, 71, 168); text-align: center; cursor: pointer; width: 100%; } A: Flexbox can do that. .card { display:flex; flex-direction:column; } .button { margin-top:auto; } .card { width:33%; margin:auto; display: flex; flex-direction: column; height:90vh; border:1px solid red; } .button { margin-top: auto; } <div class="card"> <h2>Title</h2> <h3>Name</h3> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Molestiae, voluptatum?</p> <button class="button">button</button> </div>
[ "math.stackexchange", "0001737626.txt" ]
Q: Terminology: "Unique algebraic combination" I recently came across the term "unique algebraic combination" and wasn't sure what this meant. For example, for two numbers $a$ and $b$ what are their "unique algebraic combinations"? Would it be something like $a + b$ $a - b$ $a * b$ $a / b$ A: This is not a standard term in mathematics. I would advise you search your book to see if it isn't defined earlier.
[ "stackoverflow", "0059351396.txt" ]
Q: Inserting Multiple Rows in Excel is very slow The code is working but it is taking more time to insert rows. I normally insert more than 500 line items. It is updating one by one. How can I speed up the macro? Sub InsertMultipleRows() Dim numRows As Integer Dim counter As Integer 'Select the current row ActiveSheet.Unprotect Range("C23").Select ActiveCell.EntireRow.Select On Error GoTo Last numRows = InputBox("Enter number of rows to insert", "Insert Rows") 'Keep on inserting rows until we reach the desired number For counter = 1 To numRows Selection.Insert Shift:=xlToDown, CopyOrigin:=xlFormatFromRightorAbove Next counter Last: Exit Sub End Sub A: The code that you are using is an inefficient way of inserting rows. Try this one liner Range("C23").EntireRow.Resize(numRows).Insert Couple of other things Avoid using Integer when working with rows. Use Long to avoid possible Overflow error. Avoid the use of .Select. You may want to see How to avoid using Select in Excel VBA If you are using an Inputbox to accept number then as @AJD suggested, do a proper validation. OR better still, use Application.InputBox method (Excel) with Type:=1.
[ "unix.stackexchange", "0000506683.txt" ]
Q: Execute shell script without password I have a shell script with a bunch of commands, one of them needs root. I want to execute the script without entering passwords at all: neither before script nor in the middle of execution. How can I make it? A: sudo is a common practice , to give privileges to some user . a simple example with multiple command : i want the user nagios to use a specific command to dump informations. nagios ALL=(root) NOPASSWD: /usr/bin/dmidecode, /bin/netstat -ntp Another example , you manage multiple servers , you want to deploy the same sudoers file on each . and the rule will be valid only on one server . nagios srvpeug1208 =(root) NOPASSWD: /usr/bin/dmidecode, /bin/netstat -ntp this will allow nagios on srvpeu1208 to execute some commands .
[ "stackoverflow", "0033504122.txt" ]
Q: Difficulties in routes with translations in Laravel 5 Good afternoon ! I have problems with file routes , I am using this format to recieve the view Route::group(array('prefix' => Config::get('app.locale_prefix')), function() { Route::get( '/{contact}', function () { return View::make('main'); } ); }); but I prefer using the following instruction Route::get('home', 'HomeController@index'); Could anyone help to me for substitute the first methodology for the second ? A: Just create a controller file in your app/Http/Controllers folder called HomeController.php. You can do that manually or by running the following command in your app directory: php artisan make:controller HomeController --plain In the newly generated controller you need to add the index method that returns your view like you did in your route closure: namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class HomeController extends Controller { public function index() { return View::make('main'); } } And that's about all there is to it, you can now use the route definition Route::get('home', 'HomeController@index'); and it will run the code in your index action. In the future it would really pay off to read the documentation first, because in most cases it offers all the information you need.
[ "gis.stackexchange", "0000072045.txt" ]
Q: RFE raster images datum conflict I'm using ArcGIS 9.3. I've downloaded RFE (Rainfall Estimate) images from FEWS NET, and I'm trying to load them on ArcMap, to clip them using Mozambique's shape. But as the RFE images related to Southern Africa come with unknown coordinate system, I'm having problems projecting RFE and Mozambique shape on the same map. I also tried to put them both at the same GCS which is WGS_1984, and then use the same projection for both. It didn't work. I'm a GIS beginner. Which is my mistake in this projecting and reprojecting issue? A: It may depend on which version of the RFE data you download. If you search "coordinate system" on the website, you get this page which states that the Daily datasets are in a geographic coordinate system. The Dekadal data is projected into an Albers coordinate system: Origin of latitudes : 1.000000 deg Central meridian : 20.000000 deg First std parallel : -19.000000 deg Second std parallel : 21.000000 deg Projection = ALBERS Conical Equal-area projection uses the clarke 1866 spheroid This is not great as "Clarke 1866 spheroid" means that they just munged the data together and lost any original GCS/datum information. Perhaps the data accuracy isn't good enough that the GCS/datum info doesn't matter. The effect of ignoring the datum information is, at most, a few hundred meters. With this data, there's not an easy way to identify how far off it is anyway versus another dataset. First, I would define the data using the above definition. To get the GCS, look in the geographic coordinate systems\spheroid-based folder. Add the raster to a data frame, and set the data frame's coordinate system to match the Mozambique data. Ignore any datum warning messages. Do the clip now, or export the raster into the Mozambique coordinate system by right-clicking the layer in the table of contents and selecting data, export data. In that dialog, choose the data frame's coordinate system. Another workflow is use WGS84 (or whatever GCS the Mozambique is using) when you define the Albers-based coordinate system.
[ "stackoverflow", "0036011331.txt" ]
Q: How to remove first and last values in a FOR EACH loop? I am appending values to input boxes from a Google Maps application. Each marker has a "routeTitle" attribute. I am able to get the "first point", "last point" and "all points" and appending them to input boxes. However, how can I input all values except the first and last into an input box? In other words, all points between first and last. for( var i = 0; i < markers.length; i++ ){ $("#startpoint").val(markers[0].routeTitle); $("#endpoint").val(markers[markers.length - 1].routeTitle); $("#allpoints").val(markers[i].routeTitle); $("#checkpoints").val( not sure); }; A: put the first and last values outside the loop and then amend the loop structure to start from the second value and go until the second last value. $("#startpoint").val(markers[0].routeTitle); $("#endpoint").val(markers[markers.length - 1].routeTitle); for( var i = 1; i < markers.length-2; i++ ){ $("#allpoints").val(markers[i].routeTitle); $("#checkpoints").val( not sure); };
[ "stackoverflow", "0031449440.txt" ]
Q: Excel Index Match - Partial strings with Multiple Results I'm trying to tweak this piece of code I found in a sample spreadsheet online but I can't quite get my head around it. The original spreadsheet basically does an INDEX/MATCH based on a user-defined lookup and lists the matches neatly in a concatenated list. The sample spreadsheet's output looks like this: http://i.stack.imgur.com/DyahB.png - Sample Excel Output (Note how there are no gaps between the first and second matches) The underlying algorithm is: =IF(ISERROR(INDEX($A$1:$B$8,SMALL(IF($A$1:$A$8=$E$1,ROW($A$1:$A$8)),ROW(1:1)),2)),"",INDEX($A$1:$B$8,SMALL(IF($A$1:$A$8=$E$1,ROW($A$1:$A$8)),ROW(1:1)),2)) Now, I want the lookup to instead retrieve PARTIAL matches, and in addition, generate the outputs horizontally like so: http://i.stack.imgur.com/ShED0.png - Output is generated horizontally based on partial matches I'm not sure how I would go about doing this. It seems like I would somehow try and change the IF condition to return true on partial matches but I can't get my head around it. Please help! A: Assuming by "partial match" you mean text that starts with the value in L1 then use this formula in N1 =IFERROR(INDEX($I$2:$I$8,SMALL(IF(LEFT($H$2:$H$8,LEN($L$1))=$L$1,ROW($I$2:$I$8)-ROW($I$2)+1),COLUMNS($N1:N1))),"") confirm with CTRL+SHIFT+ENTER and copy across For a match anywhere in the text you can use this version =IFERROR(INDEX($I$2:$I$8,SMALL(IF(ISNUMBER(SEARCH($L$1,$H$2:$H$8)),ROW($I$2:$I$8)-ROW($I$2)+1),COLUMNS($N1:N1))),"") Neither formula is case-sensitive, although you can easily make the latter so by changing SEARCH to FIND Use of IFERROR function means you don't need repetition for error handling - needs Excel 2007 or later version
[ "stackoverflow", "0015314454.txt" ]
Q: overflow scrolling with no scrollbars How do I create a div that has a max width/height but instead of having scollbars have nothing yet still be able to scroll? (usually done via mouse wheel, selecting text and moving the mouse down or arrrows down) I tried hidden but that doesn't let me scroll. The other options either doesn't allow it to have a max hight or puts scrollbars. Here is a sample demo. I'd like to have no scroll bar but be able to see eof. <div id=main> Text text text text text text text text... Text text text text text text text text... eof </div> #main { max-height: 400px; /*overflow: auto;*/ overflow: hidden; } A: How about pushing the scrollbar into the hidden area ? html, body { padding: 0; margin: 0; overflow: hidden; } #container { position: absolute; left: 0; top: 0; right: -30px; bottom: 0; padding-right: 15px; overflow-y: scroll; max-height: 400px; } JSFiddle. Example from SO - Hide the scrollbar but keep the ability to scroll with native feel.
[ "stackoverflow", "0062069350.txt" ]
Q: Transformer-XL: Input and labels for Language Modeling I'm trying to finetune the pretrained Transformer-XL model transfo-xl-wt103 for a language modeling task. Therfore, I use the model class TransfoXLLMHeadModel. To iterate over my dataset I use the LMOrderedIterator from the file tokenization_transfo_xl.py which yields a tensor with the data and its target for each batch (and the sequence length). Let's assume the following data with batch_size = 1 and bptt = 8: data = tensor([[1,2,3,4,5,6,7,8]]) target = tensor([[2,3,4,5,6,7,8,9]]) mems # from the previous output My question is: I currently pass this data into the model like this: output = model(input_ids=data, labels=target, mems=mems) Is this correct? I am wondering because the documentation says for the labels parameter: labels (:obj:torch.LongTensor of shape :obj:(batch_size, sequence_length), optional, defaults to :obj:None): Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can set lm_labels = input_ids So what is it about the parameter lm_labels? I only see labels defined in the forward method. And when the labels "are shifted" inside the model, does this mean I have to pass data twice (additionally instead of targets) because its shifted inside? But how does the model then know the next token to predict? I also read through this bug and the fix in this pull request but I don't quite understand how to treat the model now (before vs. after fix) Thanks in advance for some help! Edit: Link to issue on Github A: That does sound like a typo from another model's convention. You do have to pass data twice, once to input_ids and once to labels (in your case, [1, ... , 8] for both). The model will then attempt to predict [2, ... , 8] from [1, ... , 7]). I am not sure adding something at the beginning of the target tensor would work as that would probably cause size mismatches later down the line. Passing twice is the default way to do this in transformers; before the aforementioned PR, TransfoXL did not shift labels internally and you had to shift the labels yourself. The PR changed it to be consistent with the library and the documentation, where you have to pass the same data twice.
[ "ru.stackoverflow", "0000729462.txt" ]
Q: Как заменить prev/next из owl carousel на стрелки из font-awesome? Собственно вопрос. Если включить навигацию там кнопки prev/next. Как заменить на иконки из font awesome? A: Можно воспользоваться параметром в функции и передать нужный ՝HTML՝ или просто текст, например։ $(".slide").owlCarousel({ items : 6, loop : true, margin : 10, nav : true, navText : ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"] }); и всё..
[ "stackoverflow", "0000754302.txt" ]
Q: How to get ODBC connection by name? Given a User DSN how do I create an ODBC connection to that data source in .Net 3.5? A: Here is a tutorial describing the entire process. Basically, you do: OdbcConnection connection = new OdbcConnection("DSN=MyDataSourceName");
[ "stackoverflow", "0012853283.txt" ]
Q: Execute function only at first run ios Is there any way by which i can run a function only once (when the app is updated or installed)? I can't use run script as i should use objective c function. A: NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; if ( ![userDefaults valueForKey:@"version"] ) { // CALL your Function; // Adding version number to NSUserDefaults for first version: [userDefaults setFloat:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue] forKey:@"version"]; } if ([[NSUserDefaults standardUserDefaults] floatForKey:@"version"] == [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue] ) { /// Same Version so dont run the function } else { // Call Your Function; // Update version number to NSUserDefaults for other versions: [userDefaults setFloat:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue] forKey:@"version"]; } A: This is the Swift conversion of Bhupendra's answer: let infoDictionary: NSDictionary? = NSBundle.mainBundle().infoDictionary // Fetch info.plist as a Dictionary let temp: NSString = infoDictionary?.objectForKey("CFBundleVersion") as NSString let val: Float = temp.floatValue var userDefaults = NSUserDefaults() if userDefaults.valueForKey("version") == nil { // Call function // Adding version number to NSUserDefaults for first version userDefaults.setFloat(val, forKey: "version") } if NSUserDefaults().floatForKey("version") == val { // Same Version so dont run the function } else { // Call function // Update version number to NSUserDefaults for other versions userDefaults.setFloat(val, forKey: "version") } A: If you want to run some code when the app is either first installed or after every update then you could read the current version of your application from your bundle CGFloat currentVersion = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue]; and write that to user defaults after you have run the code. [[NSUserDefaults standardUserDefaults] setFloat:currentVersion forKey:kLastVersionThatExecutedMyCodeKey]; The next time you start your app, you compare the value from the user defaults against the bundle version. If the bundle version has changed the app was updated which means that you should run the code again and write the new version to user defaults.
[ "stackoverflow", "0001733514.txt" ]
Q: How to access sharepoint data using C#? I am working on project where I have to access SharePoint data in C#. I've never done this before; and have the following questions? How would I access SharePoint data from C#? What API do I use? Are there any tutorials out there that will help me get started? A: There two ways in which you can access Sharepoint data: By Using Microsoft.Sharepoint.dll In this case you need to do coding on same machine (windows server). Second way is to use Sharepoint Web Services. This will allow developer to do developement work on different machine. A: The SDK is a good place to start. The real crux of question lies in whether you are writing code which will live in a SharePoint environment, or writing code which will consume SharePoint data in an external application. In the case of the former, SharePoint has its own API which you gain access to by simply referencing the appropriate DLL. For the latter, SharePoint comes with a set of web services which allow external applications to consume its data. Either these or a set of custom services (running in the SharePoint environment) will be your entry point into SharePoint. A: This is how you would do it in PowerShell which is very similar in how you would do it in in C#: # Lets reference the assembly / GAC that we need for this function getUsers { param ([string] $verify_sitepath="https://extranet.something.com") $verify_site=new-object Microsoft.SharePoint.SPSite($verify_sitepath) $verify_web=$verify_site.Rootweb $verify_web.site.url $verify_groups = $verify_web.groups | ? {$_.Name -match "^.*$CurrentGroup" } foreach($verify_group in $verify_groups) { foreach($verify_user in $verify_group.users) { $verify_user = $verify_user -replace "WRKGRP\\","" Write-Output "$verify_user" | Out-File -filepath "$splist$currentGroup.txt" -append } } } What this does is gets all the users from SharePoint that are in a text file. Hopefully this gets you at least thinking about how SharePoint is set up. A great resource is the MSDN page with all the functions. They provide a lot of programming samples in C#!
[ "craftcms.stackexchange", "0000007112.txt" ]
Q: customised slugs using custom field I have a 'Profile' channel that gives the profile of people. I have 'Last name' as the title, 'first name' and I'd like to use first name in the slug rather than have to add the first name to the title and then need to create another field to store the last name. I thought, similar to {entry.type} I could've gone for {entry.firstName} but that doesn't work. Possible? A: Firstly I'd recommend splitting the first name and last name into seperate fields. That way in your templates it would look nicer: {{ member.firstNameField }} {{ member.lastNameField }} than having: {{ member.firstNameField }} {{ member.title }} when outputting their names. Once you have done that, in your entry type settings you can set the entry title to run off these first name and last name fields: {firstNameField} {lastNameField} The slug will be automatically generated from this as well. I may have mis-understood your question, but I hope that helps.
[ "stackoverflow", "0002743069.txt" ]
Q: Does anyone know about a WPF conponent that acts like the gmail to field? Where the To-field is a textbox that also contains a dropdown, where each new contact is added to the text field? Similar to the facebook to field, where a box is created for each receiver. Is there such a library or component out there? Thanks A: just look at the Latest WPF Toolkit they have introduced AutoCompleteTextBox. http://wpf.codeplex.com/releases/view/40535
[ "stackoverflow", "0004655102.txt" ]
Q: jQuery selector - input field I'd like to enable the textbox when it is clicked. However, when I click the textbox, nothing happens. I believe it is a problem with the jQuery selector. Why isn't this working? <script> $(document).ready(function() { $(':input').click(function() { $(this).removeAttr('disabled'); }); }); </script> <input type="text" value="123" disabled="disabled" /> Note: I tried both $('input') and $(':input') to select the textfield. Neither worked. A: A disabled input isn't going to fire events. Try changing from disabled to readonly.
[ "stackoverflow", "0005403664.txt" ]
Q: How to match parenthesis using a regular expression? I am using using boost libraries to parse a file. Its known that when you use a parenthesis it denotes a sub-expression in a regular expression. How would I declare a regular expression if my file contains parenthesis? I tried using \( with no luck. Could anyone tell me how I should declare a regular expression for the following format of file? a:(1) b:(2) I'm able to do the parsing when the file content is a:1 b:2 by declaring the regular expression as boost::regex e("([a-z]):([0-9])"); Can you tell me how I can also match if the values are in braces? A: If you want to use parentheses you need to escape them with a backslash. The issue is that you need to escape that backslash too (for the C++ compiler). Example: std::string regexstring = "\\([a-z]\\):\\([0-9]\\)";
[ "japanese.stackexchange", "0000030428.txt" ]
Q: The usage of だと and それなりに in this sentence I ran into this sentence and I'm a bit confused. 魔法の事についてだけはあいつもそれなりに真摯なのだと I guess I'm more confused about the "da to" part. Is this supposed to mean "suppose to"? And so the sentence would be "When it comes to magic alone she's supposed to be earnest/sincere"? Or is there any other usage for it that I'm missing? I'm also a bit unsure if それなりに has any important significance in this, like "she's supposed to be sincere in her own way"? I've read some examples of this expression being used and it never seemed to change anything meaningful so I'm a bit stumped. I don't think the follow up sentence is important to the context but I'll leave it here anyway. なぜそんな買いかぶりなどをしていたのか。 A: と On the contrary, your following section is super important, so that I can know the と isn't at the end of the sentence but qualifies the next verb. The whole clause before と is supposed to go to a verb phrase 買いかぶっていた "had been overrated", which is separated into two parts 買いかぶり + していた during the insertion of など, making the original form obscured. After all, the entire first clause is explaining how the speaker overrated her. と as quotative case particle can qualify any verb that means mental activity to detail what's actually said, felt and thought. それなりに in her own way No. "In her own way" is 彼女なりに. Here it is それなりに. Since それ "it" is too vague to tell actual things, それなり is more like an idiom as a whole: "so-so", "somewhat", "decent(ly)" etc.
[ "stackoverflow", "0041178576.txt" ]
Q: What's the use of dilated convolutions? I refer to Multi-Scale Context Aggregation by Dilated Convolutions. A 2x2 kernel would have holes in it such that it becomes a 3x3 kernel. A 3x3 kernel would have holes in it such that it becomes a 5x5 kernel. Above assumes interval 1 of course. I can clearly see that this allows you to effectively use 4 parameters but have a receptive field of 3x3 and 9 parameters but have a receptive field of 5x5. Is the case of dilated convolution simply to save on parameters while reaping the benefit of a larger receptive field and thus save memory and computations? A: TLDR Dilated convolutions have generally improved performance (see the better semantic segmentation results in Multi-Scale Context Aggregation by Dilated Convolutions) The more important point is that the architecture is based on the fact that dilated convolutions support exponential expansion of the receptive field without loss of resolution or coverage. Allows one to have larger receptive field with same computation and memory costs while also preserving resolution. Pooling and Strided Convolutions are similar concepts but both reduce the resolution. @Rahul referenced WaveNet, which put it very succinctly in 2.1 Dilated Causal Convolutions. It is also worth looking at Multi-Scale Context Aggregation by Dilated Convolutions I break it down further here: Figure (a) is a 1-dilated 3x3 convolution filter. In other words, it's a standard 3x3 convolution filter. Figure (b) is a 2-dilated 3x3 convolution filter. The red dots are where the weights are and everywhere else is 0. In other words, it's a 5x5 convolution filter with 9 non-zero weights and everywhere else 0, as mentioned in the question. The receptive field in this case is 7x7 because each unit in the previous output has a receptive field of 3x3. The highlighted portions in blue show the receptive field and NOT the convolution filter (you could see it as a convolution filter if you wanted to but it's not helpful). Figure (c) is a 4-dilated 3x3 convolution filter. It's a 9x9 convolution filter with 9 non-zeros weights and everywhere else 0. From (b), we have it that each unit now has a 7x7 receptive field, and hence you can see a 7x7 blue portion around each red dot. To draw an explicit contrast, consider this: If we use 3 successive layers of 3x3 convolution filters with stride of 1, the effective receptive field will only be 7x7 at the end of it. However, with the same computation and memory costs, we can achieve 15x15 with dilated convolutions. Both operations preserve resolution. If we use 3 successive layers of 3x3 convolution filters with increasing stride at an exponential rate at exactly the same rate as dilated convolutions in the paper, we will get a 15x15 receptive field at the end of it but with loss of coverage eventually as the stride gets larger. What this loss of coverage means is that the effective receptive field at some point will not be what we see above. Some parts will not be overlapping. A: In addition to the benefits you already mentioned such as larger receptive field, efficient computation and lesser memory consumption, the dilated causal convolutions also has the following benefits: it preserves the resolution/dimensions of data at the output layer. This is because the layers are dilated instead of pooling, hence the name dilated causal convolutions. it maintains the ordering of data. For example, in 1D dilated causal convolutions when the prediction of output depends on previous inputs then the structure of convolution helps in maintaining the ordering of data. I'd refer you to read this amazing paper WaveNet which applies dilated causal convolutions to raw audio waveform for generating speech, music and even recognize speech from raw audio waveform. I hope you find this answer helpful.
[ "tex.stackexchange", "0000155871.txt" ]
Q: Listing within tcolorbox: how to adjust width to the natural listing width? I would like to create a tcolorbox whose width is computed based on the longest line I have in listed code. I know it is possible to adjust the width with respect to the title. Is it also possible to adjust it based on the content? \PassOptionsToPackage {usenames,dvipsnames}{xcolor} \documentclass{standalone} \usepackage{tcolorbox} \tcbuselibrary{listings} \usepackage{tikz} \begin{document} \begin{tcblisting}{ arc=7pt, outer arc=7pt, top=1mm, bottom=1mm, left=1mm, right=1mm, boxrule=0.6pt, colback=yellow!5, colframe=yellow!50!black, fonttitle=\bfseries, listing only, } int main(int ac, char *av[], char **ep) { printf("Hello, World\n"); return 0; } \end{tcblisting} \end{document} A: You can simply add the option hbox: \PassOptionsToPackage {usenames,dvipsnames}{xcolor} \documentclass{standalone} \usepackage{tcolorbox} \tcbuselibrary{listings} \usepackage{tikz} \begin{document} \begin{tcblisting}{ arc=7pt, outer arc=7pt, top=1mm, bottom=1mm, left=1mm, right=1mm, boxrule=0.6pt, colback=yellow!5, colframe=yellow!50!black, fonttitle=\bfseries, listing only, hbox } int main(int ac, char *av[], char **ep) { printf("Hello, World\n"); return 0; } \end{tcblisting} \end{document} Note that, if you want to have the following result you have to remove the leading spaces in the lines int main(int ac, char *av[], char **ep) { printf("Hello, World\n"); return 0; } being the contents of the listing verbatim contents.
[ "stackoverflow", "0030233336.txt" ]
Q: Getting TypeError: type() argument 1 must be string, not None I am getting error while installing customized Odoo module. Here is the full Traceback I am getting. it is when I am clicking install button on module kanban view. Traceback (most recent call last): File "/home/software/ws/bma8_dev/odoo/openerp/http.py", line 518, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/home/software/ws/bma8_dev/odoo/openerp/http.py", line 539, in dispatch result = self._call_function(**self.params) File "/home/software/ws/bma8_dev/odoo/openerp/http.py", line 295, in _call_function return checked_call(self.db, *args, **kwargs) File "/home/software/ws/bma8_dev/odoo/openerp/service/model.py", line 113, in wrapper return f(dbname, *args, **kwargs) File "/home/software/ws/bma8_dev/odoo/openerp/http.py", line 292, in checked_call return self.endpoint(*a, **kw) File "/home/software/ws/bma8_dev/odoo/openerp/http.py", line 759, in __call__ return self.method(*args, **kw) File "/home/software/ws/bma8_dev/odoo/openerp/http.py", line 388, in response_wrap response = f(*args, **kw) File "/home/software/ws/bma8_dev/odoo/openerp/addons/web/controllers/main.py", line 953, in call_button action = self._call_kw(model, method, args, {}) File "/home/software/ws/bma8_dev/odoo/openerp/addons/web/controllers/main.py", line 941, in _call_kw return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs) File "/home/software/ws/bma8_dev/odoo/openerp/api.py", line 237, in wrapper return old_api(self, *args, **kwargs) File "/home/software/ws/bma8_dev/odoo/openerp/addons/base/module/module.py", line 450, in button_immediate_install return self._button_immediate_function(cr, uid, ids, self.button_install, context=context) File "/home/software/ws/bma8_dev/odoo/openerp/api.py", line 237, in wrapper return old_api(self, *args, **kwargs) File "/home/software/ws/bma8_dev/odoo/openerp/addons/base/module/module.py", line 498, in _button_immediate_function registry = openerp.modules.registry.RegistryManager.new(cr.dbname, update_module=True) File "/home/software/ws/bma8_dev/odoo/openerp/modules/registry.py", line 346, in new openerp.modules.load_modules(registry._db, force_demo, status, update_module) File "/home/software/ws/bma8_dev/odoo/openerp/modules/loading.py", line 363, in load_modules loaded_modules, update_module) File "/home/software/ws/bma8_dev/odoo/openerp/modules/loading.py", line 263, in load_marked_modules loaded, processed = load_module_graph(cr, graph, progressdict, report=report, skip_modules=loaded_modules, perform_checks=perform_checks) File "/home/software/ws/bma8_dev/odoo/openerp/modules/loading.py", line 158, in load_module_graph models = registry.load(cr, package) File "/home/software/ws/bma8_dev/odoo/openerp/modules/registry.py", line 148, in load model = cls._build_model(self, cr) File "/home/software/ws/bma8_dev/odoo/openerp/models.py", line 659, in _build_model cls = type(cls._name, (cls,), attrs) TypeError: type() argument 1 must be string, not None can any one know what is wrong ? A: You missed required module descriptor on model. try to _name or _inherit on your model class. It will resolve this kind of error.
[ "pt.stackoverflow", "0000270183.txt" ]
Q: Programar uma função em Python para executar sempre na ultima sexta-feira do mês O código abaixo demonstra um exemplo de como programar, mas é um pouco limitado a minutos, horas e dias. Eu preciso de um que inclua também o mês e o dia específico, que no meu caso é a sexta-feira. Consegui um código que obtém a data da ultima sexta-feira do mês corrente, mas não soube como integrar usando o schedule. import time import schedule import calendar from datetime import date from dateutil.relativedelta import relativedelta, FR def last_friday_of_month(month=None, year=None): month = month or date.today().month year = year or date.today().year return date(year, month, 1) + relativedelta( day=calendar.monthrange(year, month)[1], weekday=FR(-1) ) def job(string): print(string) schedule.every().thursday.at("11:49").do(job, "I'm working...") while 1: schedule.run_pending() time.sleep(1) A: Então - a biblioteca schedule não suporta isso. Por isso, a forma mais simples vai ser você simplesmente agendar a tarefa para todas as sextas-feiras, e colocarum código de filtro na entrada da função: se a data atual não for a última sexta-feira do mês, então retorne sem executar. Claro que a primeira vista isso parece implicar em colar código de cálculo de datas e etc dentro da sua tarfea, que pode não ter nada a ver com isso, e ainda repetir esse código em várias tarefas em que você queira fazer algo parecido. Aí é que entram os "decoradores" - decoradores são modificadores de função que tem uma sintaxe específica no Python: basicamente eles podem "ensanduichar" o código da sua função original e rodar, opcionalmente, algum código antes ou depois - o código do decorador fica separado da sua função principal, e você usa apenas uma linha para modificar o comportamento da sua função. Eu explico bem o seu uso nessa resposta: Como funcionam decoradores em Python? Então, você pode criar um decorador assim: import datetime from functool import wraps def only_on_last_friday(func): @wraps(func) def wrapper(*args, **kwargs): today = datetime.date.today() if today == last_friday_of_month(year=today.year, month=today.month): return func(*args, **kwargs) return None return wrapper Pronto - em combinação com sua função de encontrar a última sexta do mês, ela só vai executar a chamada a função final se for chamada na última sexta. Você tanto pode aplicar o decorador à sua função final, como simplesmente decorar no momento de chamar o scheduler - dessa forma a função continua normal para o restante do seu código, e só o scheduler recebe a função modificada para rodar só na data escolhida: @only_on_last_friday def job(string): print(string) schedule.every().friday.at("11:49").do(job, "I'm working...") ou: def job(string): print(string) schedule.every().friday.at("11:49").do(only_on_last_friday(job), "I'm working...") (Não sei se você está usando o dateutils para outras coisas, mas se não estiver, tenho uma versão do last_friday usando só o datetime padrão:) from datetime import date, timedelta def last_friday(year, month): minus_one_day = timedelta(days = 1) next_month = date(year, month, 27) + timedelta(days=7) result = date(next_month.year, next_month.month, 1) while True: result -= minus_one_day if result.weekday() == 4: # Friday return result Aproveitando o ensejo, se você está usando esse código é importante para você ter algo no lugar que assegure que o programa esteja rodando, mesmo após vários dias ligado. Há um projeto em Python muito legal para isso chamado supervisor - que pode garantir isso com bem pouco trabalho - vale a pena olhar: http://supervisord.org/
[ "math.stackexchange", "0000208345.txt" ]
Q: Evaluate $\int_{0}^{\infty} \frac{{(1+x)}^{-n}}{\log^2 x+\pi^2} \ dx, \space n\ge1$ Evaluate the integral $$\int_{0}^{\infty} \frac{{(1+x)}^{-n}}{\log^2 x+\pi^2} \ dx, \space n\ge1$$ A: This is the case $n=1$: $$ \begin{align} \int\limits_{0}^{+\infty}\frac{(1+x)^{-1}}{\log^2 x+\pi^2}dx =\{x=e^{\pi t}\} &=\frac{1}{\pi}\int\limits_{-\infty}^{+\infty}\frac{e^{\pi t}}{(1+e^{\pi t})(1+t^2)}dt\\ &=\frac{1}{\pi}\left(\int\limits_{-\infty}^{0}\frac{e^{\pi t}}{(1+e^{\pi t})(1+t^2)}dt+\int\limits_{0}^{+\infty}\frac{e^{\pi t}}{(1+e^{\pi t})(1+t^2)}dt\right)\\ &=\frac{1}{\pi}\left(\int\limits_{0}^{+\infty}\frac{e^{-\pi t}}{(1+e^{-\pi t})(1+t^2)}dt+\int\limits_{0}^{+\infty}\frac{e^{\pi t}}{(1+e^{\pi t})(1+t^2)}dt\right)\\ &=\frac{1}{\pi}\left(\int\limits_{0}^{+\infty}\frac{1}{(1+e^{\pi t})(1+t^2)}dt+\int\limits_{0}^{+\infty}\frac{e^{\pi t}}{(1+e^{\pi t})(1+t^2)}dt\right)\\ &=\frac{1}{\pi}\int\limits_{0}^\infty\left(\frac{1}{1+e^{\pi t}}+\frac{e^{\pi t}}{1+e^{\pi t}}\right)\frac{1}{t^2+1}dt\\ &=\frac{1}{\pi}\int\limits_{0}^\infty\frac{1}{t^2+1}dt=\frac{1}{2} \end{align} $$ A: This is the same integral as $\frac 1 {2 \pi i} \int_{\mathcal{C}} \frac {d x}{(1+x)^n \ln(-x)}$, where the contour $\mathcal{C}$ starts from infinity, below the positive axis and returns to infinity above the positive axis, after going around zero. Therefore the answer is given by the residue in $x=-1$ which is the coefficient of $y^{n-1}$ in the series expansion of $\frac 1{\ln(1-y)}$. Not sure if there's a closed form for that, but I guess there should be. EDIT: Here's the reasoning in more detail. First, if $x>0$ then $\ln (-x \pm 0 i) = \ln x \pm \pi i$. Therefore, $$ \frac 1 {\ln(x)^2 + \pi^2} = \frac 1 {2 \pi i} \left(\frac 1 {\ln(x)-\pi i} - \frac 1 {\ln(x) + \pi i}\right), $$ where in the RHS we have the difference between the value of the function $\frac 1 {\ln(-x)}$ above and below the real axis. Now consider the contour $\mathcal{C}$ shown above in red. When integrating along the part under the positive real axis and above the real axis we end up with the discontinuity across the branch cut. The part at infinity vanishes if $n \geq 1$. Therefore, $$ \frac 1 {2 \pi i} \int_{\mathcal{C}} \frac {d x}{(1+x)^n \ln(-x)} = \frac 1 {2 \pi i} \int_0^\infty \frac {d x}{(1+x)^n} \left(\frac 1 {\ln(-(x+0 i))}-\frac 1 {\ln(-(x-0 i))}\right)= \int_0^\infty \frac {d x}{(1+x)^n (\ln(x)^2 + \pi^2)}. $$ Now we should compute the contour integral. We only have on pole at $x=-1$ so we need to compute its residue: $$ \operatorname{Res}\left(\frac 1{(1+x)^n \ln(-x)},x=-1\right) = \operatorname{Res}\left(\frac 1{y^n \ln(1-y)},y=0\right), $$ which is the same as the coefficient of $y^{n-1}$ in the expansion of $\frac 1 {\ln(1-y)}$, which is often denoted as $[y^{n-1}] \frac 1 {\ln(1-y)}$. The expansion of $\frac 1 {\ln(1-y)}$ around $y=0$ is easy to find by computer. I find $$ \frac 1 {\ln(1-y)} = -\frac{1}{y}+\frac{1}{2}+\frac{y}{12}+\frac{y^2}{24}+\frac{19 y^3}{720}+\frac{3 y^4}{160}+\frac{863 y^5}{60480}+\frac{275 y^6}{24192}+\frac{33953 y^7}{3628800}+\frac{8183 y^8}{1036800}+O\left(y^9\right), $$ but I can't find a closed form for the $n-1$-th coefficient. EDIT2: We want to find the coefficient of $y^k$ in the expansion of $\frac 1 {\ln(1-y)}$. Using Lagrange inversion formula we have that $$ k [y^k] \left(\frac 1 {\ln(1-y)}\right) = -[y] (1-e^y)^{-k} = (-1)^{k+1} [y^{k+1}]\left(\frac y {e^y-1}\right)^k. $$ Now, using the generating function for Stirling polynomials, $$ \left(\frac y {e^y-1}\right)^k = \sum_{p=0}^\infty (-1)^p \frac {S_p(k-1)}{p!} t^p, $$ where $S_p(x)$ are the Stirling polynomials, we have that $$ [y^k] \left(\frac 1 {\ln(1-y)}\right) = \frac {S_{k+1}(k-1)} {k (k+1)!}. $$ When evaluated at integer coefficients $m>n$, the Stirling polynomial $S_n(m)$ can be expressed in terms of Stirling numbers of first kind, but here we are not in that situation... Edit3: Thanks to a comment below I found out the rational numbers which appear as the result of the integral are called Gregory coefficients (see here for more details and properties). A: Borrowing from the Norberts answers the integral can be written as: $$ \frac{1}{\pi}\int\limits_{-\infty}^{+\infty}\frac{e^{\pi t}}{(1+e^{\pi t})^n(1+t^2)}dt = \frac{1}{\pi}\left(\int\limits_{-\infty}^{+\infty}\frac{1}{(1+e^{\pi t})^{n-1}(1+t^2)}dt - \int\limits_{-\infty}^{+\infty}\frac{1}{(1+e^{\pi t})^n(1+t^2)}dt \right)$$ Now it's enough to calculate: $$ g(n)=\frac{1}{\pi}\int\limits_{-\infty}^{+\infty}\frac{1}{(1+e^{\pi t})^n(1+t^2)}dt $$ We can use integration by residues to write this as: $$ f(t) = \frac{(1+e^{\pi t})^{-n}}{(1+t^2)}\\ g(n) = \frac{1}{\pi}\int\limits_{-\infty}^{+\infty}f(t)dt = 2i\sum_{k=0}^\infty\mathrm{Res}(f,i(2k+1)) $$ Then the original integral is: $g(n-1)-g(n)$. I didn't manage to write this in closed form, but Mathematica is able to solve this for some values of $n$. The values of the original integral for $n = 1,\ldots,9$: $$ \frac{1}{2},\frac{1}{12},\frac{1}{24},\frac{19}{720},\frac{3}{160},\frac{863}{60480},\frac{275}{24192},\frac{33953}{3628800},\frac{8183}{\ 1036800} $$ Edit: OEIS sequence A002208 gives formula for $g(n)$. $$g(n) = -[x^n]\frac{x}{(1-x)\ln(1-x)} = \frac{(-1)^n}{(n-1)!}\sum_{k=1}^n(-1)^{k+1}B_k\frac{s(n,k)}{k}$$ Where $B_n$ is Bernoulli number and $s(n,k)$ is Stirling number of the first kind. The original integral is: $$g(n-1)-g(n) = \frac{(-1)^{n}}{(n-1)!}\left(\frac{B_n}{n}+\sum_{k=1}^{n-1}(-1)^kB_k\frac{s(n-1,k-1)}{k}\right)$$
[ "stackoverflow", "0039306597.txt" ]
Q: View is showing but printing width shows 0 I'm creating my view programmatically with this code : let statusfilterui = UIView(frame: CGRectMake(0, 300, 0, 0)) var height : CGFloat = 0 var width : CGFloat = 0 self.cancelledByAdmin.frame = CGRectMake(0,0,0,0) if width == 0{ width = self.cancelledByAdmin.frame.width height = self.cancelledByAdmin.frame.height } let cancelledByAdminlabel = UILabel(frame: CGRectMake(0, 0, 0, 0)) cancelledByAdminlabel.text = "لغو شده توسط پذیرش" cancelledByAdminlabel.sizeToFit() self.cancelledByAdmin.frame = CGRectMake(cancelledByAdminlabel.frame.width+10, 0, 0, 0) let cancelledLabel = UILabel(frame: CGRectMake(0, height+10, 0, 0)) cancelledLabel.text = "لغو شده توسط کاربر" cancelledLabel.sizeToFit() self.cancelled.frame = CGRectMake(cancelledLabel.frame.width+10, height + 10, 0, 0) let reservedLabel = UILabel(frame: CGRectMake(0, 2*(height + 10), 0, 0)) reservedLabel.text = "لغو شده توسط پذیرش" reservedLabel.sizeToFit() self.reserved.frame = CGRectMake(reservedLabel.frame.width+10, 2*(height + 10), 0, 0) let deprecatedLabel = UILabel(frame: CGRectMake(0, 3*(height + 10), 0, 0)) deprecatedLabel.text = "منقضی شده" deprecatedLabel.sizeToFit() self.deprecated.frame = CGRectMake(deprecatedLabel.frame.width+10, 3*(height + 10), 0, 0) statusfilterui.addSubview(self.cancelledByAdmin) statusfilterui.addSubview(cancelledByAdminlabel) statusfilterui.addSubview(self.cancelled) statusfilterui.addSubview(cancelledLabel) statusfilterui.addSubview(self.reserved) statusfilterui.addSubview(reservedLabel) statusfilterui.addSubview(self.deprecated) statusfilterui.addSubview(deprecatedLabel) print(statusfilterui.frame.width) statusfilterui.sizeToFit() print(statusfilterui.frame.width) self.filterview.addSubview(statusfilterui) print(statusfilterui.frame.width) And I want center my statusfilterui by getting width of view but the problem is I'm printing statusfilterui.frame.width 3 times and every time its printing 0.0 in console. what is wrong? A: Add statusfilterui to parent first. Then call statusfilterui.sizeToFit(). It should then work. parentView.addSubview(statusfilterui) statusfilterui.sizeToFit() Apple doc on sizeToFit()
[ "rpg.stackexchange", "0000091381.txt" ]
Q: How to optimize epic progression for an arcane/divine spellcaster? My player has decided to play an arcane/divine spellcaster. He has just completed progression of an arcane hierophant and is advancing next 7 levels in mystic theurge class. The campaign will end up with the player characters over 30th level. As a beginner gamer, he often asks for advice, however this case looks troublesome. I guess, he could advance up to 10th level of a mystyic theurge, which would be kind of a poor choice, as he only increases the arcane and divine spellcaster levels. Epic mystic theurge looks awful with it's alternately arcane/divine progression, even though it provides one bonus epic feat. Is there a way to increase both Arcane along with Divine spellcaster levels and gain other benefits like extra uses of turning undead or bonus metamagical feats? The player is currently Neutral Good Human Cleric 3/Wizard 3/Arcane Hierophant 10/Mystic Theurge 2. Materials from Dragon Magazine and published third parties are acceptable. A: Unless this character happens to have the Death domain, arcane hierophant and mystic theurge are the only classes that advance an arcane class and a divine class simultaneously. Even if he or she does have the Death domain, the class that requires it, the true necromancer, is awful, though it does dual-advance arcane and divine spellcasting (10 levels advance both, 2 levels advance arcane only, 2 levels advance divine only; yes, it is a 14-level class). However, we can trick our way into a bit more dual-advancement: ultimate magus advances two classes, a spellcaster who prepares arcane spells from a spellbook, and a spellcaster who casts arcane spells spontaneously. The wizard prepares and casts arcane spells from a spellbook; that’s no problem. The cleric prepares divine spells, obviously, right? Weeeellllll.... they have a class feature literally called “spontaneous casting,” not even the sorcerer does that. And the Alternate Source Spell feat from Dragon vol. 325 lets you use your divine spellcasting for arcane spells and vice versa, so with that feat, the cleric class is casting some arcane spells. And that can include the cure spells they spontaneously cast. So the cleric in this case can spontaneously cast arcane spells. That... is what ultimate magus asks for. So that gets us in. The wording of the actual spellcasting class feature of the ultimate magus is a little trickier: it specifies that it advances “a spontaneous arcane casting class to which you belonged before adding the prestige class level.” Does cleric now count as a “spontaneous arcane casting class” due to spontaneous casting and Alternate Source Spell? That question has already come up before: Alternate Source Spell making cleric count as arcane, spontaneous casting making cleric wizard count as spontaneous. In both cases, I go through the problems, specifically that we have zero definition of either of these two terms. In both cases, I recommend against allowing it—but both cases were asking about trying to have a dual-advancement prestige class double-advance a single class. That definitely shouldn’t be allowed. But allowing ultimate magus to advance cleric and wizard? That seems fine to me. So my recommendation is to allow the player to use ultimate magus here. I would probably not even make them take Alternate Source Spell, though it could be a useful feat for them to have in any case (particularly if they also have Practiced Spellcaster for both cleric and wizard, which they absolutely should).