id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_4000
I am saying that the Query should return an Int but it actually returns a String. If I execute it, it does complain. But is there a way to have the error at "compilation" time? Without me having to execute the query in the playground in order to see if there is a type error? import { Int, Query, Resolver } from "type-graphql"; @Resolver() export class MyResolver { @Query(() => Int) hello() { return "hello" } } A: I don't think it is possible right now for decorators to annotate the type of a function. You can explicitly type the function's return: import { Int, Query, Resolver } from "type-graphql"; @Resolver() export class MyResolver { @Query(() => Int) hello(): number { return "hello" // error } } Sadly there is duplication here, but it's the best you can get. If you want you could also make a type that gets the correct type from the GraphQL type: GetType<Int>; // number GetType<[Int]>; // number[] // etc EDIT: Took some time to make the type myself
doc_4001
My create_product and create_category endpoint works as expected without the file: UploadFile = File(...) passed to the router function I could successfully upload files with other routes and get their filename but not with the above mentioned routes Routes: @router.post('/category/create', response_model=schemas.CategoryOut) def create_category(*, request: schemas.CategoryIn, file: UploadFile = File(...), db: Session = Depends(get_db), current_user: schemas.UserOut = Depends(get_current_active_user)): category = storeview.get_category_by_slug(db, request.slug) if category: raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=f"Category with slug {request.slug} already exists!") request.image = storeview.save_file(file) return storeview.create_category(db, request) @router.post('/product/create', response_model=schemas.Product) async def create_product(*, file: UploadFile = File(...), request: schemas.ProductIn, category_id: int, db: Session = Depends(get_db), current_user: schemas.UserOut = Depends(get_current_active_user)): product = storeview.get_category_by_slug(db, request.slug) if product: raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=f"Product with slug {request.slug} already exists!") request.image = storeview.save_file(file) return storeview.create_product(db, request, category_id) Views: def create_category(db: Session, request: schemas.CategoryIn): new_category = models.Category( name=request.name, slug=request.slug, image=request.image) db.add(new_category) db.commit() db.refresh(new_category) return new_category def create_product(db: Session, request: schemas.ProductIn, category_id: int): new_product = models.Product(**request.dict(), category_id=category_id) db.add(new_product) db.commit() db.refresh(new_product) return new_product def save_file(file: UploadFile = File(...)): result = cloudinary.uploader.upload(file.file) url = result.get("url") return url Schemas: class CategoryBase(BaseModel): name: str slug: str image: str class Category(CategoryBase): id: int class Config: orm_mode = True class CategoryIn(CategoryBase): pass class ProductBase(BaseModel): name: str description: Optional[str] = None price: float image: str slug: str class Product(ProductBase): id: int category_id: int category: Category class Config: orm_mode = True class ProductIn(ProductBase): pass class CategoryOut(CategoryBase): products: List[Product] = [] id: int class Config: orm_mode = True
doc_4002
Is there a way to use an existing chromedriver window instead of just opening and closing on a loop until a conditional is satisfied? If that is not possible is there an alternative way to go about this you would reccomend? Thanks! Script: from selenium.webdriver.common.keys import Keys from selenium import webdriver import pyautogui import time import os def snkrs(): driver = webdriver.Chrome('/Users/me/Desktop/Random/chromedriver') driver.get('https://www.nike.com/launch/?s=in-stock') time.sleep(3) pyautogui.click(184,451) pyautogui.click(184,451) current = driver.current_url driver.get(current) time.sleep(3.5) elem = driver.find_element_by_xpath("//* . [@id='j_s17368440']/div[2]/aside/div[1]/h1") ihtml = elem.get_attribute('innerHTML') if ihtml == 'MOON RACER': os.system("clear") print("SNKR has not dropped") time.sleep(1) else: print("SNKR has dropped") pyautogui.click(1303,380) pyautogui.hotkey('command', 't') pyautogui.typewrite('python3 messages.py') # Notifies me by text pyautogui.press('return') pyautogui.click(928,248) pyautogui.hotkey('ctrl', 'z') # Kills the bash loop snkrs() Bash loop file: #!/bin/bash while [ 1 ] do python snkrs.py done A: You are defining a method that contains the chromedriver launch and then running through the method once (not looping) so each method call generates a new browser instance. Instead of doing that, do something more like this... url = 'https://www.nike.com/launch/?s=in-stock' driver.get(url) # toggle grid view WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[aria-label='Show Products as List']"))).click(); # wait for shoes to drop while not driver.find_elements((By.XPATH, "//div[@class='figcaption-content']//h3[contains(.,'MOON RACER')]")) print("SNKR has not dropped") time.sleep(300) // 300s = 5 mins, don't spam their site driver.get(url) print("SNKR has dropped") I simplified your code, changed the locator, and added a loop. The script launches a browser (once), loads the site, clicks the grid view toggle button, and then looks for the desired shoe to be displayed in this list. If the shoes don't exist, it just sleeps for 5 mins, reloads the page, and tries again. There's no need to refresh the page every 1s. You're going to draw attention to yourself and the shoes aren't going to be refreshed on the site that often anyway. A: If you're just trying to wait until something changes on the page then this should do the trick: snkr_has_not_dropped = True while snkr_has_not_dropped: elem = driver.find_element_by_xpath("//* .[ @ id = 'j_s17368440'] / div[2] / aside / div[1] / h1") ihtml = elem.get_attribute('innerHTML') if ihtml == 'MOON RACER': print("SNKR has not dropped") driver.refresh() else: print("SNKR has dropped") snkr_has_not_dropped = False Just need to refresh the page and try again.
doc_4003
@Override public boolean onTouchEvent(MotionEvent event) { int x = (int)event.getRawX(); int y = (int)event.getRawY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //do something case MotionEvent.ACTION_MOVE: //do something case MotionEvent.ACTION_UP: //do something } return true; } But we get the pointer position when only mouse click action happen, can not get the mouse pointer position when it is moving on the screen by moving real mouse. So my question is, how to get the mouse pointer location in this condition(NOT click mouse, just moving)? A: You want your activity to implement GestureDetector.OnGestureListener implement onGenericMotionEvent or have your view override it: @Override public boolean onGenericMotionEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_HOVER_MOVE) { // Do something // Maybe also check for ACTION_HOVER_ENTER and ACTION_HOVER_EXIT events // in which case you'll want to use a switch. } return true; }
doc_4004
<input type="" /> Any work-arounds, mods, tweaks? A: See the documentation here I guess you can use <input type="text" pattern="[0-9]*"></input> or <input type="tel"></input> Hope it helps A: You can add the input type="number" and then pattern="[0-9]*" to bring up a number pad.
doc_4005
A: If i understand your question "executable" is a file with execute permission. The execute permission grants the ability to execute the file. You can set the execute permission with chmod, for example: nano script.sh // your script chmod +x script.sh ./script.sh In the first line I create the file using nano (i choose nano because I read you have used that). In the second line because I want run the script just created I must to allow it being executable. I can do it using the chmod program (you can learn more about chmod typing man chmod). So I set the execute permission using chmod with the +x option. Now I could check if script.sh has the execute permission with the command ls -l script.sh. -rwxr-xr-x 1 Mpac staff 8456 31 Feb 12:00 script.sh Finally, in the last line I run the script. A: As it relates to this question, it essentially just means it can be executed without specifying anything else about the program outside of the script. For bash you're going to want to specify the bash location in the shebang (#!/path/to/bash) in the first line of the file, and this is in turn used to execute it when the script is called. e.g. $ printf "#%c$(which bash)\necho \"hello world\"\n" > test.sh $ chmod u+x test.sh $ cat test.sh #!/bin/bash echo "hello world" $ ./test.sh hello world
doc_4006
In concrete, I need to receive a request, extract the request body and process the request body as if it were a brand new request (thus rewriting the entire request before it gets handled further). Thereafter, I need to rewrite the response that is generated and wrap it somehow. Can anyone help and provide some pointers? Thanks A: You can write interceptors in Spring MVC by implementing HandlerInterceptor interface. There are three methods that need to be implemented. preHandle(..) is called before the actual handler is executed; postHandle(..) is called after the handler is executed; afterCompletion(..) is called after the complete request has finished. These three methods should provide enough flexibility to do all kinds of preprocessing and postprocessing. Learn more about how to place a filter in SpringMVC: http://viralpatel.net/blogs/spring-mvc-interceptor-example/
doc_4007
from tkinter import * class Page6(Tk): def Page6(): window=Toplevel() window.geometry("1920x1080") window["bg"] = ("#FFB6C1") window.title("Dating Simulator") iag = PhotoImage(file="Images\ClassroomTextBoxThree.gif") labelfour = Label(window, image=iag) labelfour.place(x=-100,y=-50) labelfour.photo = iag textThree = Label(window, text ="Hello What is your Name?", font= "Times 15") textThree.place( x = 80, y = 60) #add name to code/username below #the code below is where I want to retrieve the input from class Page2 MyButton1 = Button(window, text="Hello my name is" + E1.get(), width=10, font="Times 20", command=Page7.Page7) MyButton1.place(x=1120, y=275) class Page2(Tk): def Page2(): window=Toplevel() window.geometry("1920x1080") window["bg"] = ("#FFB6C1") window.title("Dating Simulator") imag = PhotoImage(file="Images\Minami.gif") labelthree = Label(window, image=imag) labelthree.place(x=-100,y=-50) labelthree.photo = imag #labelthree.pack(side="right") #E1 is where the user should input their name E1 = Entry(window, bd = 5) E1.place(x=1100, y= 675) EntryOne = Label(window, text = "Please insert your name (First name only):", font = "Times 20", bg ="#ffffff") EntryOne.place(x=600,y=200) MyButton1 = Button(window, text="Submit", width=10, font="Times 20", command=Page3.Page3) MyButton1.place(x=1090, y=725) I tried looking up other solutions from other posts, but either only involved taking data from one class or just a variable, not a entry input. The working product should make the button (from class Page6) include the user's name input from class Page2 as a part of its text. Thank you very much for reading.
doc_4008
This works only if one client is connected. If I connect a second client then communication breaks between the server and the first client. Which server <-> client pattern works for one server and multiple clients? A: for servers, you want to use ROUTER, and for clients, DEALER. There are a lot of examples of this in the ZeroMQ Guide. It's worth reading through that (or buy the book) and learning the different patterns, as you try simple models of your own. Don't try to build anything too complex to start with.
doc_4009
and have a running example of java with the input is decision table defined in csv files. Of course, in the way of knowledgeBuilder, not line-by-line such as in exceljs module Now that I want to have the same program in JavaScript NodeJS. However, I don't know what is the equivalent for reading the defined CSV files Is there a way to do that in NodeJS? In Java, we have knowledgeBuilder class, what is equivalent of that in NodeJS??
doc_4010
Something like: "Select a From Table a WHERE a.field LIKE IN :list" So that i can set the Parameters like this: {"12%","13%","16%"} or do i have to chain dynamicly many OR-clauses? THX, Necros A: I think this is not possible the way you like, but you could use several OR'ed conditions like Select * from table1 where x like "12%1234" OR x like "23%". If that doesn't work because the list is too long or whatever, maybe look at the criteria api to programmatically OR the conditions you need?
doc_4011
My problem is that on some computers (1 out of 50), after Windows 10 updates, I get a different hash than before (result of GetIfTable changes). Physically, there is nothing changed on the computer - no new cards or devices are attached to the computer, but the result is different. Any ideas on what might be causing this problem? unit ethernet_address; interface uses classes, sysutils; const MAX_INTERFACE_NAME_LEN = $100; ERROR_SUCCESS = 0; MAXLEN_IFDESCR = $100; MAXLEN_PHYSADDR = 8; MIB_IF_OPER_STATUS_NON_OPERATIONAL = 0 ; MIB_IF_OPER_STATUS_UNREACHABLE = 1; MIB_IF_OPER_STATUS_DISCONNECTED = 2; MIB_IF_OPER_STATUS_CONNECTING = 3; MIB_IF_OPER_STATUS_CONNECTED = 4; MIB_IF_OPER_STATUS_OPERATIONAL = 5; MIB_IF_TYPE_OTHER = 1; MIB_IF_TYPE_ETHERNET = 6; MIB_IF_TYPE_TOKENRING = 9; MIB_IF_TYPE_FDDI = 15; MIB_IF_TYPE_PPP = 23; MIB_IF_TYPE_LOOPBACK = 24; MIB_IF_TYPE_SLIP = 28; MIB_IF_ADMIN_STATUS_UP = 1; MIB_IF_ADMIN_STATUS_DOWN = 2; MIB_IF_ADMIN_STATUS_TESTING = 3; type MIB_IFROW = Record wszName : Array[0 .. (MAX_INTERFACE_NAME_LEN*2-1)] of char; dwIndex : LongInt; dwType : LongInt; dwMtu : LongInt; dwSpeed : LongInt; dwPhysAddrLen : LongInt; bPhysAddr : Array[0 .. (MAXLEN_PHYSADDR-1)] of Byte; dwAdminStatus : LongInt; dwOperStatus : LongInt; dwLastChange : LongInt; dwInOctets : LongInt; dwInUcastPkts : LongInt; dwInNUcastPkts : LongInt; dwInDiscards : LongInt; dwInErrors : LongInt; dwInUnknownProtos : LongInt; dwOutOctets : LongInt; dwOutUcastPkts : LongInt; dwOutNUcastPkts : LongInt; dwOutDiscards : LongInt; dwOutErrors : LongInt; dwOutQLen : LongInt; dwDescrLen : LongInt; bDescr : Array[0 .. (MAXLEN_IFDESCR - 1)] of Char; end; function Get_EthernetAddresses: TStringList; Function GetIfTable( pIfTable : Pointer; VAR pdwSize : LongInt; bOrder : LongInt ): LongInt; stdcall; implementation Function GetIfTable; stdcall; external 'IPHLPAPI.DLL'; function Get_EthernetAddresses: TStringList; const _MAX_ROWS_ = 20; type _IfTable = Record nRows : LongInt; ifRow : Array[1.._MAX_ROWS_] of MIB_IFROW; end; VAR pIfTable : ^_IfTable; TableSize : LongInt; tmp : String; i,j : Integer; ErrCode : LongInt; begin pIfTable := nil; //------------------------------------------------------------ Result:=TStringList.Create; if Assigned(Result) then try //------------------------------------------------------- // First: just get the buffer size. // TableSize returns the size needed. TableSize:=0; // Set to zero so the GetIfTabel function // won't try to fill the buffer yet, // but only return the actual size it needs. GetIfTable(pIfTable, TableSize, 1); if (TableSize < SizeOf(MIB_IFROW)+Sizeof(LongInt)) then begin Exit; // less than 1 table entry?! end; // if-end. // Second: // allocate memory for the buffer and retrieve the // entire table. GetMem(pIfTable, TableSize); ErrCode := GetIfTable(pIfTable, TableSize, 1); if ErrCode<>ERROR_SUCCESS then begin Exit; // OK, that did not work. // Not enough memory i guess. end; // if-end. // Read the ETHERNET addresses. for i := 1 to pIfTable^.nRows do try if pIfTable^.ifRow[i].dwType=MIB_IF_TYPE_ETHERNET then begin tmp:=''; for j:=0 to pIfTable^.ifRow[i].dwPhysAddrLen-1 do begin tmp := tmp + format('%.2x', [ pIfTable^.ifRow[i].bPhysAddr[j] ] ); end; // for-end. //------------------------------------- if Length(tmp)>0 then Result.Add(tmp); end; // if-end. except Exit; end; // if-try-except-end. finally if Assigned(pIfTable) then FreeMem(pIfTable,TableSize); end; // if-try-finally-end. end; end. // ************************ // Note: this is where we display a part of the Ethernet string as a test. This is what changes after Windows updates, but only on certain computers! // ************************ // StringList := Get_EthernetAddresses; try if (StringList.Count > 0) and (Length(StringList.Strings[0]) >= 6) then begin EthernetPartStr := Copy(StringList.Strings[0], 5, 2); //Problem is here, Label10 will change after a Windows update Label10.Caption := EthernetPartStr[1] + EthernetPartStr[2] + ' - ' + StringList.Strings[0]; end; finally StringList.Free; end;
doc_4012
var old = File.ReadAllText("old.txt").Split(null).ToList(); var junk = File.ReadAllText("junk.txt").Split(null).ToList(); var result = old.Except(junk).ToList(); Console.WriteLine(old.Count); Console.WriteLine(junk.Count); Console.WriteLine(result.Count); I get 10791 // old 2431 // junk 5762 // ????????????????????? I would expect 10791 - 2431 to come back with 8360. What can explain the 5762 number? A: The number do not have to match: * *The junk file may contain words that are not in the old file and can therefore not be removed. *On the other hand the old file could have duplicates that will all be removed. So the result count can be everything between 0 (if everything is junk in the old file) and the original count of old (if there was no junk at all).
doc_4013
instantHelpBtn = UIButton() instantHelpBtn.frame = CGRectMake(10, 10, 30, 30) instantHelpBtn.setBackgroundImage(UIImage(named: "questions1.png"), forState: .Normal) instantHelpBtn.addTarget(self, action: "instantHelpBtnPressed", forControlEvents: .TouchUpInside) self.view.addSubview(instantHelpBtn) The problem is that function instantHelpBtnPressed is working only if I'm somehow pressing non-transparent parts of the background image. If I miss (and I miss often), nothing happens. How could I change this behavior? A: Problem is your button frame. You are creating 30X30 UIButton where as, per Apple iOS human interface guideline, minimum size should be 44X44. A: It seems to me, that 30*30 frame is just too small. Apple recommend to create ui tappable elements no smaller than 44x44 pixels. Here is a link on documentation: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/LayoutandAppearance.html A: How about instead of setting it to a transparent image do... instantHelpBtn.backgroundColor = UIColor.clearColor() And if you want to set it to the image when clicked do... func instantHelpBtnPressed(sender: UIButton) { sender.setBackgroundImage(UIImage(named: "questions1.png"), forState: .Normal) }
doc_4014
I am not getting any dropdown tool.
doc_4015
I can't set it globally, or other links (such as some social media icons) are changing. Here is what I've tried: div.entry-content a:link { color: blue; } entry-content a:link { color: blue; } Here is what I'm looking at when I inspect the page: So, where am I going wrong? I hope I added everything needed for assistance. Thanks. A: I'm assuming all three links are wrapped in in div with class entry-content. The only thing I can think of is that the first link is black or darker color because it's active or visited. You can style your links with just a selector or with additional pseudo selectors. /* Just a selector */ .entry-content a { color: blue; } /* Just a selector */ .entry-content a, .entry-content a:visited, .entry-content a:active { color: blue; } A: It seems you have clicked on the link earlier, so the link status is active or visited. Try this, if ok then update your code with pseudo selectors :active and :visited: a, a:link, a:visited, a:active { color: blue; } Hope this help! A: Try adding a class name to the anchors, like so: <a class="blue" href="url">link text</a> and then in your css create the blue class .blue { color: blue; }
doc_4016
this is my question class class Question(models.Model): question = models.CharField(max_length = 200) questionbody = models.TextField() questioncontent = models.TextField() author = models.ForeignKey(User) tags = models.ManyToManyField(Tag) timestamp = models.DateTimeField('question post date') upvote = models.IntegerField(default = 0) downvote = models.IntegerField(default = 0) view = models.IntegerField(default = 0) and this is my userprofile class(extends user) class UserProfile(models.Model): user = models.OneToOneField(User) tags = models.ManyToManyField(Tag) # favorite_question = models.ManyToManyField(Question) # upvote_question = models.ManyToManyField(Question) # downvote_question = models.ManyToManyField(Question) # upvote_answer = models.ManyToManyField(Answer) # downvote_answer = models.ManyToManyField(Answer) integration = models.IntegerField(default = 0) level = models.CharField(max_length = 100) if uncomment the line run the synvdb command it will show the error access for m2m field 'favorite-question' clashes with related m2m field 'question-userprofile_set',add a related_name argument to thr definition for 'favorite-question' and same error shows up for the rest 4 line. am really new to django ,please help A: About the error, you have to defined the related name if you want to use a relationship of same type across models: for example: favorite_question = models.ManyToManyField(Question, related_name='favourite_question')
doc_4017
I can remove all NA values from a vector v1 <- c(1,2,3,NA,5,6,NA,7,8,9,10,11,12) v2 <- na.omit(v1) v2 but how do I return a vector with values only after the last NA c( 7,8,9,10,11,12) Thank you for your help. A: You could detect the last NA with which and add 1 to get the index past the last NA and index until the length(v1): v1[(max(which(is.na(v1)))+1):length(v1)] [1] 7 8 9 10 11 12 A: You could detect the last NA with which v1[(tail(which(is.na(v1)), 1) + 1):length(v1)] # [1] 7 8 9 10 11 12 However, the most general - as @MrFlick pointed out - seems to be this: tail(v1, -tail(which(is.na(v1)), 1)) # [1] 7 8 9 10 11 12 which also handles the following case correctly: v1[13] <- NA tail(v1, -tail(which(is.na(v1)), 1)) # numeric(0) To get the null NA case, too, v1 <- 1:13 we can do if (any(is.na(v1))) tail(v1, -tail(which(is.na(v1)), 1)) else v1 # [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 Data v1 <- c(1, 2, 3, NA, 5, 6, NA, 7, 8, 9, 10, 11, 12) A: v1 <- c(1,2,3,NA,5,6,NA,7,8,9,10,11,12) v1[seq_along(v1) > max(0, tail(which(is.na(v1)), 1))] #[1] 7 8 9 10 11 12 v1 = 1:5 v1[seq_along(v1) > max(0, tail(which(is.na(v1)), 1))] #[1] 1 2 3 4 5 v1 = c(1:5, NA) v1[seq_along(v1) > max(0, tail(which(is.na(v1)), 1))] #integer(0) A: Here’s an alternative solution that does not use indices and only vectorised operations: after_last_na = as.logical(rev(cumprod(rev(! is.na(v1))))) v1[after_last_na] The idea is to use cumprod to fill the non-NA fields from the last to the end. It’s not a terribly useful solution in its own right (I urge you to use the more obvious, index range based solution from other answers) but it shows some interesting techniques. A: The following will do what you want. i <- which(is.na(v1)) if(i[length(i)] < length(v1)){ v1[(i[length(i)] + 1):length(v1)] }else{ NULL } #[1] 7 8 9 10 11 12
doc_4018
In my gradle I make minsdk as 19 when I put 19 it crashes and give below error. but when I change to 23 it's fine. E/AndroidRuntime: FATAL EXCEPTION: main Process: info.androidhive.fingerprint, PID: 15697 java.lang.NoClassDefFoundError: Failed resolution of: Landroid/hardware/fingerprint/FingerprintManager; at info.androidhive.fingerprint.FingerprintActivity.onCreate(FingerprintActivity.java:45) at android.app.Activity.performCreate(Activity.java:6010) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413) at android.app.ActivityThread.access$800(ActivityThread.java:155) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5343) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700) Caused by: java.lang.ClassNotFoundException: Didn't find class "android.hardware.fingerprint.FingerprintManager" on path: DexPathList[[zip file "/data/app/info.androidhive.fingerprint-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass(ClassLoader.java:511) at java.lang.ClassLoader.loadClass(ClassLoader.java:469) at info.androidhive.fingerprint.FingerprintActivity.onCreate(FingerprintActivity.java:45)  at android.app.Activity.performCreate(Activity.java:6010)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)  at android.app.ActivityThread.access$800(ActivityThread.java:155)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5343)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)  Suppressed: java.lang.ClassNotFoundException: android.hardware.fingerprint.FingerprintManager at java.lang.Class.classForName(Native Method) at java.lang.BootClassLoader.findClass(ClassLoader.java:781) at java.lang.BootClassLoader.loadClass(ClassLoader.java:841) at java.lang.ClassLoader.loadClass(ClassLoader.java:504) ... 15 more Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available A: We cannot use FingerpintManager with api less than 23. The minSdkVersion for this FingerpintManager is 23. If you want to use FingerpintManager in apps whose API level is less than 23, you may consider using FingerprintManagerCompat, which behaves as if no fingerprint sensors are available with API level less than 23. For more info check link and also example. https://developer.android.com/reference/android/support/v4/hardware/fingerprint/FingerprintManagerCompat.html https://github.com/AMykich/Android-Fingerprint-API
doc_4019
No operator "==" matches these operands. You can see in the following code that both types (snake and addsnakey[0]) are sf::RectangleShape. Why do I get a compiler error when I try to compare two sf::RectangleShape? Below is the offending code. I added a comment where the error is: sf::RectangleShape snake; //increases size of the snake sf::RectangleShape addsnake() { sf::RectangleShape addsnake1; addsnake1.setSize(sf::Vector2f(20, 25)); addsnake1.setFillColor(sf::Color::Red); addsnake1.setPosition(100, 100); sf::RectangleShape addsnake2; addsnake2.setSize(sf::Vector2f(20, 30)); addsnake2.setFillColor(sf::Color::Red); addsnake2.setPosition(100, 100); sf::RectangleShape addsnake3; addsnake3.setFillColor(sf::Color::Red); addsnake3.setSize(sf::Vector2f(20, 35)); addsnake3.setPosition(100, 100); sf::RectangleShape addsnake4; addsnake4.setSize(sf::Vector2f(20, 40)); addsnake4.setFillColor(sf::Color::Red); addsnake4.setPosition(100, 100); sf::RectangleShape addsnakey[4] = { addsnake1, addsnake2, addsnake3, addsnake4 }; if (snake == snake) //problem here (No operator "==" matches these operands) return addsnakey[0]; else if (snake == addsnakey[0]) return addsnakey[1]; else if (snake == addsnakey[1]) return addsnakey[2]; else if (snake == addsnakey[2]) return addsnakey[3]; else if (snake == addsnakey[3]) return addsnakey[4]; } A: There is no equality operator defined for the sf::RectangleShape class. You will need to create one, and decide on exactly what properties determine equality. Perhaps size and position are what you care about. So you could define the following function: bool operator==( const sf::RectangleShape & a, const sf::RectangleShape & b ) { return a.getSize() == b.getSize() && a.getPosition() == b.getPosition(); } This would be okay, because both the getSize and getPosition member functions return a Vector2f which does have an equality operator. You might care about about getScale too. Naturally, it's up to you to determine what constitutes equality. The lack of an equality operator on the sf::RectangleShape is not surprising, given that it does a lot, including texturing etc. It's obviously not the kind of thing you expect to be comparing with other objects. See Reference for sf::Vector2f
doc_4020
list.apply { return when (size) { //size in 0..4 0 -> false 1 -> get(0) == 9 2 -> get(0) == 9 || get(0) == get(1) || get(0) + get(1) == 8 3 -> get(0) == 9 || get(0) == get(1) || get(0) + get(1) == 8 || get(0) == get(2) || get(0) + get(2) == 8 else -> get(0) == 9 || get(0) == get(1) || get(0) + get(1) == 8 || get(0) == get(2) || get(0) + get(2) == 8 || get(0) == get(3) || get(0) + get(3) == 8 // when size == 4 } } As you can see, the below code have many repetitions. I found another solution, and this one almost doesn't repeat itself, but I have the impression that it is possible to shorten the code (maybe I'm wrong?). Here is the other version (still in the inline function apply) : var rtn = false if (size > 0) rtn = rtn || get(0) == 9 if (size > 1) rtn = rtn || get(0) == get(1) || get(0) + get(1) == 8 if (size > 2) rtn = rtn || get(0) == get(2) || get(0) + get(2) == 8 if (size > 3) rtn = rtn || get(0) == get(3) || get(0) + get(3) == 8 return rtn Is there any way to shorten or optimize the code a bit more? And among these 2 versions, which one is to be preferred and why? A: val result = with(list) { isNotEmpty() && (first() == 9 || (1..lastIndex).any { first() == get(it) || first() + get(it) == 8 }) }
doc_4021
Error 500 Unable to locate object to be marshalled in model: {} I do know the POST worked because I can manually go to the new URL (/todos/5) and see the newly created resource. Its only when trying to redirect that I get the failure. I know in my example I could just return the newly created Todo object, but I have other cases where a redirect makes sense. The error looks like a marshaling problem, but like I said, it only rears itself when I add redirects to my RESTful methods, and does not occur if manually hitting the URL I am redirecting to. A snippet of the code: @Controller @RequestMapping("/todos") public class TodoController { @RequestMapping(value="/{id}", method=GET) public Todo getTodo(@PathVariable long id) { return todoRepository.findById(id); } @RequestMapping(method=POST) public String newTodo(@RequestBody Todo todo) { todoRepository.save(todo); // generates and sets the ID on the todo object return "redirect:/todos/" + todo.getId(); } ... more methods ... public void setTodoRepository(TodoRepository todoRepository) { this.todoRepository = todoRepository; } private TodoRepository todoRepository; } Can you spot what I am missing? I am suspecting it may have something to do with returning a redirect string - perhaps instead of it triggering a redirect it is actually being passed to the XML marshaling view used by my view resolver (not shown - but typical of all the online examples), and JAXB (the configured OXM tool) doesn't know what to do with it. Just a guess... Thanks in advance. A: This happend because redirect: prefix is handled by InternalResourceViewResolver (actually, by UrlBasedViewResolver). So, if you don't have InternalResourceViewResolver or your request doesn't get into it during view resolution process, redirect is not handled. To solve it, you can either return a RedirectView from your controller method, or add a custom view resolver for handling redirects: public class RedirectViewResolver implements ViewResolver, Ordered { private int order = Integer.MIN_VALUE; public View resolveViewName(String viewName, Locale arg1) throws Exception { if (viewName.startsWith(UrlBasedViewResolver.REDIRECT_URL_PREFIX)) { String redirectUrl = viewName.substring(UrlBasedViewResolver.REDIRECT_URL_PREFIX.length()); return new RedirectView(redirectUrl, true); } return null; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } }
doc_4022
When I do apache2 -l I get this: Compiled in modules: core.c mod_log_config.c mod_logio.c prefork.c http_core.c mod_so.c When I do sudo a2enmod rewrite I get this: Module rewrite already enabled And rewrite.load is in /etc/apache2/mods-enabled. Can anyone tell what's wrong? A: This really belongs on ServerFault, but since it'll probably get migrated eventually I'll go ahead and say that there's a difference between modules that are compiled into Apache and modules that are dynamically loaded. Apache is able to load modules in two different ways. The "simpler" way is for the module to be statically compiled into the server. This means that the executable file apache2 literally includes the module's code. The advantage of this approach is that the module is always available and Apache doesn't have to do anything special to get access to its code, but on the other hand, if you want to add, remove, or update a statically compiled module, you have to recompile all of Apache. Plus, the more modules that are statically compiled, the bigger the executable file becomes. For these reasons, it's normal for that list to only include a few of the most essential modules, basically the minimum necessary for Apache to run. Those few modules are the ones that appear in the list you see when you run apache2 -l. All the other modules that Apache uses, including mod_rewrite, are dynamically loaded. That is, their code is stored as separate files, which Apache locates and reads in after it's started up. This negates the disadvantages of the static compilation approach: since the modules are stored in separate files, if you want to add/remove/change one, you only need to restart the server, not recompile it. You can tell Apache which modules to load by putting LoadModule directives in your Apache configuration file. This is basically what a2enmod does: it adds a LoadModule directive to the configuration file. (Actually it symlinks a stub configuration file into a directory that is sourced by the main configuration) If you want to see a complete list of loaded modules, including the dynamically loaded ones, you can run apache2 -M You'll have to make sure to run Apache in the same way as Ubuntu's init script, though. It's common for the system to read in a configuration file or something before it starts Apache up, and if you don't do the same, it might change the set of modules that gets loaded.
doc_4023
How to show all legends in Google Visualization: Pie Chart A: You can simply set the sliceVisibilityThreshold option to 0. This will force all the legends to show. var options = { sliceVisibilityThreshold: 0 }; var data = /* ... */; var chart = new google.visualization.PieChart(/* ... */); chart.draw(data, options); A: What I did was to add a small value (0.005) to each of the values. When setting the sliceVisibilityThreshold: 1/25000, (1/25000 = 0.004) the slice/legend will be shown but the value will still be 0% due to rounding.
doc_4024
This is the below table ItemCode LOC001 LOC002 LOC003 AAA 10 11 12 BBB 13 31 14 CCC 15 18 0 This is the Static Code: var table=(from x in Mst_LocationItems group x by x.ItemCode into gr select new { ItemCode=gr.Key, LOC001 = gr.Where(x=>x.LocationID == "LOC001").Sum(x=>x.Reorder), LOC002 = gr.Where(x=>x.LocationID == "LOC002").Sum(x=>x.Reorder), LOC003 = gr.Where(x=>x.LocationID == "LOC003").Sum(x=>x.Reorder) }).ToList(); table.Dump();
doc_4025
[0,1..] >>= \i -> [i * 2] In the definition of >>= for List, the lambda function \i -> [i * 2] is mapped over the list argument via fmap, resulting in a list of lists, [[0], [2]..]. So >>= needs to flatten the result using a join function in order to return the list: [0, 2..] According to this source: "...the definition of bind in terms of fmap and join works for every monad m: ma >>= k = join $ fmap k ma" So why is it necessary to place the burden of returning a monad on the function supplied to >>=? Why not simply define bind like so? ma >>= k = fmap k ma This way you don't have to deal with flattening the result. A: What you're proposing is to simply define the bind operator to be equal to fmap, but with arguments swapped: ma >>= k = fmap k ma -- is equivalent to: (>>=) = flip fmap In which case, why not just use the fmap itself, or its operator form <$>? (*2) <$> [0,1..] > [0,2,4,6,...] However, this does not cover all cases where bind may be used. The difference is that monads are more powerful than functors. Where functors only let you produce exactly one output for every input, monads let you do all kinds of crazy stuff. Consider, for example, the following: [0,1,2,3] >>= \i -> [i*2, i*3] > [0,0,2,3,4,6,6,9] Here, the function produces two values for each input. This cannot be expressed via just fmap. This requires joining the resulting values. Here's another, even less obvious example: [0,1,2,3,4,5] >>= \i -> if i `mod` 2 == 0 then [] else [i] > [1,3,5] Here, the function either produces a value or doesn't. The empty list is technically still a value in the List monad, yet it cannot be obtained by fmaping the input. A: A major feature of a monad is to be able to "flatten" (join). This is necessary to define a nice form of composition. Consider the composition of two functions with side effects, say in the IO monad: foo :: A -> IO B bar :: B -> IO C If >>= was only fmap (without the final join) pass, the composition \a -> foo a >>= bar would mean \a -> fmap bar (foo a) -- i.e. fmap bar . foo which does look as a nice composition, but unfortunately has type A -> IO (IO C) ! If we can't flatten the nested IO, every composition would add yet another layer, and we would end up with result types of the form IO (IO (IO ...)) showing the number of compositions. At best, this would be inconvenient. At worst, this would prevent recursion such as loop = readLn >>= \x -> print x >>= \_ -> loop since it leads to a type with an infinite nesting of IO.
doc_4026
A: GAE supports pretty much any "pure" Python modules which don't try to access files or sockets or other system level utilities. The poster from your link was mostly just trying to minimize the number of modules they included. They expressed a trial and error approach to figuring out which NLTK modules would be needed for their application. A slightly faster approach would be to download the whole NLTK package and move in all the ".py" files rather than just one at a time. There's no big downside to including modules you won't be using. However this process is something of a fact of life with GAE. Any modules that aren't directly included in the GAE libraries need to be installed manually, and they need to be checked for any deviations from the GAE sandbox restrictions. See this. A quick glance at the NLTK source code suggests that modules that depend on "mallet" in particular might be problematic, since this is compiled java code.
doc_4027
My code below is simple, in terms that it scans for devices and then prompts a delegate, but the delegate is not responding. Please help... Delegate import UIKit import CoreBluetooth protocol BLEDelegate { func bleDidConnectToPeripheral(sender: BLEDiscovery, peripheral: CBPeripheral) } let bleDiscoverySharedInstance = BLEDiscovery() //MARK: - UUIDS for StingRay Genessis M (SRG) let StingRayGenesisMUUID = CBUUID (string: "346D0000-12A9-11CF-1279-81F2B7A91332") //Core UUID //MARK: - UUIDS for StingRay Genessis HR (SRG) let StingRayGenesisHRUUID = CBUUID (string: "F9AB0000-3F75-4668-9BAC-F8264DAE7820") //Core UUID //MARK: - Device and Characteristic Registers var BLEDevices : [CBPeripheral] = [] //Device Array var BLECharDictionary = [String: CBCharacteristic]() //Characteristic Dictionary class BLEDiscovery: NSObject, CBCentralManagerDelegate { private var centralManager : CBCentralManager? var delegate: BLEDelegate? override init() { super.init() let centralStingRayBLEQueue = dispatch_queue_create("com.stingray", DISPATCH_QUEUE_SERIAL) centralManager = CBCentralManager(delegate: self, queue: centralStingRayBLEQueue) } // MARK: - CB centralManager func centralManagerDidUpdateState(central: CBCentralManager) { switch (central.state) { case CBCentralManagerState.PoweredOff: print("CBCentralManagerState.PoweredOff") case CBCentralManagerState.Unauthorized: // Indicate to user that the iOS device does not support BLE. print("CBCentralManagerState.Unauthorized") break case CBCentralManagerState.Unknown: // Wait for another event print("CBCentralManagerState.Unknown") break case CBCentralManagerState.PoweredOn: print("CBCentralManagerState.PoweredOn") self.startScanning() case CBCentralManagerState.Resetting: print("CBCentralManagerState.Resetting") case CBCentralManagerState.Unsupported: print("CBCentralManagerState.Unsupported") break } } // MARK: - Start scanning for StringRay devices with the appropriate UUID func startScanning() { if let central = centralManager { central.scanForPeripheralsWithServices([StingRayGenesisMUUID,StingRayGenesisHRUUID], options: nil) } } // MARK: - CB Central Manager - Did discover peripheral (follows : startScanning) func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) { delegate?.bleDidConnectToPeripheral(self, peripheral: peripheral) //Check if new discovery and append to BLEDevices where required if BLEDevices.contains(peripheral) { print("didDiscoverPeripheral - ALREADY DISCOVERED ==", peripheral.name) } else{ BLEDevices.append(peripheral) print("didDiscoverPeripheral - NEW DISCOVERY ==", peripheral.name) } } // MARK: - CB Central Manager - Connect and Disconnet BLE Devices func connectBLEDevice (peripheral: CBPeripheral){ //Connect self.centralManager!.connectPeripheral(peripheral, options: nil) } func disconnectBLEDevice (peripheral: CBPeripheral){ //Disconnect self.centralManager?.cancelPeripheralConnection(peripheral) } } Delegator import UIKit import CoreBluetooth class MainViewController: UIViewController,UITableViewDelegate,UITableViewDataSource, BLEDelegate { //MARK: - View Object Links @IBOutlet weak var deviceTableView: UITableView! @IBOutlet weak var infoBlockView: UIView! // MARK: - Interface Builder Inspectables @IBInspectable var BorderWidth : CGFloat = 0.75 @IBInspectable var BorderRadius : CGFloat = 5.0 @IBInspectable var BorderColor : UIColor = UIColor.whiteColor() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. formatDeviceTableView() formatInFoBlock() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func bleDidConnectToPeripheral(sender: BLEDiscovery, peripheral: CBPeripheral) { print ("Its alive == ", peripheral.name) } // MARK: - View Fomrating func formatInFoBlock(){ infoBlockView.layer.borderColor = BorderColor.CGColor infoBlockView.layer.cornerRadius = BorderRadius infoBlockView.layer.borderWidth = BorderWidth } // MARK: - TableView Functions func formatDeviceTableView() { deviceTableView.layer.borderColor = BorderColor.CGColor deviceTableView.layer.cornerRadius = BorderRadius deviceTableView.layer.borderWidth = BorderWidth } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //Define a cell and assign it to DeviceTableCellTableViewCell class and use the reuse identifier from IB - "deviceCell" let cell = deviceTableView.dequeueReusableCellWithIdentifier("deviceCell") as! DeviceTableCellTableViewCell cell.backgroundColor = UIColor.clearColor() cell.deviceNameLabel.text = String(indexPath.row) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("Row Selected ::", indexPath.row) } func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { print("Accesory Selected ::", indexPath.row) } } I expect the code just to print out "Its alive..." to show me that it is working... A: * *In the Delegate file in var delegate: BLEDelegate?; add "weak" to it: weak var delegate: BLEDelegate?; *Move let bleDiscoverySharedInstance = BLEDiscovery(); from the delegate to the delegator. *To finish add: bleDiscoverySharedInstance.delegate = self; into the viewDidLoad to let it know that is the delegate. If you want in the link below you have a really similar example to follow using delegates: https://bitbucket.org/vicrius/flickr-visualizer/src Hope all that helps.
doc_4028
But in derived table I'm converting the values into (DT_DECIMAL) as I need to insert it into database. My problem is value 12345.6754. I want to take only 2 digits after the decimal, i.e., I want 12345.67. For that I tried (DT_DECIMAL,2)MYCOLUMN and (DT_NUMERIC,10,2) MYCOLUMN too, but then also it is giving me 12345.6754 :( please help A: In a Derived Column Transformation I'd look at using an appropriate String Functions and Other Functions (SSIS Expression) to manipulate the value. In this case, it sounds like you want toRound
doc_4029
I tried to write a batch file but its not working, @echo off echo Setting JAVA_HOME set JAVA_HOME=C:/Program Files/Java/jdk-17 set PATH=C:/Program Files/Java/jdk-17/bin; set APP_HOME=APPDIR set JAVA_EXE=%JAVA_HOME%/bin/java.exe set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar "%JAVA_EXE%" %DEFAULT_JVM_OPTS% -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* When i execute the above batch file, it's failing and its not working as expected. How can i log the execution error?
doc_4030
if ( isset(var1) & isset(var2) ) { if ( (var1 != something1) || (var2 != something2) ) { // ... code ... } } Seems like this could be condensed to only one IF statement but am not certain if I'd use an AND or OR A: Boolean varsAreSets = isset(var1) & isset(var2); // or some other name that indicates what this is doing Boolean someMeaningfulName = (var1 != something1) || (var2 != something2); // would suggest a meaningful name but don't know what this is accomplishing if ( varsAreSets && someMeaningfulName ) { // ... code ... } This makes the code very readable and helps you and whoever reads the code understand what these checks are actually doing. A: if (isset(var1) && ((var1 != something1) || (var1 != something2))) // ... code ... } You would use an and because you can only get to the // ... code ... part if both if-statements are true. A: You can do: if(isset(var1) && isset(var2) && ( (var1 != something1) || (var1 != something2) ) ){ //..code } As a general example: if( cond1 && cond2 ) { if( cond3 || cond4) { // ...code.. } } The code will be executed only when both cond1 and cond2 are true and either of cond3 or cond3 is true. A: It's a question of in what order your computer interprets boolean logic: Take for example the following conditions: A: False B: True if you were to write if (A && B) what your computer actually does is think: Is A true? No. Well, A and B can't be true because A isn't true. Therefore this statement is false. [computer ignores the rest of the logic] Because of this, when you evaluate the statement isset(var1) && ( (var1 != something1) || (var1 != something2) ) it first checks isset(var1) and if that's false, then it skips the rest of the condition, just like your double-if statement. A: if ( isset(var1) && isset(var2) && ( (var1 != something1) || (var2 != something2) ) ) { // ... code ... } A: if (isset(var1) && isset(var2) && ((var1 != something1) || (var2 != something2))) { // ... code ... } A: Another option: if (isset(var1) && isset(var2) && !(var1 == something1 && var2 == something2)) { ... A: I think most of the examples above that have 1 IF may spit out an error if var1 or var2 is NOT set (isset($var1) && isset($var2)) ? ($var1!='something1' && $var2!='something2') ? $go=TRUE : $go=FALSE : $go = FALSE; if ($go){ echo 'hello'; }
doc_4031
import 'package:flutter/material.dart'; import 'dart:math' as math; class ProgressMonitorAnimation extends StatefulWidget { @override State<StatefulWidget> createState() => _ProgressMonitorAnimationState(); } class _ProgressMonitorAnimationState extends State<ProgressMonitorAnimation> with TickerProviderStateMixin { double _progress = 0.0; Animation<double> animation; @override void initState() { var controller = AnimationController(duration: Duration(milliseconds: 3000), vsync: this); animation = Tween(begin: 1.0, end: 0.0).animate(controller)..addListener(() { setState(() { _progress = animation.value; }); }); controller.forward(); super.initState(); } @override Widget build(BuildContext context) { return Transform( alignment: Alignment.center, transform: Matrix4.rotationX(math.pi), child: CustomPaint( foregroundPainter: ProgressPainter(_progress), ), ); } } class ProgressPainter extends CustomPainter { double _progress; ProgressPainter(this._progress); @override void paint(Canvas canvas, Size size) { final Paint circlePainter = Paint()..color = Colors.green; final Paint linePainter = Paint()..color = Colors.black..strokeWidth = 4..strokeCap = StrokeCap.round; canvas.drawCircle(Offset(0.0, 30.0 * 3), 10.0, circlePainter); canvas.drawCircle(Offset(15.0 * 2, 80.0 * 3), 10.0, circlePainter); canvas.drawLine(Offset(0.0 / (_progress * 10), 30.0 * 3), Offset((30.0 * 3) + (15.0) / (_progress * 15) * 2, (80.0 * 3) / (_progress * 15)), linePainter); } @override bool shouldRepaint(CustomPainter oldDelegate) => true; } A: You can do as follows using flutter Custom Painter. import 'dart:async'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; class AnimatedPathPainter extends CustomPainter { final Animation<double> _animation; AnimatedPathPainter(this._animation) : super(repaint: _animation); Path _createAnyPath(Size size) { return Path() // ..moveTo(size.height / 4, size.height / 4) // ..lineTo(size.height, size.width / 2) // ..lineTo(size.height / 2, size.width) ..quadraticBezierTo(size.height / 2, 100, size.width, size.height); } @override void paint(Canvas canvas, Size size) { final animationPercent = this._animation.value; print("Painting + ${animationPercent} - ${size}"); final path = createAnimatedPath(_createAnyPath(size), animationPercent); final Paint paint = Paint(); paint.color = Colors.black; paint.style = PaintingStyle.stroke; paint.strokeWidth = 4.0; canvas.drawPath(path, paint); } @override bool shouldRepaint(CustomPainter oldDelegate) => true; } Path createAnimatedPath( Path originalPath, double animationPercent, ) { // ComputeMetrics can only be iterated once! final totalLength = originalPath .computeMetrics() .fold(0.0, (double prev, PathMetric metric) => prev + metric.length); final currentLength = totalLength * animationPercent; return extractPathUntilLength(originalPath, currentLength); } Path extractPathUntilLength( Path originalPath, double length, ) { var currentLength = 0.0; final path = new Path(); var metricsIterator = originalPath.computeMetrics().iterator; while (metricsIterator.moveNext()) { var metric = metricsIterator.current; var nextLength = currentLength + metric.length; final isLastSegment = nextLength > length; if (isLastSegment) { final remainingLength = length - currentLength; final pathSegment = metric.extractPath(0.0, remainingLength); path.addPath(pathSegment, Offset.zero); break; } else { // There might be a more efficient way of extracting an entire path final pathSegment = metric.extractPath(0.0, metric.length); path.addPath(pathSegment, Offset.zero); } currentLength = nextLength; } return path; } class AnimatedPathDemo extends StatefulWidget { @override _AnimatedPathDemoState createState() => _AnimatedPathDemoState(); } class _AnimatedPathDemoState extends State<AnimatedPathDemo> with SingleTickerProviderStateMixin { AnimationController _controller; Completer<GoogleMapController> _controllerMap = Completer(); static final CameraPosition _initialPosition = CameraPosition( // target: LatLng(12.947437, 77.685345), target: LatLng(7.8731, 80.7718), zoom: 8, ); void _startAnimation() { _controller.stop(); _controller.reset(); _controller.repeat( period: Duration(seconds: 2), ); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar(title: const Text('Animated Paint')), body: Stack( children: <Widget>[ GoogleMap( // rotateGesturesEnabled: false, mapType: MapType.normal, compassEnabled: false, initialCameraPosition: _initialPosition, // polylines: _polylines, // markers: _markers, onMapCreated: (GoogleMapController controller) { // controller.setMapStyle(Utils.mapStyles); _controllerMap.complete(controller); }, ), SizedBox( height: 300, width: 300, child: new CustomPaint( painter: new AnimatedPathPainter(_controller), ), ), ], ), floatingActionButton: new FloatingActionButton( onPressed: _startAnimation, child: new Icon(Icons.play_arrow), ), ); } @override void initState() { super.initState(); _controller = new AnimationController( vsync: this, ); } @override void dispose() { _controller.dispose(); super.dispose(); } }
doc_4032
| | | | 1 | mani |5000 | 10 | 2 |nani |6000 | 20 | 3 |phani |7000 | 30 | A: you are describing an UPDATE UPDATE table SET name = 'new name', salary = 1000, deptno = 50 WHERE uid = 2 But I'm not quite sure why to reuse the uid.
doc_4033
It turns out that after configuring jenkins and creating the environment variable I get the error below everytime I execute "jenkins start" from outside C:\Program Files (x86)\Jenkins. Is there any configuration missing? ERROR System.IO.FileNotFoundException: Unable to locate jenkins.xml file within executable directory or any parents at winsw.ServiceDescriptor..ctor() at winsw.WrapperService.Run(String[] _args, ServiceDescriptor descriptor) at winsw.WrapperService.Main(String[] args) SYSTEM ENVIRONMENT VARIABLES JENKINS_HOME: * *C:\Program Files (x86)\jenkins Path: * *%JENKINS_HOME% A: You need to run your jenkins install jenkins.xml at the place where is your jenkins.xml 1 rename winsw.exe to jenkins.exe 2 cd c:/...where is your jenkins.exe 3 run jenkins.exe install jenkins.xml (both files must be in the same directory) A: In Windows 10, the path of the configuration file (config.xml) is: C:\ProgramData\Jenkins.jenkins The Folder ProgramData is hidden, so go to the address bar and type or use the CLI. A: Solution: Save your jenkins-agent file as xml format. not just jenkins-agent.xml we can use notepad++ to save the xml type. similarly remove .exe at end of jenkins-agent.exe Hope its useful.... cheers !!
doc_4034
First, a bit of history: I pulled from my upstream to bring in changes and merged them with the branch I was working in. At the time, I may have been using a console window with root access. I say this because I noticed a day later I couldn't save to a lot of the files in my local repo. I noticed the owner / group had been changed to root and permissions were 644. After going through and hunting down all of the screwed up files, I then pushed some changes I had made back to my remote working branch. A week later (now), and I've added several other commits to an open pull request from my remote branch. In the middle of them was the commit I made after fixing my local repo file permissions. I noticed it has some 1200 "empty" files (no changes). I'm a little concerned that merging this pull request upstream could cause big problems and I have no idea how to remove this one commit or if it's even possible... I tried creating a new branch and using cherry-pick to get all but the one commit, but I've removed files and couldn't merge the older commits that saw a "conflict" between the file that existed at the time and one that no longer exists in the local repo... Anyway, any thoughts? A: The solution I used was to reset my local branch to the commit just before the one that I didn't want. I then copied and pasted the commits after the failed commit into code, recommited, and pushed toa new branch. Long way around, yes. But it wasn't bad as I didn't have a lot of code to fix. A simpler method might have been to use cherry-pick to pull the later commits into my reset local branch, but I tried that at one point and had problems...
doc_4035
Benjamins-MacBook-Pro:everyvotematters benjamin$ git status # On branch master # Your branch is ahead of 'everyvotematters/master' by 4 commits. # nothing to commit (working directory clean) Benjamins-MacBook-Pro:everyvotematters benjamin$ git push everyvotematters master Counting objects: 24, done. Delta compression using up to 8 threads. Compressing objects: 100% (19/19), done. Writing objects: 100% (20/20), 4.49 KiB, done. Total 20 (delta 7), reused 0 (delta 0) -----> Heroku receiving push -----> Git submodules detected, installing Submodule 'sdk' (https://github.com/facebook/facebook-php-sdk.git) registered for path 'sdk' Initialized empty Git repository in /tmp/build_awiw4oll8o2g/sdk/.git/ Submodule path 'sdk': checked out '98f2be163c96a51166354e467b95dd38aa4b0a19' ! Heroku push rejected, no Cedar-supported app detected To git@heroku.com:everyvotematters.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'git@heroku.com:everyvotematters.git' Benjamins-MacBook-Pro:everyvotematters benjamin$ A: Hmmm, the "no Cedar-supported app detected" is curious. I suspect you've modified your app in such a way that there's no longer an index.php in the root folder? That's how Heroku detects it's a PHP app. A: I had a local version of the SDK folder. This was fine, then one day it just up and quit working on me. First copy your SDK folder somehwere safe then run: git rm sdk git commit -am "removing sdk folder" git push heroku master Then I copy the folder back in, reran the commit and push commands This fixed it for me.
doc_4036
But Less compiler I was using in grunt wont recognize classes .m-b-0 generated by loop when I nested them in other class, but classes like .m-b-1 and .m-b-10 will be recognized correctly. The loop code in my Less files is like this: .m-loop (@i) when (@i <= @iterations) { .m-@{i}{ margin: ~"@{i}px"; } .m-h-@{i}{ margin-left: ~"@{i}px"; margin-right: ~"@{i}px"; } .m-v-@{i}{ margin-top: ~"@{i}px"; margin-bottom: ~"@{i}px"; } .m-l-@{i}{ margin-left: ~"@{i}px"; } .m-r-@{i}{ margin-right: ~"@{i}px"; } .m-t-@{i}{ margin-top: ~"@{i}px"; } .m-b-@{i}{ margin-bottom: ~"@{i}px"; } .m-loop(@i + 1); } .m-loop(0); and I use the classes supposed to be generated in the same less file like this: .panel{ .m-b-0; } Then my compiler throwed Running "less:production" (less) task >> NameError: .m-b-0 is undefined in ../css/less/stylesheet.less on line 237, column 3: >> 236 div.panel{ >> 237 .m-b-0; >> 238 } Warning: Error compiling ../css/less/stylesheet.less Used --force, continuing. Is this forbidden to use zero valued iterator in Less compiling or where did I take it wrong? Thanks! A: Looks like there might be a syntax error. I don't see an opening brace on this line: .m-t-@{i} See if that helps.
doc_4037
ERROR: Failed to download Chromium r579032! Set "PUPPETEER_SKIP_CHROMIUM_DOWNLOAD" env variableto skip download. { Error: read ETIMEDOUT at _errnoException (util.js:1022:11) at TLSWrap.onread (net.js:628:25) code: 'ETIMEDOUT', errno: 'ETIMEDOUT', syscall: 'read' } npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! puppeteer@1.7.0 install: `node install.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the puppeteer@1.7.0 install script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/anne/.npm/_logs/2018-08-28T11_59_47_508Z-debug.log I tried npm install puppeteer --unsafe-perm=true it didn't work. please let me know if you know how to solve it. A: Set npm mirror npm config set puppeteer_download_host=https://npm.taobao.org/mirrors npm i puppeteer https://github.com/GoogleChrome/puppeteer/issues/1597#issuecomment-351945645 A: This sounds like a corporate proxy issue. Confirm that there is no firewall blocks on your network. Then ask your IT colleagues about the appropriate proxy settings if it is allowed. A: My current work-around is to manually download Chromium with the specific version above. Then I add its install path to my environment path variable. Then use the below so puppeteer finds it. Either with PUPPETEER_SKIP_CHROMIUM_DOWNLOAD environment variable set, or npm install --ignore-scripts puppeteer   this.loading = puppeteer.launch({ args: [ '--no-sandbox', '--full-memory-crash-report' ] }).then(aBrowser => { this.browser = aBrowser; this.loading = undefined; return this.browser; }).catch(() => { return puppeteer.launch({ executablePath: "chromium.exe", args: [ '--no-sandbox', '--full-memory-crash-report' ] }).then(aBrowser => { this.browser = aBrowser; this.loading = undefined; return this.browser; }); }) I am avoiding any download location I do not trust A: Try the below instead: sudo npm install -g puppeteer --unsafe-perm=true --allow-root A: my colleague gave a way use a npm mirror in China solved the problem. ssh cnpm install prerender-spa-plugin@2.1.0 --save
doc_4038
Please find below the link demonstrating the functionality I would like to achieve in Big query : [https://www.ibm.com/support/knowledgecenter/en/SSULQD_7.2.1/com.ibm.nz.dbu.doc/r_dbuser_create_sequence.html][1] I have reviewed RANK() but this is not solving my purpose to the core. Any leads would be appreciated. A: in BigQuery Standard SQL you can find two function that can help you here - GENERATE_ARRAY(start_expression, end_expression\[, step_expression\]) and GENERATE_DATE_ARRAY(start_date, end_date\[, INTERVAL INT64_expr date_part\]) For example, below code #standardSQL SELECT sequence FROM UNNEST(GENERATE_ARRAY(1, 10, 1)) AS sequence produces result as sequence 1 2 3 4 5 6 7 8 9 10
doc_4039
Function GenerateBlendedReturnSeries(AccountID1 As String, Account1Proportion As Double, _ Optional ByVal AccountID2 As String, Optional ByVal Account2Proportion As Double, _ Optional ByVal AccountID3 As String, Optional ByVal Account3Proportion As Double) As Variant 'Vs. As Double() ' CODE IN BETWEEN Dim BlendedReturnSeriesArray As Variant ReDim BlendedReturnSeriesArray(ArraySize, 1) Debug.Print (ArraySize) On Error Resume Next For i = 0 To UBound(BlendedReturnSeriesArray) BlendedReturnSeriesArray(i, 1) = _ Account1PeriodReturnSeriesArray(i, 1) * Account1Proportion _ + Account2PeriodReturnSeriesArray(i, 1) * Account2Proportion _ + Account3PeriodReturnSeriesArray(i, 1) * Account3Proportion 'Debug.Print (BlendedReturnSeriesArray(i, 1)) 'Debug.Print (i) Next i On Error GoTo 0 Debug.Print (BlendedReturnSeriesArray(300, 1)) GenerateBlendedReturnSeries = BlendedReturnSeriesArray 'BlendedReturnSeriesArray End Function A: Unless you do this ReDim BlendedReturnSeriesArray(1 To ArraySize, 1 To 1) or you're using Option Base 1 (never a good idea), your return array will be sized as (0 to ArraySize, 0 to 1), so likely you're only seeing the first "column" of the array (the zero index) on your worksheet. If you expand the formula to cover two columns you'll see the numbers you're missing.
doc_4040
But when I accessed some html.erb, all code stopped working. Everything that used to execute and display something now displays only: <% code here %> If I downgrade to '4.2.6', everything works. Am I missing something? Thanks in advance.
doc_4041
driver = webdriver.Chrome('/snap/bin/chromium.chromedriver', options=option) I can access the URL using Firefox or Chromium without my script (just normal). Or Firefox in a script. But using Chromium in a script, it clicks the login button and just hangs, that eventually leads to a timeout selenium.common.exceptions.TimeoutException: Message: If I open a new tab and try to login without the script but manually, it still hangs. A login is impossible (on my target site) within a launched browser from selenium, only. #!/usr/bin/python3 from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from seleniumbase import BaseCase import time import random user_name = 'user' password = 'password' list = [ ] minptime = 4 maxptime = 24 list_length = len(list) print('Array length ', list_length) class MyMeClass(BaseCase): def method_a(): option = webdriver.ChromeOptions() option.add_argument('--disable-notifications') option.add_argument("--mute-audio") driver = webdriver.Chrome('/snap/bin/chromium.chromedriver', options=option) driver.get("https://me.com/") print(driver.title) element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.login-btn.btn-shadow#login-fake-btn[data-testid='login-fake-btn']"))).click() driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/form/input[1]').send_keys(user_name) driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/form/input[2]').send_keys(password) time.sleep(5) driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div/form/button').click() #button click in question time.sleep(8) driver.get(url) print(driver.current_url) return driver driver = MyMeClass.method_a() button I am accessing How do I use/unblock the use of this login button in chromium in a script? A: Try below code: with contains wait = WebDriverWait(driver, 30) wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Log in')]"))).click() Class Name wait = WebDriverWait(driver, 30) wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn-login btn-shadow']"))).click() Note : please add below imports to your solution from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait Working Solution: driver.get(" your url ") wait = WebDriverWait(driver,30) element = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@id='login-fake-btn']"))) print element.text element.click() wait = WebDriverWait(driver,30) element = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@id='email']"))).send_keys("Test") wait = WebDriverWait(driver,30) element = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@id='password']"))).send_keys("Test") element1 = wait.until(EC.presence_of_element_located((By.XPATH, "//div[@id='login-overlay']//div//form//button"))) element1.click() output :
doc_4042
Below I have mentioned the versions of my application Ionic: ionic (Ionic CLI) : 4.4.0 (C:\Users\Jahir\node_modules\ionic) Ionic Framework : ionic-angular 3.9.2 @ionic/app-scripts : 3.2.0 Cordova: cordova (Cordova CLI) : 8.1.2 (cordova-lib@8.1.1) Cordova Platforms : not available Cordova Plugins : not available System: Android SDK Tools : 26.1.1 (C:\Users\Jahir\AppData\Local\Android\Sdk) NodeJS : v11.2.0 (C:\Program Files\nodejs\node.exe) npm : 6.4.1 OS : Windows 7 I also posted my error elaborately from the CLI, please find it below events.js:167 throw er; // Unhandled 'error' event ^ Error: spawn cmd ENOENT at Process.ChildProcess._handle.onexit (internal/child_process.js:246:19) at onErrorNT (internal/child_process.js:421:16) at process.internalTickCallback (internal/process/next_tick.js:72:19) Emitted 'error' event at: at Process.ChildProcess._handle.onexit (internal/child_process.js:252:12) at onErrorNT (internal/child_process.js:421:16) at process.internalTickCallback (internal/process/next_tick.js:72:19) Please give me the solution, I know it is a simple error, a solution will be much helpful. A: just add it to the PATH: C:\Windows\System32 and start cmd as Administrator Goto > Control Panel\System and Security\System\Advance system setting\Enviroment variable and set system variables path C:\Windows\System32\ variable and restart your System. Positively Hope, it will work
doc_4043
I've tried this but get a not callable error, where the ID posted is the ID of the users message. await channel.send(message.content(608999881578774540)) I've also tried using message.id with the same issue. I would like the bot to take the users message, just the contents of it and have it posted just like the message by the user. The message never gets deleted, it just gets edited so I wouldn't have to worry about getting the message ID as it stays the same. A: Content in this case is not a method, therefore you should just take its value so that line would become this: await channel.send(message.content)
doc_4044
* *customers can order from the front end *admin can add a product from the 'last ordered' or 'recently viewed products' from the customer recent activity panel It therefore seems to be an issue with just this button alone. We've tried the below fixes without any success: * *removed theme from our site (revert to default); button still missing *noted a previous bug relating to payment methods in v 1.7; tried copying all payment .phtml files to theme; button still missing At a loss as to what this could be. All other functions appear to be working. Has anyone got any pointers as to how to resolve this? A: This isn't exactly an ideal fix, because it involves changing core functionality, but the "Add Product" backend button is handled in: app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Items.php What you're looking for specifically is the getButtonsHtml function. Having the same issue after upgrading from 1.6 to 1.9, I changed mine to look like this: public function getButtonsHtml() { $html = ''; // Make buttons to be rendered in opposite order of addition. This makes "Add products" the last one. $this->_buttons = array_reverse($this->_buttons); //If the buttons array isn't empty, let it do its thing if (!empty($this->_buttons)) { foreach ($this->_buttons as $buttonData) { $html .= $this->getLayout()->createBlock('adminhtml/widget_button')->setData($buttonData)->toHtml(); } } else { $addButtonData = array( 'label' => Mage::helper('sales')->__('Add Products'), 'onclick' => "order.productGridShow(this)", 'class' => 'add', ); $html .= $this->getLayout()->createBlock('adminhtml/widget_button')->setData($addButtonData)->toHtml(); } return $html; } It works, but it's really just a hackjob fix. I'm hoping someone more knowledgeable than I can come up with a proper solution. Edit - Leaving the above answer, but I sussed out my personal problem. I was running a dual install of Magento, and I forgot to change the .htaccess of my Minify library to re-route to the newer install. So it was compiling the old 1.6 JavaScript and using it on my 1.9 install.
doc_4045
docker run -d --name postgres postgres:9.4 I want to do something like this: docker run -d --name postgres --volumes-from postgres_datastore postgres:9.4 But GitLab CI Runner doesn't support any options (-v or --volumes-from). Is there any other way? A: The Docker volumes-from option is not yet available in Gitlab CI Runner (see this PR), however you can configure host mounts and volumes: [runners.docker] volumes = ["/host/path:/target/path:rw", "/some/path"] The above example would mount /host/path at /target/path/ inside the container and also create a new volume container at /some/path. See the Gitlab CI Runner manual for all docker related options. Edit: For service containers it seems you can only define volumes via the dockerfile of the service image. Maybe enough depending on your requirements.
doc_4046
{ "field1": "value1", "field2": "value2", ... "field100": "value100", } ...and appropriate POJO @Builder @Data public class BigJsonDto{ private String field1; private String field2; private String field100; } Let's say all fields are required and nullable except field1 that can't have a null value. So I want to tell Jackson (or another way) stop serialization if one or more required fields have null value, rather than just ignore it (with @JsonInclude). How can I reach it? It would be nice if it's possible to use built-in ObjectMapper. I tried to use @JsonProperty(required = true) annotation but as I can see this annotation is used in deserialization. So in this case, I got required fields with null values. A: I think you can add the @NonNull annotation to the field you require to not be null. Then you can try to handle the exception whenever you build the BigJsonDto object. For example the code below will throw the following exception Exception in thread "main" java.lang.NullPointerException: field1 is marked non-null but is null at BigJsonDto.<init>(StackOverflowQuestion.java:21) at BigJsonDto$BigJsonDtoBuilder.build(StackOverflowQuestion.java:21) at StackOverflowQuestion.main(StackOverflowQuestion.java:16) import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Builder; import lombok.Data; import lombok.NonNull; public class StackOverflowQuestion { public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); var output = mapper.writeValueAsString( BigJsonDto.builder() // uncomment this line to not throw exception //.field1("a") .field2("b") .field100("c").build()); System.out.println(output); } } @Builder @Data class BigJsonDto { @NonNull private String field1; private String field2; private String field100; } A: If you need to prevent an invalid POJO from being serialized you can create a custom serializer by extending JsonSerializer. For that, you would need to override serialize() method. public class BigJsonDtoSerializer extends JsonSerializer<BigJsonDto> { public static final Predicate<BigJsonDto> IS_NOT_VALID = dto -> Stream.of(dto.getField1(), // add as many fields as you need dto.getFieldN()) .anyMatch(Objects::isNull); @Override public void serialize(BigJsonDto value, JsonGenerator gen, SerializerProvider serializers) throws IOException { // Serialization fails if (IS_NOT_VALID.test(value)) throw new JsonGenerationException("BigJsonDto instance is not valid", gen); // Serialization succeeds (we need to provide the value of every field to JsonGenerator) gen.writeString(value.getField1()); gen.writeString(value.getField2()); gen.writeString(value.getField3()); // Et cetera gen.writeString(value.getFieldN()); } @Override public Class<BigJsonDto> handledType() { // needed ONLY if registered as part of module return BigJsonDto.class; } } Then you can register the serializer through the using attribute of the annotation @JsonSerialize applied on the top of your class. @Data @Builder @JsonSerialize(using = BigJsonDtoSerializer.class) public static class BigJsonDto { private String field1; private String field2; private String field3; private String fieldN; } Or you can register the serializer (or multiple serializers) globally by including it into a custom module (as described in the Jackson's documentation). This way also require handledType() to be overridden in each these serializers. If you're using Spring Boot, to register the module you can place in the Spring's Context as a Bean, or do it manually (if you're not using Spring in your project) via ObjectMapper.registerModule(). Annotation @JsonSerialize would not be needed in this case. ObjectMapper mapper = new ObjectMapper(); SimpleModule mySerializationModule = new SimpleModule( "MySerializationModule", new Version(1, 0, 0, "module-description", "groupId", "artifactId" ), Map.of(), // deserializers List.of(new BigJsonDtoSerializer()) // serializers ); mapper.registerModule(mySerializationModule); Usage example: String sourceJson = """ { "field1" : null, "field2" : "Bob", "field3" : "Carol", "fieldN" : "N" } """; ObjectMapper mapper = new ObjectMapper(); // for simplisity let's assume you chosen annotate the class with @JsonSerialize instead of registing the module BigJsonDto dto = mapper.readValue(sourceJson, BigJsonDto.class); String resultingJson = mapper.writeValueAsString(dto); // <- this line would fale because field1 is null
doc_4047
using namespace Eigen; I am not sure where the problem is. Thank you, everyone! A: The directive using namespace Eigen; does not import the Eigen project into your code, but rather allows you to type MatrixXd instead of Eigen::MatrixXd. When you type #include <Eigen/Dense> you actually insert the file Dense into your code at that point, effectively importing the Eigen project into your directory. The file Dense is just a regular text file. On your computer it's located at /usr/local/Cellar/eigen/3.3.4/include/eigen3/Eigen/Dense. Open it in a text editor to see what it looks like.
doc_4048
#एक 1के अंकगणित8IU अधोरेखाunderscore $thatऔर %redएकyellow $चिह्न अंडरस्कोर@_ The desired text file should be like, # 1 8IU underscore $that %redyellow $ @_ This is what I have tried so far, using awk awk -F"[अ-ह]*" '{print $1}' filename.txt And the output that I am getting is, # 1 $that %red $ and using this awk -F"[अ-ह]*" '{print $1,$2}' filename.txt and I am getting an output like this, # 1 े ं ो $that %red yellow $ ि ं Is there anyway to solve this in bash script? A: Using perl: $ perl -CSD -lpe 's/\p{Devanagari}+//g' input.txt # 1 8IU underscore $that %redyellow $ @_ -CSD tells perl that standard streams and any opened files are encoded in UTF-8. -p loops over input files printing each line to standard output after executing the script given by -e. If you want to modify the file in place, add the -i option. The regular expression matches any codepoints assigned to the Devanagari script in the Unicode standard and removes them. Use \P{Devanagari} to do the opposite and remove the non-Devanagari characters. A: Using awk you can do: awk '{sub(/[^\x00-\x7F]+/, "")} 1' file # 1 8IU underscore $that %redyellow * *See documentation: https://www.gnu.org/software/gawk/manual/html_node/Bracket-Expressions.html using [\x00-\x7F]. This matches all values numerically between zero and 127, which is the defined range of the ASCII character set. Use a complemented character list [^\x00-\x7F] to match any single-byte characters that are not in the ASCII range. A: tr is a very good fit for this task: LC_ALL=C tr -c -d '[:cntrl:][:graph:]' < input.txt It sets the POSIX C locale environment so that only US English character set is valid. Then instructs tr to -d delete -c complement [:cntrl:][:graph:], control and drawn characters classes (those not control or visible) characters. Since it is sets all the locale setting to C, all non-US-English characters are discarded.
doc_4049
Cannot implicitly convert type 'int' to 'SVSFinAP.Databases.FMSExpenseCode' where SVSFinAP.Databases.FMSExpenseCode is defined as int? This is my code: ol.FMSExpenseCode = (int)rowOrderLine.OrderLineExpenseCodeID; A: 'SVSFinAP.Databases.FMSExpenseCode' <-- is not an integer which means you need to convert to 'SVSFinAP.Databases.FMSExpenseCode' type A: are you sure the ol.FMSExpenseCode is an int? The exception message says it is an SVSFinAP.Databases.FMSExpenseCode type. Check the type of you are working like ol.FMSExpenseCode, rowOrderLine.OrderLineExpenseCodeID and cast to the right type. It is not an integer. A: Perhaps you need to cast, assuming it's an enum? ol.FMSExpenseCode = (FMSExpenseCode)rowOrderLine.OrderLineExpenseCodeID; A: ol.FMSExpenseCode = Convert.ToInt32(rowOrderLine.OrderLineExpenseCodeID);
doc_4050
ptxas fatal : Unresolved extern function 'get_group_id' In the PTX file I have the following for every OpenCL function call I use .func (.param .b64 func_retval0) get_group_id ( .param .b32 get_group_id_param_0 ) ; The above isn't present in the PTX files created by the OpenCL runtime when I provide it with a CL file. Instead it has the proper special register. Following these instructions (links against a different libclc library) gives me a segmentation fault during the LLVM IR to PTX compilation with the following error: fatal error: error in backend: Cannot cast between two non-generic address spaces Are those instructions still valid? Is there something else I should be doing? I'm using the latest version of libclc, Clang 3.7, and Nvidia driver 352.39 A: The problem is that llvm does not provide an OpenCL device code library. llvm however provides the intrinsics for getting the IDs of a GPU thread. Now you have to write your own implantations of get_global_id etc. using clang's builtins and compile it to llvm bitcode with the nvptx target. Before you lower your IR to PTX you use llvm-link to link your device library with your compiled OpenCL module and that's it. A example how you would write such a function: #define __ptx_mad(a,b,c) ((a)*(b)+(c)) __attribute__((always_inline)) unsigned int get_global_id(unsigned int dimindx) { switch (dimindx) { case 0: return __ptx_mad(__nvvm_read_ptx_sreg_ntid_x(), __nvvm_read_ptx_sreg_ctaid_x(), __nvvm_read_ptx_sreg_tid_x()); case 1: return __ptx_mad(__nvvm_read_ptx_sreg_ntid_y(), __nvvm_read_ptx_sreg_ctaid_y(), __nvvm_read_ptx_sreg_tid_y()); case 2: return __ptx_mad(__nvvm_read_ptx_sreg_ntid_z(), __nvvm_read_ptx_sreg_ctaid_z(), __nvvm_read_ptx_sreg_tid_z()); default: return 0; } }
doc_4051
''' from datetime import datetime from datetime import date from datetime import time from datetime import timedelta import sys a = date.today() b = datetime.now() print("Today is :" +str(b)) q = int(input("enter your birth month :")) w = int(input("enter your brth day :")) my_bday = date(a.year,q,w) #print(my_bday) if my_bday < a : my_bday = my_bday.replace(year = a.year +1) time_to_bday = abs (a -my_bday) #print("The number of days remaining for your bday is :" +time_to_bday) o = time_to_bday.split(' ') z = o[0] k = timedelta(days = z) print("Time remaining for your bday is : " +str(b + k)) Here split is not working and giving below error: Traceback (most recent call last): File "f:/Ch2/practise.py", line 96, in <module> o = time_to_bday.split(' ') AttributeError: 'datetime.timedelta' object has no attribute 'split' I double checked the o/p of code till time_to_bday as below : PS F:\Ch2> & "C:/Users/sai kiran/AppData/Local/Programs/Python/Python36-32/python.exe" f:/Ch2/practise.py Today is :2021-05-01 20:32:08.677781 enter your birth month :11 enter your brth day :17 200 days, 0:00:00 A: Timedelta isn't a str so doesn't have spilit(). print() converts it to str. You need to call o=str(o) for example A: You have already calculated delta in time, It's not string anymore time_to_bday is timedelta object, you can directly get days as below time_to_bday.days if you want to print in hours you can print using time_to_bday.days * 24 From your code :: enter your birth month :4 enter your brth day :17 >> time_to_bday.days 350
doc_4052
I am able to get redirected to required URL with code={} value. When I am trying to use this code in below URL, https://connect.stripe.com/oauth/token\client_secret={{secret test key}}\code={{code}}\grant_type = authorization_code" 1.I get preflight is invalid (Redirect) error in browser from my angular solution. 2.The html for stripe login page from Postman. The code I wrote for making the post call to above URL (in angular) is : getCredentialsFromStripe(code: any) { let Url = "https://connect.stripe.com/oauth/token"; //\client_secret=" + {{key}} + "\code=" + code + "\grant_type = authorization_code"; return this.http.post(Url, { Body: "client_secret = {{key}}\code =" + code, Headers: { 'Authorization': 'Bearer '+ code, "Accept": "application/json; charset=UTF-8", "Access-Control-Allow-Origin": "https://connect.stripe.com/oauth/token" } }).map(res => res.json()); } As per suggestions on internet,I tried making the post call from backend(.NET core(2.0) API for me),but didn't get through in creating account for standard account type. Moreover testing from postman is giving the full html page of login ,instead of getting this object: { "token_type": "bearer", "stripe_publishable_key": "{PUBLISHABLE_KEY}", "scope": "read_write", "livemode": false, "stripe_user_id": "{ACCOUNT_ID}", "refresh_token": "{REFRESH_TOKEN}", "access_token": "{ACCESS_TOKEN}" } Can anybody give me a lead on this.I have been stuck past two days. Any thoughts will be really appreciated. A: Well,I was able to fix it. Instead of creating accounts using the URL (given above) in angular project (following the node.js documents),I called the stripe api's in Asp.net core (my api solution) and called them.It worked easily.
doc_4053
To better illustrate my point, here's how my history looks like now (let's say that TAG means the arbitrarily chosen point in history when the prototype started to become a solution): current repo: (ROOT)-----(commits)-----(TAG)--------(commits)---(HEAD) And this is how I would like it to look: current repo: (ROOT)-----(commits)-----(TAG)--------(commits)---(HEAD) new repo: (ROOT)-----(commits)-----(TAG == HEAD) Side question: is it possible to make it split them entirely, making them look like so: current repo: (TAG == ROOT)----(commits)-----(HEAD) new repo: (ROOT)-----------(commits)-----(TAG == HEAD) A: You can do whichever you want. For the "prototype" repo, I would start by creating a "mirror" clone git clone --mirror url/to/old/repo/origin To make the prototype version of the repo is pretty simple. You must want to move master back to the TAG that marks the last prototype version. You'll have to locate that commit. Say its SHA value is ABC123; then git reset --hard ABC123 If you have any other tags or branches from more recent history, you'll probably want to delete them. But since you say it's a simple, linear history, there shouldn't be much to that. Then you can clean this up if you want. There are a few ways; I usually go with rm -r .git/logs git gc --aggressive --prune=now And this is now your prototype repo. That gets you to the first picture. Now if you also want to remove the prototype history from the "solution" repo, again I'd start with a fresh clone. If this will replace the original repo, a plain clone is fine; if you're using this to start a new repo, again I'd suggest a mirror clone. From there, there are lots of ways to do it, but how about git rebase -i --root An editor pops up with a line per commit. Leave the 1st one alone. Change the first word on the 2nd commit through (and including) the 1st "solution" commit to squash, then save and exit the editor. After a little work, a new editor will come up showing the combined commit messages from the squashed commits. Make this look however you want, save and exit. If this was a regular clone and you're replacing the original repo, you now force-push the master ref back to origin. Note that this is an upstream rebase, and anyone else using the repo will have to recover from that. (See the git rebase documentation.)
doc_4054
<script type="text/javascript"> function validLogin() { if(document.getElementById("txtUserName").value == "") { alert("Please enter your UserName"); return false; } if(document.getElementById("txtPassword").value == "") { alert("Please enter your Password"); return false; } } </script> protected void Page_Load(object sender, EventArgs e) { BtnLogin.Attributes.Add("onClick","return ValidLogin();"); } A: I see that you're using ASP .NET (the Page_Load event on your posted code). I think that will be easier to handle validation through ASP .NET Validation Controls, i.e. RequiredFieldValidator. A: Check your case on return ValidLogin(); it doesn't match. P.S.: I hope you aren't performing all user validation client-side. A: It would probably be easier to user ASP .NET validation controls, here's a sample: User Name: <asp:TextBox ID="UserName" runat="server" /> <asp:RequiredFieldValidator ID="UserNameValidator" ControlToValidate="UserName" ErrorMessage="User Name Required" runat="server" /> Password: <asp:TextBox ID="Password" runat="server" /> <asp:RequiredFieldValidator ID="PasswordValidator" ControlToValidate="Password" ErrorMessage="Password Required" runat="server" /> A: first make sure it's not a difference in case... your javascript function is validLogin and in Page_Load you have ValidLogin
doc_4055
capture = cv2.VideoCapture(0) while True: ret, frame = capture.read() cv2.imshow('video', frame) # esc if cv2.waitKey(1) == 27: photo = frame break capture.release() cv2.destroyAllWindows() img = Image.fromarray(cv2.cvtColor(photo, cv2.COLOR_BGR2RGB)) img = img.resize([224, 224], Image.LANCZOS) if transform is not None: img = transform(img).unsqueeze(0) return img This is my code to get image from the camera, image_tensor = img.to(device) And I have an error at the line above... Traceback (most recent call last): File "E:/PycharmProjects/ArsElectronica/image_captioning/sample.py", line 126, in <module> main(args) File "E:/PycharmProjects/ArsElectronica/image_captioning/sample.py", line 110, in main caption = Image_Captioning(args, img) File "E:/PycharmProjects/ArsElectronica/image_captioning/sample.py", line 88, in Image_Captioning image_tensor = img.to(device) AttributeError: 'Image' object has no attribute 'to' The error is like this. If I have the image as png file and reload it with PIL, it works. But the one I want is to use the image without saving. Pls... Someone save me... A: You could convert your PIL.Image to torch.Tensor with torchvision.transforms.ToTensor: if transform is not None: img = transform(img).unsqueeze(0) tensor = T.ToTensor()(img) return tensor having imported torchvision.transforms as T
doc_4056
var fs = require('fs'); var path = require('path'); var Sequelize = require('sequelize'); var CONFIG = require('../config/config'); var sequelize = new Sequelize(CONFIG.database, CONFIG.user, CONFIG.password, { host: CONFIG.host, dialect: CONFIG.dialect, port: CONFIG.port, operatorsAliases: Sequelize.Op, logging: false }); var db = {}; fs.readdirSync(__dirname) .filter(function (file) { return (file.indexOf('.') !== 0) && (file !== 'index.js'); }) .forEach(function (file) { var model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function (modelName) { if ('associate' in db[modelName]) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db; And I would like to include twice a model with different conditions, so I plan to use alias on this case: module.exports = function (sequelize, DataTypes) { var TSection = sequelize.define('TSection', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING(500), allowNull: true }, TestId: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true, field: 'test_id', references: { model: 'test', key: 'id' } }, }, { tableName: 't_sections' }); TSection.associate = function (models) { TSection.belongsTo(models.Test), { foreignKey: 'id', as: 'sections' }, TSection.hasMany(models.TQuestion), { foreignKey: 'id' } }; return TSection; }; and module.exports = function (sequelize, DataTypes) { var Test = sequelize.define('Test', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING(500), allowNull: true, }, }, { tableName: 'tests' }) Test.associate = function (models) { Test.hasMany(models.TSection), { foreignKey: 'id' } } return Test; }; When I try to get the info like: const test = await Test.findOne({ attributes: ['id', 'name'], include: [{ model: TSection, attributes: ['id', 'name'], }, { model: TSection, as: 'sections' }] }); I have this error and I don't know what might be causing it: NOTE: I've tried several combinations including and not including the said model UnhandledPromiseRejectionWarning: Error: Error: SequelizeEagerLoadingError: TSection is associated to Test using an alias. You've included an alias (sections), but it does not match the alias(es) defined in your association (TSections). I case you are wondering my objective is to count the number of total sections, but to retrieve only one (the one that matches a given condition) Thanks! A: You added extra brackets in associations. They should look like this: TSection.associate = function (models) { TSection.belongsTo(models.Test, { foreignKey: 'id', as: 'sections' }); TSection.hasMany(models.TQuestion, { foreignKey: 'id' }); }; and Test.associate = function (models) { Test.hasMany(models.TSection, { foreignKey: 'id' }) }
doc_4057
r = 0 c = txtbbus.Text For i = 0 To n - 1 For j = 0 To n - 1 If a(i, j) = c Then txtbres.Text = "The value exists " & r & " and it's in the position (" & i & ", " & j & ") " Else txtbres.Text = "The value doesn't exists" End If Next j Next i And this is how I initialize a: txtbmatriz.Text = "" For i = 0 To n - 1 For j = 0 To n - 1 a(i, j) = CInt((100 * Rnd()) + 1) txtbmatriz.Text += a(i, j) & " " m += a(i, j) l += 1 Next j txtbmatriz.Text += vbCrLf Next i A: The problem is almost certainly that you don't break out of the loop when you find a match. Your code will only ever show you the result of the last element in the array because you always keep searching to the last element. Once you find a match, there's no point to looking further and, in fact, doing so is detrimental. Once you find a match, stop looking. Finding a single/first match: Dim rng As New Random Dim matrix = New Integer(9, 9) {} For i = 0 To matrix.GetUpperBound(0) For j = 0 To matrix.GetUpperBound(1) matrix(i, j) = rng.Next(1, 101) Next Next Dim target = rng.Next(1, 101) Dim message As String For i = 0 To matrix.GetUpperBound(0) For j = 0 To matrix.GetUpperBound(1) If matrix(i, j) = target Then message = $"{target} found at ({i},{j})" Exit For End If Next If message IsNot Nothing Then Exit For End If Next Console.WriteLine(If(message, $"{target} not found")) Finding all matches: Dim rng As New Random Dim matrix = New Integer(9, 9) {} For i = 0 To matrix.GetUpperBound(0) For j = 0 To matrix.GetUpperBound(1) matrix(i, j) = rng.Next(1, 101) Next Next Dim target = rng.Next(1, 101) Dim matches As New List(Of String) For i = 0 To matrix.GetUpperBound(0) For j = 0 To matrix.GetUpperBound(1) If matrix(i, j) = target Then matches.Add($"({i},{j})") End If Next Next Console.WriteLine(If(matches.Any(), $"{target} found at {String.Join(", ", matches)}", $"{target} not found")) A: Try this: r = 0 c = txtbbus.Text Dim i As Integer Dim j As Integer Dim FoundMatch As Boolean = False For i = 0 To n - 1 For j = 0 To n - 1 If a(i, j) = c Then FoundMatch = True Exit For End If Next j If FoundMatch = True Then Exit For End If Next i If FoundMatch = True Then txtbres.Text = "The value exists " & r & " and it's in the position (" & i & ", " & j & ") " Else txtbres.Text = "The value doesn't exists" End If A: I'm going to assume c = txtbbus.Text is from some form input. Meaning a string. For the equality check you'd be testing against an Int type. Try casting the input from txtbbus.Text as an integer. Also, like the other poster said breaking from the loop on finding your match would also be a good decision.
doc_4058
<ul> <li> <p><span>can you slice columns in a 2d list? </span></p> <pre><code class='language-python' lang='python'>queryMatrixTranspose[a-1:b][i] = queryMatrix[i][a-1:b] </code></pre> <ul> <li> <span>No: can&#39;t do this because python doesn&#39;t support multi-axis slicing, only multi-list slicing; see the article </span><a href='http://ilan.schnell-web.net/prog/slicing/' target='_blank' class='url'>http://ilan.schnell-web.net/prog/slicing/</a><span> for more info.</span> </li> </ul> </li> </ul> The answer on the flashcard will always be a list item located under the xpath: /html/body/ul/li/ul. I'd like to retrieve the answer in the format shown here <li> <span>No: can&#39;t do this because python doesn&#39;t support multi-axis slicing, only multi-list slicing; see the article </span><a href='http://ilan.schnell-web.net/prog/slicing/' target='_blank' class='url'>http://ilan.schnell-web.net/prog/slicing/</a><span> for more info.</span> </li> The flashcard's question is everything that remains in the xpath: /html/body/ul/li after the answer has been extracted: <li> <p><span>can you slice columns in a 2d list? </span></p> <pre><code class='language-python' lang='python'>queryMatrixTranspose[a-1:b][i] = queryMatrix[i][a-1:b] </code></pre> </li> For each flashcard in an unordered list of flashcards, I'd like to extract the utf-8 encoded html content of the question and answer list items. That is, I'd like to have both the text and html tags. I tried to solve this problem by iterating through each flashcard and corresponding answer and removing the child-node answer from the parent-node flashcard. flashcard_list = [] htmlTree = html.fromstring(htmlString) for flashcardTree,answerTree in zip(htmlTree.xpath("/html/body/ul/li"), htmlTree.xpath('/html/body/ul/li/ul')): flashcard = html.tostring(flashcardTree, pretty_print=True).decode("utf-8") answer = html.tostring(answerTree, pretty_print=True).decode("utf-8") question = html.tostring(flashcardTree.remove(answerTree), pretty_print=True).decode("utf-8") flashcard_list.append((question,answer)) However, when I try to remove the answer child-node with flashcardTree.remove(answerTree), I encounter the error, TypeError: Type 'NoneType' cannot be serialized. I don't understand why this function would return none; I'm trying to remove a node at /html/body/ul/li/ul which is a valid child node of /html/body/ul/li. Whatever suggestions you have would be greatly appreciated. I'm not in any way attached to the code I wrote in my first attempt; I'll accept any answer where the output is a list of (question,answer) tuples, one for each flashcard. A: If I understand correctly what you are looking for, this should work: for flashcardTree,answerTree in zip(htmlTree.xpath("/html/body/ul/li/p/span"), htmlTree.xpath('/html/body/ul/li/ul/li/descendant-or-self::*')): question = flashcardTree.text answer = answerTree.text_content().strip() flashcard_list.append((question,answer)) for i in flashcard_list: print(i[0],'\n',i[1]) Output: can you slice columns in a 2d list? No: can't do this because python doesn't support multi-axis slicing, only multi-list slicing; see the article http://ilan.schnell-web.net/prog/slicing/ for more info.
doc_4059
// grab entity you want to update entity.UserId = "123"; // update the fields you want to update. entity.Name = "bob"; Dbcontext.SubmitChanges(); I am wondering can you juse pass in a new object and have it figure it out? Like could I do this? Enity myEntity = new Entity(); myEntity.UserId = "123"; myEntity.Name = bob: // grab entity record // shove record ito the found record // it figured out what to update and what no to update A: Depending on what exactly you want to do you either need the InsertOnSubmit method, or the Attach method of the respective table (i.e. dbContext.Entities). InsertOnSubmit is used to add a record, while Attach can be used if you want to affect an UPDATE without having to first SELECT the record (you already know the primary key value) A: In the case you have the dbContext available and ready, just add InsertOnSubmit: Entity myEntity = new Entity(); myEntity.UserId = "123"; myEntity.Name = bob: Dbcontext.InsertOnSubmit(myEntity); Dbcontext.SubmitChanges(); As the name of the method implies, this will insert your new entity into the database on calling SubmitChanges. Marc A: If you want to do this for performance reasons then you shouldn't worry about it. Linq to Sql will cache objects locally so that just grabbing an entity by ID to modify some fields is very cheap. A: It's possible to attach and persist it to the database, however you may want to set a field to check for concurrency (ie LastModified). If you are going to use the Attach method on the data context, you need to set the primary/composite keys before you attach the entity (so you don't trigger INotifyPropertyChanging, INotifyPropertyChanged events).
doc_4060
import pytest class TimeLine: def __init__(self, s, instances=[0, 0, 0]): self.s = s self.instances = instances @pytest.fixture(params=[ ('foo', [0, 2, 4, 0, 6]), ('bar', [2, 5]), ('hello', [6, 8, 10]) ]) def timeline(request): return TimeLine(request.param[0], request.param[1]) This works def test_timeline(timeline): for instance in timeline.instances: assert instance % 2 == 0 I would like to create a parameterized test for the length of instances. @pytest.mark.parametrize('length', [ (5), (1), (3) ]) def test_timeline(length, timeline): assert len(timeline.instances) == length There should be 3 tests. The first and the last tests should pass. The second test should fail. How would I set up the test to do this? A: I'll note that @pytest.mark.parameterize does exactly the same thing as the parameterized fixture you set up: runs the test once for each parameter. Therefore, I never use it because the indentation gets out of control with any sort of nested structure. I use this template: well_named_params = [1,2,3] # I move this outside to avoid information overload. @pytest.fixture( params=well_named_params, ids=["one","two","three"] # test label ) def some_param(request): """ Run the test once for each item in params. Ids just provide a label for pytest. """ return request.param Your code is good, but you need a comma after the numbers to denote a tuple. Should be (5,), (1,), (3,). I'm not 100% sure that each entry needs to be iterable, so if that doesn't work, try just removing the parenthesis.
doc_4061
EDIT: here's the code I'm using to initialize it: public class Console extends JPanel implements ActionListener, Serializable { boolean ready = false; protected JTextField textField; protected JTextArea textArea; private final static String newline = "\n"; Game m_game; Thread t; public Console(Game game) { super(new GridBagLayout()); m_game = game; textField = new JTextField(20); textField.setPreferredSize(null); textField.addActionListener(this); textArea = new JTextArea(20, 60); textArea.setEditable(false); textArea.setWrapStyleWord(true); textArea.setLineWrap(true); Font comic = new Font("Serif", Font.PLAIN, 14); textArea.setFont(comic); JScrollPane scrollPane = new JScrollPane(textArea); //Add Components to this panel. GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; add(scrollPane, c); add(textField, c); } public void actionPerformed(ActionEvent evt) { String text = textField.getText(); m_game.input = text; textField.selectAll(); textArea.setCaretPosition(textArea.getDocument().getLength()); m_game.wait = false; synchronized (m_game){ ready = true; m_game.notifyAll(); } } public void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("Game"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add contents to the window. frame.add(new Console(m_game)); //Display the window. frame.pack(); frame.setVisible(true); } A: I think it's connected with Layout Manager. http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
doc_4062
I read several pages of documentation but still, I have big problems concerning the structure of a Vaadin app. My problem is that I lack something about the theory behind it, and I'll try to expose my problems with a first attempt of code. I'll really appreciate anything that can help me understand how Vaadin works. I want to create a website where a user can register, log in and log out. The structure of the GUI of the website is an Homepage where there is something like a button or something like that to do the login if the user is not logged, and if the user is logged, instead of the login button, it should appear a logout button. First thing, I have a class that extends UI; in that class, I set the servlet and the init() method. In the init() method, I start creating a VerticalLayout(), then a MenuBar and a Panel (called contentPanel). Then, I create a Navigator. The first problem I encounter is that I understand the Navigator as a possibility of browsing between different pages; the constructor of a Navigator wants a SingleComponentContainer, so for now, I don't know how to navigate between different web pages. For my example, in the constructor I use the Panel: new Navigator(this, contentPanel); Then I add different View that will then appear inside the panel. Finally, I navigate to the Welcome page. MyUI class: public class MyUI extends UI { /** * Class that checks if the user is in the database * and the psw inserted is correct */ public static Authentication AUTH; public static User user = null; @WebServlet(value = "/*", asyncSupported= true) @VaadinServletConfiguration(productionMode = false, ui = MyUI.class) public static class MyUIServlet extends VaadinServlet { } @Override protected void init(VaadinRequest request) { AUTH = new Authentication(); VaadinSession.getCurrent().setAttribute("user", user); final VerticalLayout layout = new VerticalLayout(); layout.setMargin(true); setContent(layout); Panel contentPanel = new Panel("Main Panel"); contentPanel.setSizeFull(); new Navigator(this, contentPanel); getNavigator().addView(LoginPage.NAME, LoginPage.class); getNavigator().setErrorView(LoginPage.class); getNavigator().addView(LogoutPage.NAME, LogoutPage.class); getNavigator().addView(WelcomePage.NAME, WelcomePage.class); MenuBar.Command welcome = new Command() { @Override public void menuSelected(MenuItem selectedItem) { getNavigator().navigateTo(WelcomePage.NAME); } }; MenuBar.Command login = new Command() { @Override public void menuSelected(MenuItem selectedItem) { getNavigator().navigateTo(LoginPage.NAME); } }; MenuBar.Command logout = new Command() { @Override public void menuSelected(MenuItem selectedItem) { getNavigator().navigateTo(LogoutPage.NAME); } }; MenuBar mainMenu = new MenuBar(); mainMenu.addItem("Welcome", VaadinIcons.ARROW_CIRCLE_LEFT, welcome); mainMenu.addItem("Login", VaadinIcons.ENTER, login); mainMenu.addItem("Logout", VaadinIcons.EXIT, logout); layout.addComponent(mainMenu); layout.addComponent(contentPanel); getNavigator().navigateTo(WelcomePage.NAME); } } LoginPage class: public class LoginPage extends VerticalLayout implements View { private static final long serialVersionUID = 1L; public static final String NAME = "loginpage"; public LoginPage(){ Panel panel = new Panel("Login"); panel.setSizeUndefined(); addComponent(panel); FormLayout content = new FormLayout(); TextField username = new TextField("Username"); content.addComponent(username); PasswordField password = new PasswordField("Password"); content.addComponent(password); Button send = new Button("Enter"); send.addClickListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { //The authenticate method will returns //true if the credentials are correct //false otherwise if(MyUI.AUTH.authenticate(username.getValue(), password.getValue())){ //In AUTH there is a User field called "user" //User is a class that represents an user (so it has mail, psw, name etc) VaadinSession.getCurrent().setAttribute("user", MyUI.AUTH.getUser()); }else{ Notification.show("Invalid credentials", Notification.Type.ERROR_MESSAGE); } } }); content.addComponent(send); content.setSizeUndefined(); content.setMargin(true); panel.setContent(content); setComponentAlignment(panel, Alignment.MIDDLE_CENTER); } } Logout class has the same structure of Login class; there is a logout method: private void doLogout() { MyUI.AUTH.setUser(null); VaadinSession.getCurrent().setAttribute("user", MyUI.AUTH.getUser()); getSession().close(); } Another problem is: how can I dynamically add components in my layout, basing on the user status (logged or not?) Next problem is: I didn't understand how to effectively do a logout. I'll add complete code to facilitate any tests. public class LogoutPage extends VerticalLayout implements View { private static final long serialVersionUID = 1L; public static final String NAME = "logoutpage"; public LogoutPage(){ Panel panel = new Panel("Logout"); panel.setSizeUndefined(); addComponent(panel); Button logout = new Button("Logout"); logout.addClickListener(e -> doLogout()); addComponent(logout); } private void doLogout() { MyUI.AUTH.setUser(null); VaadinSession.getCurrent().setAttribute("user", MyUI.AUTH.getUser()); getSession().close(); } } ______________________________________________________________________________ public class WelcomePage extends VerticalLayout implements View { private static final long serialVersionUID = 1L; public static final String NAME = "welcomepage"; public WelcomePage() { setMargin(true); setSpacing(true); Label welcome = new Label("Welcome"); welcome.addStyleName("h1"); addComponent(welcome); } @Override public void enter(ViewChangeEvent event) { } } ______________________________________________________________________________ public class Authentication { private static User user = null; //those fields should be in user; this is just a test private String userID = "ID"; private String psw = "psw"; public Authentication() { } public void setUser(User user) { Authentication.user = user; } public User getUser(){ return Authentication.user; } public Boolean authenticate(String userID, String psw){ if(userID == this.userID && psw == this.psw) { user = new User(); return true; } return false; } } A: I have seen many users struggling with the vaadin concept. In short it is not a page-based framework, where you switch to a new page with each mouse click. Instead it is more like a Swing application, where you have a single gui instance, where you add forms/poups/buttons, modify them and remove them based on user interaction. This is known as a Single-Page Application. The Navigator is mainly used to allow the user to navigate with the backward/forward buttons of the webbrowser to the "previous" page, or bookmark specific pages. This link provides some more detailed informations about this concept. To answer you question: - Use a single page/nvigation - When not logged in, show a modal login popup - When the user correctly enters authentification, remove the popup and show the main content in the vertical layout - When the user logs out, remove the content from the vertical layout For your simple use case, there is no need to work with the Navigator or Views A: I initially ran into the same issues, which got me interested in Spring and ultimately Vaadin4Spring. Check out https://github.com/peholmst/vaadin4spring/tree/master/samples/security-sample-managed even if you have no interest in using Spring. It will provide you some insight on your View Navigation and with the addition of the Vaadin4Spring Sidebar it can make it easy to control access to views and menus. I am sure permissions will be your focus soon which can be complex.
doc_4063
Suppose I have a Student table, a Subject table (ie Geography, History etc) and a StudentSubject table that records which subjects each student has chosen. StudentSubject contains StudentId and SubjectId as foreign keys. No student is to choose more that 5 subjects. Is there any way to define a validation rule on the table such that a given StudentId may not appear in the StudentSubject table more than 5 times? I could enforce the contraint by introducing an additional table, but if possible, I like to avoid that. I also want to define a constraint at table level, rather than use vba code that gets invoked when a record is inserted via a form. Access, as far as I know, has no such thing as triggers, as one would have in an sql system. A: You can use a CHECK constraint to limit the possibilities: ALTER TABLE StudentSubject ADD CONSTRAINT Max5Subjects CHECK( NOT EXISTS( SELECT 1 FROM StudentSubject GROUP BY StudentID HAVING Count(StudentID) > 5 ) ) Note that this might slow down data entry a bit, especially if StudentID is not indexed. Check constraints need to be executed either in ANSI 92 compatible mode, or using ADO (e.g. using CurrentProject.Connection.Execute). More details here To execute it using ADO, you can just use this single line in the immediate window: CurrentProject.Connection.Execute "ALTER TABLE StudentSubject ADD CONSTRAINT Max5Subjects CHECK(NOT EXISTS( SELECT 1 FROM StudentSubject GROUP BY StudentID HAVING Count(StudentID) > 5))" Also, keep in mind that if somehow there are records that violate the constraint (e.g. because they were present before the constraint got added), your table will get locked down fully.
doc_4064
If any one has any insight or knows of a tutorial explaining this process please post. Part of the reason I am trying to do this is for code readability, better code management, and a better code structure for the application. I came across this stack thread explaining some of what I am talking about. Also here's a picture of what my project looks like if that helps shed any light. A: You need to consider the parent class of your controllers, UIViewController for example. To do so, you must check the .h file and your xib/nib file. I. In your .h file, you will be seing: @interface ViewControllerWelcome : NSObject Change 'NSObject' to 'UIViewController' - this will mean that ViewControllerWelcome has a parent class UIViewController. II. In your nib/xib file: 1. Click on the controller that you are going to set from the storyboard. 2. Go to interface builder and click the "Identity Inspector" (third item from the left) from the Utilities panel. 3. You need to specifically set each controller's name (eg. ViewControllerWelcome) Do these to all controllers from your storyboard. Here's something you can read about ViewControllers and Storyboards.
doc_4065
Is there any other way to do this? A: * *Using iOS AV Foundation framework and a few lines of Objective-C (you can also convert from MOV to MP4 since Android cannot read MOV): so using this code without buffer play smooth video from Live URL its works but before upload video to your server use this code and convert your video and after upload it. so video is play video like snapchat without any load. Don't forgot to add this below framework into your Project. #import <AVFoundation/AVAsset.h> #import <AVFoundation/AVAssetExportSession.h> #import <AVFoundation/AVMediaFormat.h> + (void) convertVideoToMP4AndFixMooV: (NSString*)filename toPath:(NSString*)outputPath { NSURL *url = [NSURL fileURLWithPath:filename]; AVAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil]; AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:avAsset presetName:AVAssetExportPresetPassthrough]; exportSession.outputURL = [NSURL fileURLWithPath:outputPath]; exportSession.outputFileType = AVFileTypeAppleM4V; // This should move the moov atom before the mdat atom, // hence allow playback before the entire file is downloaded exportSession.shouldOptimizeForNetworkUse = YES; [exportSession exportAsynchronouslyWithCompletionHandler: ^{ if (AVAssetExportSessionStatusCompleted == exportSession.status) {} else if (AVAssetExportSessionStatusFailed == exportSession.status) { NSLog(@"AVAssetExportSessionStatusFailed"); } else { NSLog(@"Export Session Status: %d", exportSession.status); } }]; } A: Here is the code to a method I edited and wrote to work with iOS to find and then write the moov atom to specific location so then right after you have these two parts of the video file you just need to access the bytes of the video file from where the FTYP atom ends(take a look at the variables marked as start_offset and last_offset) and the streaming will occur. - (NSString *)fixForFastPlayback:(char*)dest:(ALAsset*)selected { FILE *infile = NULL; FILE *outfile = NULL; uint32_t atom_type = 0; uint64_t atom_size = 0; uint64_t atom_offset = 0; uint64_t last_offset; uint64_t moov_atom_size; uint64_t ftyp_atom_size = 0; uint64_t i, j; uint32_t offset_count; uint64_t current_offset; uint64_t start_offset = 0; ALAssetRepresentation * rep = [[selected defaultRepresentation] retain]; int bufferSize = 8192; // or use 8192 size as read from other posts int read = 0; NSError * err = nil; uint8_t * buffer = calloc(bufferSize, sizeof(*buffer)); uint8_t * ftyp_atom; /* traverse through the atoms in the file to make sure that 'moov' is * at the end */ int asset_offset = 0; while (asset_offset < [rep size]) { read = [rep getBytes:buffer fromOffset:asset_offset length:ATOM_PREAMBLE_SIZE error:&err]; asset_offset += read; if (err != nil) { NSLog(@"Error: %@ %@", err, [err userInfo]); } atom_size = (uint32_t)BE_32(&buffer[0]); atom_type = BE_32(&buffer[4]); /* keep ftyp atom */ if (atom_type == FTYP_ATOM) //no idea what an atom is, maybe a header or some sort of meta data or a file marker { ftyp_atom_size = atom_size; ftyp_atom = calloc(ftyp_atom_size, sizeof(*buffer)); if (!ftyp_atom) { printf ("could not allocate %"PRIu64" byte for ftyp atom\n", atom_size); } asset_offset -= ATOM_PREAMBLE_SIZE; read = [rep getBytes:ftyp_atom fromOffset:asset_offset length:ftyp_atom_size error:&err]; asset_offset += read; start_offset = asset_offset; } else { asset_offset += (atom_size - ATOM_PREAMBLE_SIZE); } printf("%c%c%c%c %10"PRIu64" %"PRIu64"\n", (atom_type >> 24) & 255, (atom_type >> 16) & 255, (atom_type >> 8) & 255, (atom_type >> 0) & 255, atom_offset, atom_size); if ((atom_type != FREE_ATOM) && (atom_type != JUNK_ATOM) && (atom_type != MDAT_ATOM) && (atom_type != MOOV_ATOM) && (atom_type != PNOT_ATOM) && (atom_type != SKIP_ATOM) && (atom_type != WIDE_ATOM) && (atom_type != PICT_ATOM) && (atom_type != UUID_ATOM) && (atom_type != FTYP_ATOM)) { printf ("encountered non-QT top-level atom (is this a Quicktime file?)\n"); break; } atom_offset += atom_size; /* The atom header is 8 (or 16 bytes), if the atom size (which * includes these 8 or 16 bytes) is less than that, we won't be * able to continue scanning sensibly after this atom, so break. */ if (atom_size < 8) break; } if (atom_type != MOOV_ATOM) { printf ("last atom in file was not a moov atom\n"); free(ftyp_atom); fclose(infile); return 0; } asset_offset = [rep size]; asset_offset -= atom_size; last_offset = asset_offset; moov_atom_size = atom_size; uint8_t * moov_atom = calloc(moov_atom_size, sizeof(*buffer)); if (!moov_atom) { printf ("could not allocate %"PRIu64" byte for moov atom\n", atom_size); } read = [rep getBytes:moov_atom fromOffset:asset_offset length:moov_atom_size error:&err]; asset_offset += read; /* this utility does not support compressed atoms yet, so disqualify * files with compressed QT atoms */ if (BE_32(&moov_atom[12]) == CMOV_ATOM) { printf ("this utility does not support compressed moov atoms yet\n"); } /* crawl through the moov chunk in search of stco or co64 atoms */ for (i = 4; i < moov_atom_size - 4; i++) { atom_type = BE_32(&moov_atom[i]); if (atom_type == STCO_ATOM) { printf (" patching stco atom...\n"); atom_size = BE_32(&moov_atom[i - 4]); if (i + atom_size - 4 > moov_atom_size) { printf (" bad atom size\n"); } offset_count = BE_32(&moov_atom[i + 8]); for (j = 0; j < offset_count; j++) { current_offset = BE_32(&moov_atom[i + 12 + j * 4]); current_offset += moov_atom_size; moov_atom[i + 12 + j * 4 + 0] = (current_offset >> 24) & 0xFF; moov_atom[i + 12 + j * 4 + 1] = (current_offset >> 16) & 0xFF; moov_atom[i + 12 + j * 4 + 2] = (current_offset >> 8) & 0xFF; moov_atom[i + 12 + j * 4 + 3] = (current_offset >> 0) & 0xFF; } i += atom_size - 4; } else if (atom_type == CO64_ATOM) { printf (" patching co64 atom...\n"); atom_size = BE_32(&moov_atom[i - 4]); if (i + atom_size - 4 > moov_atom_size) { printf (" bad atom size\n"); } offset_count = BE_32(&moov_atom[i + 8]); for (j = 0; j < offset_count; j++) { current_offset = BE_64(&moov_atom[i + 12 + j * 8]); current_offset += moov_atom_size; moov_atom[i + 12 + j * 8 + 0] = (current_offset >> 56) & 0xFF; moov_atom[i + 12 + j * 8 + 1] = (current_offset >> 48) & 0xFF; moov_atom[i + 12 + j * 8 + 2] = (current_offset >> 40) & 0xFF; moov_atom[i + 12 + j * 8 + 3] = (current_offset >> 32) & 0xFF; moov_atom[i + 12 + j * 8 + 4] = (current_offset >> 24) & 0xFF; moov_atom[i + 12 + j * 8 + 5] = (current_offset >> 16) & 0xFF; moov_atom[i + 12 + j * 8 + 6] = (current_offset >> 8) & 0xFF; moov_atom[i + 12 + j * 8 + 7] = (current_offset >> 0) & 0xFF; } i += atom_size - 4; } } outfile = fopen(dest, "wb"); NSLog(@"%llu",last_offset); //global variables to be used when returning the actual data start_offset_not_c = start_offset; last_offset_not_c = last_offset; if (ftyp_atom_size > 0) { printf ("writing ftyp atom...\n"); if (fwrite(ftyp_atom, ftyp_atom_size, 1, outfile) != 1) { perror(dest); } } printf ("writing moov atom...\n"); if (fwrite(moov_atom, moov_atom_size, 1, outfile) != 1) { perror(dest); } fclose(outfile); free(ftyp_atom); free(moov_atom); ftyp_atom = NULL; moov_atom = NULL; return [NSString stringWithCString:dest encoding:NSStringEncodingConversionAllowLossy]; } Enjoy!
doc_4066
z = ['0b111000','0b1000011'] # z is a list d = z.count('1') print(d) The output is 0. Whereas the required output should be in the form of [3,3] which is number of ones in every element that Z is containing : A: Here it is : z=['0b111000','0b1000011'] finalData = [] for word in z: finalData.append(word.count('1')) print(finalData) The problem with your code was you were trying to use count() method on list type and it is used for string. You first need to get the string from the list and then use count() method on it. Hope this helps :) A: z = ['0b111000','0b1000011'] d = z.count('1') This attempts to find the number of times the string '1' is in z. This obviously returns 0 since z contains '0b111000' and '0b1000011'. You should iterate over every string in z and count the numbers of '1' in every string: z = ['0b111000','0b1000011'] output = [string.count('1') for string in z] print(output) # [3, 3] A: list.count(x) will count the number of occurrences such that it only counts the element if it is equal to x. Use list comprehension to loop through each string and then count the number of 1s. Such as: z = ['0b111000','0b1000011'] d = [x.count("1") for x in z] print(d) This will output: [3, 3]
doc_4067
I'm using perforce and the TC-Server should be configured correct, but when running the project I'm getting the error: [Updating sources: server side checkout...] Error while applying patch: Failed to change text file: C:\Projects\BuildSrv7... C:\Projects\BuildSrv7.. (Access denied) I checked the Settings and everybody has full rights in the directory. And idea, what to do, or how this could happen? A: Please check the known issues. Most likely it's your case. A: Ok, solved the problem. In my case it was an error with Clientmapping configuration. Teamcity default was "//depot/... //team-city-agent/.." I changed it to "//depot/... //team-city-agent/..." with 3 dots on the end and it worked. Thats the normal way of perforce with 3 dots.
doc_4068
Before I make second Ajax call, I need to check some condition. And if its true, then I need to make second ajax call otherwise, there is no need to make second ajax call. Here is Pseudo-code $.when($.get(url, function (result, status, xhr) { myresult = result; })), ( //If XYZ === 10 //Make second Ajax call only if condition is true ).then(function (r1, r2) { //DO something }); How can I achieve this ?? With Jquery or any other library ?? A: Execute a function after two ajax requests are successful. $.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) { //if both the calls are sucess then only you can reach here. // inside this you can make your third ajax call. } }); A: var first = $.ajax(...); var second = (condition) ? $.ajax(...) : $.Deferred().resolve(); // ajax only on condition $.when(first, second).then(function(res1, res2){ // work with res1 and res2, res2 is undefined if no call was made }); A: You can use ternary operator for second ajax call. pass null value if condition is false as second parameter to $.when. Here is Pseudo-code $.when( //first ajax call , (XYZ===10) ? //second ajax call : null ).then(function (r1, r2) { //DO something }); Hope it helps. Demo:- jsfiddle.net/NF2jz/5721 (try for a=0 and a=1)
doc_4069
Thanks in Advance A: To do so, sign up for a free trial of QuickBooks Online at http://quickbooks.intuit.com using existing intuit id. Thanks
doc_4070
In my app navigation behaviour is random, it not be in sequence every time. Since page viewer perform caching to load extra child, and this is what my problem is. I am not sure exactly when I should initialise/release member of child class. Required suggestion from you guys, will it be preferable to use PageViwer in this case or I should go with traditional activity flow for each of component. A: ViewPager is typically used for move efficient horizontal item to item navigation. Typical use cases would be * *Swiping through the related items (e.g. emails, images, songs of an album, etc.) *Swiping between the tabs *Swiping back-and-forth in a wizard-like activity For more details you can read a section about Swipe Views Android Design pattern. Regarding the lifecycle, it basically uses the same lifecycle as any other Fragment. The only difference is, that lifecycle methods can be called a bit later or earlier than you expect, because of fragment's caching ViewPager implements. I am not sure exactly when I should initialise/release member of child class. You should basically rely on two methods: onStart() and onStop(). In onStart() you create class members and initialize everything you want to. In onStop() method you should deinitialize everything and remove all listeners you set in onStart(). Method setUserVisibleHint() is used independently of onStart() or onStop(). You shoud better not initialize or destroy anything in there. You must not consider it to the a lifecycle method, because it's not. It's there just to give you a hint, that your fragment is visible to the user. Here you can start or stop animation, or request data update or perform similar tasks. This is the only purpose of this method. Required suggestion from you guys, will it be preferable to use PageViwer in this case or I should go with traditional activity flow for each of component. If your activity fits into one of the points mentioned about, I would suggest you to use ViewPager. Otherwise you might consider other options. Update: Most likely you won't override onCreate() and onDestroy() lifecycle methods of a fragment very often. You will use onCreateView() and onDestroyView() methods instead. There you can implement so called static initialization, the initialization which doesn't change while a fragment is still alive. This is layout initialization and similar tasks. A: ViewPager Usages Screen slides are transitions between one entire screen to another and are common with UIs like setup wizards or slideshows. If you have good knowledge in Fragment than ViewPager is right component for implements. Because viewpager provide a place which you can add fragment runtime. For eg. If you want to use TabBar in your project than viewpager is right component for using. Because it's provide a place which you can add Fragment runtime. Tabbar is common in android application. It's provide lot of functionality inbuild we can use to add fragment runtime. Facebook app using ViewPager to manage tab. Viewpager provide smoothness of your application. You can Download example from this url and check your requirement fulfill or not You can download the Example here A: ViewPager It is an widget Allows the user to swipe left or right to see an entirely new screen. Easy to show the user multiple tabs Dynamically add and remove pages (or tabs) at anytime. To Read More: http://architects.dzone.com/articles/android-tutorial-using
doc_4071
i tried to add the flowing : , curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch,CURLOPT_HTTPPROXYTUNNEL, true); here is my code : $proxy_ip = //proxy ip; $proxy_port = //proxy port; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://www.facebook.com');\\ example curl_setopt($ch, CURLOPT_PROXY, $proxy_ip); curl_setopt($ch, CURLOPT_PROXYPORT, $proxy_port); curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_exec($ch); echo curl_error($ch); echo $result; the proxy works fine on postman so i know for sure that the proxy that im using is live and it don't need authentication
doc_4072
catch (FilenotFoundException e){ system.out.println("File not found"); } try { FileReader freader = new FileReader("MyFile.txt"); } } Its asking for what the error is?? I thought it may be the e not being capitalized is that the reason? A: A try{} block should be followed by a catch{} block or finally{} block, you have reversed it. Use like this: - try { FileReader freader = new FileReader("MyFile.txt"); } catch (FileNotFoundException e){ System.out.println("File not found"); } As per Java Naming Convention: - * *Class Names start with a capital letter, and all subsequent word also start with capital letter. So, FilenotFoundException should be FileNotFoundException *And, system should be -> System. A: A catch{} block follows a try{} block, not the other way around. Also, FilenotFoundException should be FileNotFoundException. I doubt it will compile with the alternate spelling. Likewise with system vs. System, as indicated in @Rohit Jain's answer. A: It should be otherway. try followed by catch. try { FileReader freader = new FileReader("MyFile.txt"); }catch (FileNotFoundException e){ System.out.println("File not found"); } A: Since Java 7: try( FileReader freader = new FileReader("MyFile.txt")) { use freader }// try catch( IOException e) { e.printStackTrace(); } A: catch block should follow try try { //code that exception might occur } catch(Exception ex) { //catch the exception here. } your try block should either be followed by catch or finally. try { //code that exception might occur } finally { //close your resources here }
doc_4073
I am trying to achieve an effect that can be achieved if script would make following change <script type="text/javascript"> window.screen.__defineGetter__('width', function(){return 1024;}); window.screen.__defineGetter__('height', function(){return 768;}); </script> However, I cannot put this javascript inside a page, they have to be coming from Ruby, there are other things I might add other than window.width and window.screen driver = Selenium::WebDriver.for :firefox, :profile => profile driver.execute_script("window.screen.__defineGetter__('height', function(){return 768;});") # this executes before page load starts driver.navigate.to 'http://somesite.com/' driver.execute_script("window.screen.__defineGetter__('height', function(){return 768;});") # this executes after page completely loads So, what I want to do is to execute for example driver.execute_script("window.screen.__defineGetter__('height', function(){return 768;});") this while page loads, it does not work if I put this before navigate.to or after navigate.to. The same is if I change .navigate.to with .get A: Unfortunately this is not going to work. The reason is quite simple, anything that you inject before navigate.to is going to be executed on different page than your target page. Anything that you inject after navigate.to will most likely be executed after your application is started. If you would like to get specific window size, you can set it before you navigate to the page: driver.manage.window.resize_to("1024", "768") (for chrome browser) or create a separate Firefox profile, with predefined window width and height and use it in your tests.
doc_4074
$ cd $my_android_ndk_path/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/ $ make ARCH=arm CROSS_COMPILE=arm-eabi- modules_prepare it returns make: *** No rule to make target `modules_prepare'. Stop. If i type the same command from my Kernel Source (where my .config is located) $ make ARCH=arm CROSS_COMPILE=path/to/android_ndk/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/arm-eabi- modules_prepare it returns make: /path/to/android_ndk/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/arm-eabi-gcc: Command not found CHK include/linux/version.h make[1]: `include/asm-arm/mach-types.h' is up to date. CHK include/linux/utsrelease.h SYMLINK include/asm -> include/asm-arm CC kernel/bounds.s I am sure my directories are right. Does anyone have any idea what i could be doing wrong. I'm not using any particular tool for the ndk. I just unzipped the ndk and sdk seperatly and installaled JDK. Everything should work but it doesn't. A: did you check the compatibility between your arm-eabi-gcc (command: file /arm-eabi-gcc) compiler and your machine (32 or 64-bits)? If your arm-eabi-gcc is 32-bits machine compatible, to prevent errors like "make: arm-eabi-gcc: Command not found" in a 64-bits machine, you must install the package "ia32-libs" (command: sudo apt-get install ia32-libs). A: modules_prepare is a kernel preparation routine. Its purpose is to make sure that enough of the header files exist that you could subsequently build a kernel module against that kernel source tree. You see, the kernel has some auto-generated files, and without running at least modules_prepare, a kernel module compilation will not be possible. To this end, when you run modules_prepare from the kernel tree, that's a correct action. Running it from the cross compiler makes no sense because it doesn't understand what you're trying to do. I'll recommend you make your life easier by adding the cross compiler to the PATH as so: PATH=$PATH:$my_android_ndk_path/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/ cd <kernel directory> make ARCH=arm CROSS_COMPILE=arm-eabi- modules_prepare So this said... modules_prepare is just the first step in preparing to build a module. If you're trying to build a kernel module (LiME? I don't know what that is) then you'll need to follow the steps for building a kernel module. Edit: Now that I know what kernel module you're building (lime-forensics) I can see its SVN sources. The Makefile expects that you're building for your local computer, and not cross-compiling. Change the following: default: $(MAKE) -C /lib/modules/$(KVER)/build M=$(PWD) modules to default: $(MAKE) -C <your Android kernel> ARCH=arm CROSS_COMPILE=arm-eabi- M=$(PWD) modules That will likely get you further.
doc_4075
i can successfully console.log the result without putting the datatype json in the ajax dataType: 'json', when i console.log without it i get {"id":"1","post_id":"748037498494861","post_title":"laptop","image1":"team217.jpg","price":"1234"}{"id":"2","post_id":"740811329642473","post_title":"remote control car","image1":"team522.jpg","price":"50"}{"id":"4","post_id":"316194613858174","post_title":"Ipad 3","image1":"team523.jpg","price":"400"} however i cant display the json data if i put dataType: 'json', my console.log is empty i dont understand where the problem is $(document).ready(function(){ var username = $("#usernameinfo").text(); $.ajax({ type:"GET", url: "<?= base_url()?>"+"account/listings/more_user_ads", data: {"username":username,"pid":"<?=$this->input->get('pid')?>"}, success: function(res){ console.log(res); } }); }); php function more_user_ads(){ $post_id = $this->input->get('pid'); $username = $this->input->get('username'); $query = $this->get_where_custom('username', $username); if($query->num_rows()>0){ foreach($query->result() as $row){ if($post_id != $row->post_id){ $result = array( 'id'=> $row->id, 'post_id'=> $row->post_id, 'post_title'=> $row->post_title, 'image1'=> $row->image1, 'price'=> $row->price, 'price'=> $row->price, ); $res = json_encode($result); echo $res; A: Add each row to the $result array then echo the json_encode once. public function more_user_ads() { $post_id = $this->input->get('pid'); $username = $this->input->get('username'); $query = $this->get_where_custom('username', $username); $result = []; //so we have something if there are no rows if($query->num_rows() > 0) { foreach($query->result() as $row) { if($post_id != $row->post_id) { $result[] = array( 'id' => $row->id, 'post_id' => $row->post_id, 'post_title' => $row->post_title, 'image1' => $row->image1, 'price' => $row->price, 'price' => $row->price, ); } } } echo json_encode($result); } Actually, you can shorten this a bit by using $query->result_array(); because you won't have to convert an object to an array. public function more_user_ads() { $post_id = $this->input->get('pid'); $username = $this->input->get('username'); $query = $this->get_where_custom('username', $username); $result = []; //so we have something if there are no rows if($query->num_rows() > 0) { $rows = $query->result_array(); foreach($rows as $row) { if($post_id != $row['post_id']) { $result[] = $row; } } } echo json_encode($result); }
doc_4076
if [ $DAY -eq 1 ]; then code here; fi If the day is 1, so it's saying that I am in the new month, so I need to domy backup as well. Do you guys have any idea how can I do the check if today is the last day in the Month "January 31th" for example??? Thank you!!!! A: One way would be to use GNU date: if [[ $(date -d "+1 day" +%m) != $(date +%m) ]] then echo "Today is the last day of the month" else echo "Today is NOT the last day of the month" fi A: This gives you last day of previous month date -d "-$(date +%d) days -0 month" and this gives you last day of current month date -d "-$(date +%d) days +1 month" if [[ $(date +%d%m%Y -d "-$(date +%d) days +1 month") != $(date +%d%m%Y) || $(date +%d%m%Y -d "-$(date +%d) days -0 month") != $(date +%d%m%Y) ]] echo "Today is NOT the last day of the month" else echo "Today is the last day of the month" fi A: Getting the last day for a month is sometimes tricky, because not all months have the same days number of course. One way to do it is to get this month's first day, add a month to that (to get next month's first day) and then subtract a day. date --date="$(date +%Y-%m-01) +1 month -1 day" thu jan 31 00:00:00 -07 2019 And remember that date can output whatever format you want (argument starting with +). date --date="$(date +%Y-%m-01) +1 month -1 day" '+%F' 2019-01-31 See man date for more info or info '(coreutils) date invocation' for even more.
doc_4077
<div id="loading"> <div id="spinner"> <div class="spinner-icon"></div> </div> <p class="spinner-text">Please wait</p> </div> I'm interested which of the elements is loaded/displayed first? The icon? Text? I was thinking of something like this: Date t1 = new Date(); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("#loading"))); Date t2 = new Date(); long duration = t2.getTime() - t1.getTime(); But, can I use intertwined waits? Can I do this in a single script? A: Looking for something like this? long[] loadTime = wait.until(new Function<WebDriver, long[]>() { Date start = new Date(); long[] loadTimes = new long[] { 0, 0, 0, 0 }; String[] selectors = new String[] { "#loading", "#spinner", "#spinner .spinner-icon", "#spinner .spinner-text" }; @Override public long[] apply(WebDriver t) { int invisible = 0; for (int i = 0; i < selectors.length; i++) { if (!t.findElement(By.cssSelector(selectors[i])).isDisplayed()) { if (loadTimes[i] == 0) { loadTimes[i] = new Date().getTime() - start.getTime(); } invisible++; } } return invisible == 4 ? loadTimes : null; } });
doc_4078
$window.requestFileSystem($window.LocalFileSystem.PERSISTENT, 0, function(fs) { console.log("fs", fs); var directoryReader = fs.root.createReader(); directoryReader.readEntries(function(entries) { var arr = []; processEntries(entries, arr); // arr is pass by refrence $scope.files = arr; // $rootScope.hide(); }, function(error) { console.log(error); }); }, function(error) { console.log(error); }); The result of the above code just only allow me to access to the root directory of my phone. However, I want to access to the specific folders in my phone. For example, I want to open the 'Download' folder everytime I open the app. How can I get it to be done. Please help :( A: You maybe need to use window.resolveLocalFileSystemURL(pathToYourDownloadDir) ? and be sure your are permission to acces file system
doc_4079
Before compiling: // ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS // @output_file_name default.js // @formatting pretty_print,print_input_delimiter // ==/ClosureCompiler== var myObj1 = (function() { var undefined; //<----- declare undefined this.test = function(value, arg1) { var exp = 0; arg1 = arg1 == undefined ? true : arg1; //<----- use declare undefined exp = (arg1) ? value * 5 : value * 10; return exp; }; return this; }).call({}); var myObj2 = (function() { this.test = function(value, arg1) { var exp = 0; arg1 = arg1 == undefined ? true : arg1; //<----- without declare undefined exp = (arg1) ? value * 5 : value * 10; return exp; }; return this; }).call({}); Compiled: // Input 0 var myObj1 = function() { this.test = function(b, a) { a = a == void 0 ? true : a; //<----- var c = 0; return c = a ? b * 5 : b * 10 }; return this }.call({}), myObj2 = function() { this.test = function(b, a) { a = a == undefined ? true : a; //<----- var c = 0; return c = a ? b * 5 : b * 10 }; return this }.call({}); With this I believe the question of the use of "void 0 " and "undefined", is there any difference in the use or the two cases are well?. Edit if I define "var undefined" compiled with "void 0 ", if I did not define "undefined" compiled with "undedined. " then not a matter of number of characters between "undefined" and "void 0" Test Edit II: performance, based on this link Code and Test IE 8: typeof: 228ms undefined: 62ms void 0: 57ms Firefox 3.6: typeof: 10ms undefined: 3ms void 0: 3ms Opera 11: typeof: 67ms undefined: 19ms void 0: 20ms Chrome 8: typeof: 3ms undefined: 5ms void 0: 3ms A: From MDN: The void operator evaluates the given expression and then returns undefined. This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired. The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value). Closure Compiler swaps in void 0 because it contains fewer characters than undefined, therefore producing equivalent, smaller code. Re: OP comment yes, I read the documentation, but in the example I gave, "google closure" in a case using "void 0" and another "undefined" I believe this is actually a bug in Google Closure Compiler! A: The real only semantic difference between void expr and undefined is that on ECMAScript 3, the undefined property of the global object (window.undefined on browser environments) is writable, whereas the void operator will return the undefined value always. A popular pattern that is often implemented, to use undefined without worries is simply declaring an argument, and not passing anything to it: (function (undefined) { //... if (foo !== undefined) { // ... } })(); That will allow minifiers to shrink the argument maybe to a single letter (even shorter than void 0 :), e.g.: (function (a) { //... if (foo !== a) { // ... } })(); A: There is no difference, Try it yourself: void 0 === undefined will evaluate to true. undefined is 3 characters longer, I guess that is the reason why they use it that way. A: Just a follow-up on all the answers before. They look the same, but to the Compiler they are completely different. The two code sections compile to different outputs because one is referring to a local variable (the var undefined), and the compiler simply in-lines it because it is used exactly once and is no more than one line. If it is used more than once, then this in-lining won't happen. The in-lining provides a result of "undefined", which is shorter to represent as "void 0". The one without a local variable is referring to the variable called "undefined" under the global object, which is automatically "extern'ed" by the Closure Compiler (in fact, all global object properties are). Therefore, no renaming takes place, and no in-lining takes place. Voila! still "undefined".
doc_4080
I have to access the GPIO pins for AM57x. Can anybody please help me with this?
doc_4081
I generally write a series of helper classes for each of the tables that my application utilises. The issue I have is that I don't really know the best way to handle any SQL Timeouts or failed connections, apart from stick a Try-catch around each method that deals with returning data. In EntitySpaces the SQL Connection is built and executed only when I run any kind of CRUD command. For example: public TblUserCollection GetCollection() { TblUserCollection collection = new TblUserCollection(); collection.Query.Where(collection.Query.CompanyId == CompanyId); collection.Query.OrderBy(collection.Query.FullName, esOrderByDirection.Ascending); collection.Query.Load(); return collection; } This method is called when my helper class is told to assign the user list of a certain company to a ComboBox. The method then calls this and I assign the data to the list. I've got about 30 of these dotted around, all called GetCollection() in table specific helper classes. Aside from just writing the method as: public TblUserCollection GetCollection() { try { TblUserCollection collection = new TblUserCollection(); collection.Query.Where(collection.Query.CompanyId == CompanyId); collection.Query.OrderBy(collection.Query.FullName, esOrderByDirection.Ascending); collection.Query.Load(); return collection; } catch (System.Data.SqlClient.SqlException ex) { // } } What else can I do? A: Define a base class to handle your SQL error handling and let all your classes ex. TblUserCollection implement that base class. So when your child classes throw sql exceptions, you can have the base class handle them for you with graceful exits Have you tried Subsonic (free version) and LLBLGen(commercial version). Both will generate the DAL and some web components for you. Also are you happy with Entityspaces? Your answer will help me with my own projects. A: This doesn't really answer your question, but you might try learning LINQ. It could make this code: public TblUserCollection GetCollection() { TblUserCollection collection = new TblUserCollection(); collection.Query.Where(collection.Query.CompanyId == CompanyId); collection.Query.OrderBy(collection.Query.FullName, esOrderByDirection.Ascending); collection.Query.Load(); return collection; } alot more readable in my mind. A: The conventional approach would be to just let the exception propagate from your GetCollection method. You usually don't want to return what may be an incomplete collection. Then maybe in the top-level of your presentation tier, you could catch the exception and e.g. offer the user the opportunity to retry.
doc_4082
I think there's something wrong with my if logic here: if newip and originip == originip: print "there was an error, resetting..." else: print "You are now connected successfully" So I've tested the above, and when my VPN connects ok, it reports the new and the old IP address as different, then prints "there was an error, resetting" If it connects, and displays both newip and originip as the same, it also goes to print "there was an error, resetting..." I have not been able to get it to execute the else part of that above statement. Here's the entire python side of the program #!/usr/bin/env python import pexpect import sys import os import time import subprocess secdelay = int(raw_input("How many seconds before resetting? ")) p = subprocess.Popen(["./checkmyip.sh"], shell=False, stdout=subprocess.PIPE) originip = p.stdout.read() print 'Public IP Address is', originip child = pexpect.spawn ('./vpn.sh -arg1') child.expect ('') child.expect ('(?i)Enter Aut Username:') child.sendline ('myusername') child.expect ('(?i)Enter Auth Password:') child.sendline ('mypassword') print "Establishing connection..." time.sleep(10) p = subprocess.Popen(["./checkmyip.sh"], shell=False, stdout=subprocess.PIPE) newip = p.stdout.read() print "The New IP is ",newip print "the old IP was ", originip if newip and originip == originip: print "there was an error, resetting..." else: print "You are now connected successfully" print "sleeping for ",secdelay," seconds" time.sleep(secdelay) child.sendcontrol('c') if child.isalive(): child.sendcontrol('c') child.close() if child.isalive(): print 'Child did not exit gracefully.' else: print 'Child exited gracefully.' Finnaly, here is the code I added to my "checkmyip.sh" script. It's just a simple wget: #!/usr/bin/env bash wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//' So the script works fine, it's just this error-checking logic that is confusing me. Why my if x and y == x is not working tho, when x and y both enumerate different values in the print line directly above my if statement, I'm confused on. Any suggestions or help would be extremely appreciated. Thanks for reading! Thanks for the help everyone! The fixed code was this: if newip and originip == originip: was changed to if newip == originip: A: Yup, the condition originip == originip is always going to be True. Thus, if newip is not empty, the whole expression newip and originip == originip is also going to be True: >>> originip = 'foo' >>> originip == originip True >>> newip = '' >>> newip and originip == originip False >>> newip = 'bar' >>> newip and originip == originip True Did you mean: if newip and newip == originip: instead? A: Try this instead: if newip == originip: print "there was an error, resetting..." A: >if newip and originip == originip: You're testing the "boolean" value of newip then you are testing if originip is equal to itself, which is always true. You probably mean: if newip == originip:
doc_4083
Error: Can't resolve './src/resource/Original.svg' in 'C:\Users\User\IdeaProjects\demo\personal-blog\src\components\Sidebar' Why is this error happening? // this is component code <Link to={'/'}> <div className="logo"></div> </Link> // Problematic css file .Sidebar .logo { background: url("src/resource/Logo/Resizable Vector Files/Original.svg"); } A: I think in your Sidebar.js file ./src/resource/Original.svg is not imported correctly A: either you typed ./src/resource/Original.svg wrong or you didn't give background-image:url(); A: you can use JSS styling inside your component file instead of CSS. so you should code your component like below: import backgroundImg from './src/resource/Original.svg' const styles = { main: { backgroundImage: `url(${backgroundImg})` } } . . . <Link to={'/'}> <div style={styles.main}></div> </Link>
doc_4084
An example of before working in my system function builder() { jQuery.post('/cart/add.js', { items: [ { quantity: 1, id: 100 } ,{ quantity: 1, id: 200 } ] }); } document.getElementById('someLink').href = "/cart"; <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a id="someLink" onclick="builder()"><input type="submit" value="Click me" /></a> What I am trying to do is have the whole contents of items and everything within the square brackets be in a JS variable instead that I can later call there. A non-working example of how I'm trying to accomplish would look something like this: function builder() { var cartContents = "items: [{ quantity: 1, id: 100 } , { quantity: 1, id: 200 } ]"; jQuery.post('/cart/add.js', { cartContents; }); } document.getElementById('someLink').href = "/cart"; <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a id="someLink" onclick="builder()"><input type="submit" value="Click me" /></a> That line "cartContents;" in the post function is where I know I'm wrong and I can't seem to find the right way to declare that JQuery variable in a way that simply inserts the contents of the variable's value. Any advice is much appreciated. A: The problem is that you're assigning cartContents as a string variable. Instead just make it a normal object and it will work. See below for working example: function builder() { var cartContents = { items: [ { quantity: 1, id: 100 } , { quantity: 1, id: 200 } ] }; jQuery.post('/cart/add.js', cartContents); }
doc_4085
Simply, I have dataset like this : import pandas as pd pd.read_clipboard(sep='\s\s+') df3 = pd.DataFrame([[1,12,111], [1, 13,111], [1, 14,111]], columns=['user_id', 'product_id','session_id']) user_id product_id session_id 0 1 12 111 1 1 13 111 2 1 14 111 I want to transform that dataset to below form : user_id product_id1 product_id2 product_id3 session_id target_id 0 1 NaN 12.0 13 111 11 1 1 11.0 NaN 13 111 12 As you see target_id column is consist of removed item from each user's basket. After getting this dataset I want to do classification to predict this removed item
doc_4086
Right now, with View controller-based status bar appearance set to YES, and -(BOOL)prefersStatusBarHidden { return YES; } in my 'hidden status bar' ModalViewController, the upper half of my Navigation Item is cut off. http://i.stack.imgur.com/m2xc2.png Currently, the rest of the app's view's doesn't have a status bar. Suggestions?
doc_4087
The CSS of this page is stored in another file, and that file is currently static. What is the best way to switch the attribute left and right according to the locale? Is there a built in attribute in CSS for this problem? (I don't want to use JS, it feels too messy) I have: .elem{ left: 10px; bottom: 10px; position: absolute; } I want something like this: .elem{ right-or-left-according-to-html-dir: 10px; bottom: 10px; position: absolute; } Currently the only option I can think of is turning the file into a template also: .elem{ {{dir}}: 10px; bottom: 10px; position: absolute; } Is there a better way that will let me keep my CSS file static? A: How about adding the direction to your body element via a special class, then you can write according selectors: <body class="rtl"> and in the CSS: .rtl .myclass { text-align: right; } A: You say you're making the document rtl or ltr depending on locale. In that case you can use the :lang() selector to make certain parts of your document have styling depending on the locale. * *http://www.w3.org/wiki/CSS/Selectors/pseudo-classes/:lang *http://www.w3.org/TR/css3-selectors/#lang-pseudo If you want a little more support (IE7+) you could use the attribute selector selector[lang='en'] though that will only test the attribute on the specified selector. * *http://www.w3.org/TR/css3-selectors/#attribute-selectors If you specify the language in the html element (which you should, with lang="en" for example) you can just put the html selector in front of the class you want to apply in certain locales: .elem { margin: 0 10px 0 0; color: blue; } html[lang='en'] .elem { margin: 0 0 0 10px; } Even better, if you specified the dir attribute you can directly use that in css like so: .elem[dir='rtl'] { margin: 0 10px 0 0; } Please note that with a class on the body element you will always depend on that class always being there. But the dir and lang attribute can be specified on a more specific scope, like a single div, and still be used in the css along with styles for the 'other' reading directions. Edit Lastly, to gaze into the future, the CSS Selectors 'Level 4' will include a psuedo tag which will be able to filter on text directionality. Of course the specs are in development and adoption by browsers may take years before it is possible to reliably use it: http://dev.w3.org/csswg/selectors4/#dir-pseudo
doc_4088
# Bitbucket pipeline to build an image and upload it to AWS ECR image: atlassian/default-image:2 pipelines: branches: master: - step: caches: - docker services: - docker name: Build and Push deployment: Production script: - echo "Build Docker and Push to Registry" - docker build -t $AWS_ECR_REPOSITORY . - docker inspect $AWS_ECR_REPOSITORY - pipe: atlassian/aws-ecr-push-image:1.4.1 variables: AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION IMAGE_NAME: $AWS_ECR_REPOSITORY Now I want to create another bitbucket pipeline which can take that image from AWS ECR and deploy that application on AWS Elastic Beanstalk. I'm not sure how to do that.
doc_4089
As you would imagine there numerous drop drown fields in the list which I would like to use as a filter within the Powerapp, but being that these are "Complex" fields, they are non-delegatable. I'm lead to believe that I can avoid this by creating additional Columns in the SharePoint list that use a Flow that populates them with plain text based on the Drop-down selected. This is a bit of pain, so I'd like to limit the quantity of these helper columns as much as possible. Can anyone advise if a Powerapps Gallery will initially filter the results being returned using the delegateable functions first, and then perform the non-delegatable search functions on those items, or whether the inclusion of a non-delgatable search criteria means that the whole query is performed in a non-delegatable manner? i.e. Filter 3000 records down to 800 using delegatable search, then perform the additional filtering of those 800 on the app for the non-delegatable search criteria. I understand that it may be possible to do this via loading the initial filtered results into a collection within the app and potentially filtering that list, but have read some conflicting information as to the efficacy of this method, so not such if this is the route I should take. A: Delegation can be a challenge. Here are some methods for handling it: * *Users rarely need more than a few dozen records at any time in a mobile app. Try to use delegable queries to create a Collection locally. From there, its lightning fast. *If you MUST pull in all 3k+ of your records, here's my favorite hack. Collect chunks of your data source then combine into a single collection. *If you want the function to scale (and the user's wait time) you can determine the first and last ID to dynamically build a function. Good luck!
doc_4090
How do I add the math libraries on Ubuntu or include them when I run jq? jq -n 'pow(2,4)' returns jq: error: pow/1 is not defined at <top-level>, line 1: pow(2,4) jq: 1 compile error A: The error message gives it away: pow/1 is not defined […] huh, but you are calling it with 2 arguments – why does it try to call the unary function? Nope, you are not. jq uses semicolons to separate call arguments. commas separate the elements in a stream. jq -n 'pow(2;4)' This will call pow/2 which you are after. Then where do commas come into play? Consider: $ jq -n 'pow(2,3;4,5)' 16 # 2**4 or pow(2;4) 81 # 3**4 or pow(3;4) 32 # 2**5 or pow(2;5) 243 # 3**5 or pow(3;5)
doc_4091
I am getting everything correct but when I am trying to run the code I miss out the first two entries , I mean the first two rows. The code is below, The line which is not reading the entire file is highlighted. I would like some expert advice. I just started coding in python so I am not well versed entirely with it. ##fileformat=VCFv4.0 ##fileDate=20140901 ##source=dbSNP ##dbSNP_BUILD_ID=137 ##reference=hg19 #CHROM POS ID REF ALT QUAL FILTER INFO import sys text=open(sys.argv[1]).readlines() print text print "First print" text=filter(lambda x:x.split('\t')[31].strip()=='KEEP',text[2:]) print text print "################################################" text=map(lambda x:x.split('\t')[0]+'\t'+x.split('\t')[1]+'\t.\t'+x.split('\t')[2]+'\t'+x.split('\t')[3]+'\t.\tPASS\t.\n',text) print text file=open(sys.argv[1].replace('.txt','.vcf'),'w') file.write('##fileformat=VCFv4.0\n') file.write('##source=dbSNP') file.write('##dbSNP_BUILD_ID=137') file.write('##reference=hg19\n') file.write('#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n') for i in text: file.write(i) file.close() INPUT: chrM 152 T C T_S7998 N_S8980 0 DBSNP COVERED 1 1 1 282 36 0 163.60287 0.214008 0.02 11.666081 202 55 7221 1953 0 0 TT 14.748595 49 0 1786 0 KEEP chr9 311 T C T_S7998 N_S8980 0 NOVEL COVERED 0.993882 0.999919 0.993962 299 0 0 207.697923 1 0.02 1.854431 0 56 0 1810 1 116 CC -44.649001 0 12 0 390 KEEP chr13 440 C T T_S7998 N_S8980 0 NOVEL COVERED 1 1 1 503 7 0 4.130339 0.006696 0.02 4.124606 445 3 16048 135 0 0 CC 12.942762 40 0 1684 0 KEEP OUTPUT desired: ##fileformat=VCFv4.0 ##source=dbSNP##dbSNP_BUILD_ID=137##reference=hg19 #CHROM POS ID REF ALT QUAL FILTER INFO chrM 152 . T C . PASS . chr9 311 . T C . PASS . chr13 440 . C T . PASS . OUTPUT obtained: ##fileformat=VCFv4.0 ##source=dbSNP##dbSNP_BUILD_ID=137##reference=hg19 #CHROM POS ID REF ALT QUAL FILTER INFO chr13 440 . C T . PASS . I would like to have some help regarding how this error can be rectified. A: There are couple of issues with your code * *In the filter function you are passing text[2:]. I think you want to pass text to get all the rows. *In the last loop where you write to the .vcf file, you are closing the file inside the loop. You should first write all the values and then close the file outside the loop. So your code will look like (I removed all the prints): import sys text=open(sys.argv[1]).readlines() text=filter(lambda x:x.split('\t')[31].strip()=='KEEP',text) # Pass text text=map(lambda x:x.split('\t')[0]+'\t'+x.split('\t')[1]+'\t.\t'+x.split('\t')[2]+'\t'+x.split('\t')[3]+'\t.\tPASS\t.\n',text) file=open(sys.argv[1].replace('.txt','.vcf'),'w') file.write('##fileformat=VCFv4.0\n') file.write('##source=dbSNP') file.write('##dbSNP_BUILD_ID=137') file.write('##reference=hg19\n') file.write('#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n') for i in text: file.write(i) file.close() # close after writing all the values, in the end
doc_4092
Traceback (most recent call last): File "d:\Python\LCR_skema_opdater\202203-test\Skema\Moder\LCR_opdater_skema.py", line 31, in <module> cell2.value = cell1.value AttributeError: 'tuple' object has no attribute 'value' This is the script I wrote: import openpyxl import os #Current path path = os.path.dirname(os.path.abspath(__file__)) #Beregningsmodul navn Beregningsmodul_moder_navn = "Beregning COREP LCR - MODER - 202202.xlsx" #workbook_beregn path beregn_path = path + "\\" + Beregningsmodul_moder_navn workbook_beregn = openpyxl.load_workbook(beregn_path) #Skema 72 navn skema_72_navn ="C_72_00_a.xlsx" #skema path skema_72_path = path + "\\" + skema_72_navn workbook_skema_72 = openpyxl.load_workbook(skema_72_path) #Kopier til wb_72C = workbook_beregn["72C"]['E8':'G54'] #kopier fra C_72_00_a = workbook_skema_72["C_72_00_a"]['D9':'F55'] #Pair the rows for row1,row2 in zip(C_72_00_a, workbook_beregn): #within the row pair, pair the cells for cell1, cell2 in zip(row1,row2): #assign the value of cell 1 to the destination cell 2 for each row cell2.value = cell1.value #save document workbook_beregn.save('destination.xlsx') print("Finished") I hope you can point me in the right direction. #Update: I found a solution and ended up defining a function to make it easier to replicate in the future: #Copy from wb_72C = workbook_beregn['72C']['E8':'G54'] #Copy to C_72_00_a = workbook_skema_72['C_72_00_a']['D9':'F55'] #Define function def workbook_copy(copy_from,copy_to): #Pair the rows for row1,row2 in zip(copy_from, copy_to): #within the row pair, pair the cells for cell1, cell2 in zip(row1,row2): #assign the value of cell 1 to the destination cell 2 for each row cell2.value = cell1.value workbook_copy(C_72_00_a, wb_72C) A: When the iteration is run, the return object is a tuple (combination of all values in the cells of the given row) for e.g. ('A', '123', 'CD' , 125) will be result for a row with four columns for copying values from source cell to target cell, you will need to iterate over the coordinates of the cell (row address and column address) When you iterate over the rows, the code only understands the row and not each cell in the row. Hence the error, "AttributeError: 'tuple' object has no attribute 'value'" I hope this helps A: I found the issue I was iterating through the workbook instead of the tuple I had made. wb_72C = workbook_beregn['72C']['E8':'G54'] C_72_00_a = workbook_skema_72['C_72_00_a']['D9':'F55'] #Pair the rows for row1,row2 in zip(C_72_00_a, wb_72C): #within the row pair, pair the cells for cell1, cell2 in zip(row1,row2): #assign the value of cell 1 to the destination cell 2 for each row cell2.value = cell1.value So I changed this line from: for row1,row2 in zip(C_72_00_a, workbook_beregn): to this line: for row1,row2 in zip(C_72_00_a, wb_72C): I hope this someone else in the future.
doc_4093
<input value="5303" data-bind="checked: checkTest" type="checkbox" name="test" id="2"><span class="label-text"> TEST</span> $scope.checkTest= ko.observableArray(); How do I unselect the checkbox on this template by code? A: I have a checkbox which selects the value "5303" in a object By this you mean the value '5303' gets inserted into the observableArray checkTest, correct? To unselect the checkbox by code, update its value with an empty array: $scope.checkTest([]);
doc_4094
I'm getting groovyx.net.http.HttpResponseException: Not Found and want to see the logs from HTTPBuilder. I'm using Groovy 2.1.9 with groovyConsole. What I tried So I checked this blog post that says about adding log4j.xml to groovy.home/conf/. I did that, here's my file: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{ISO8601} %-5p %c{1} - %m%n" /> </layout> </appender> <category name="groovyx.net.http"> <priority value="DEBUG" /> </category> <!-- Use DEBUG to see basic request/response info; Use TRACE to see headers for HttpURLClient. --> <category name="groovyx.net.http.HttpURLClient"> <priority value="INFO" /> </category> <category name="org.apache.http"> <priority value="DEBUG" /> </category> <category name="org.apache.http.headers"> <priority value="DEBUG" /> </category> <category name="org.apache.http.wire"> <priority value="DEBUG" /> </category> <root> <priority value="INFO" /> <appender-ref ref="console" /> </root> </log4j:configuration> And here's my script that I'm running in the console: import groovyx.net.http.* import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager import javax.net.ssl.SSLContext import java.security.cert.X509Certificate import javax.net.ssl.TrustManager import java.security.SecureRandom import org.apache.http.conn.ssl.SSLSocketFactory import org.apache.http.conn.scheme.Scheme import org.apache.http.conn.scheme.SchemeRegistry import groovy.util.logging.* @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6') @Grab( 'log4j:log4j:1.2.16' ) @Log4j class WebserviceTest { static void main (String[] args) { def http = new HTTPBuilder('https://localhost:8443/project/service/') log.debug "http is instanceof ${http.getClass()}" //this is printed //=== SSL UNSECURE CERTIFICATE === def sslContext = SSLContext.getInstance("SSL") sslContext.init(null, [ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() {null} public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } ] as TrustManager[], new SecureRandom()) def sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) def httpsScheme = new Scheme("https", sf, 4483) http.client.connectionManager.schemeRegistry.register( httpsScheme ) //================================ //the next line throws the exeption... http.post(path: '/method', contentType: ContentType.JSON, query: [param: '1000']) { resp, reader -> println "resp is instanceof ${resp.getClass()}" println "and reader is instanceof ${reder.getClass()}" println "response status: ${resp.statusLine}" println 'Headers: -----------' resp.headers.each { h -> println " ${h.name} : ${h.value}" } println 'Response data: -----' System.out << reader println '\n--------------------' } } } EDIT: my HttpResponseException is solved, I had a / unnecessary in the request, but still no builder logs appearing. A: HTTPBuilder uses commons-logging, so you have to bridge the output from commons-logging to log4j. Unfortunately log4j 1.2 doesn't support this out of the box. So I simplified your example and switched to SLF4J, which is a 'Simple Logging Facade for Java'. Under the hood the following config still uses log4j, so you still need your log4j.xml in place (groovy.home/conf/). For a detailled explanation see Bridging legacy APIs. @Grapes([ @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6'), // This brings in slf4j, log4j12 (as dependancies) and the bridge to log4j @Grab(group='org.slf4j', module='slf4j-log4j12', version='1.7.7'), // This brings in the bridge to commons-logging @Grab(group='org.slf4j', module='jcl-over-slf4j', version='1.7.7') ]) import org.slf4j.LoggerFactory import groovyx.net.http.* // get a logger for the script def log = LoggerFactory.getLogger('script') def http = new HTTPBuilder('http://www.google.com') log.info "http is instanceof ${http.getClass()}" //this is printed http.get( path : '/search', contentType : ContentType.TEXT, query : [q:'Groovy'] ) { resp, reader -> log.debug "response status: ${resp.statusLine}" println 'Done' } A: Try this Import this import ch.qos.logback.classic.Level import ch.qos.logback.classic.Logger And Set Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) rootLogger.setLevel(mLevel) You can set this before the HTTP builder gets called
doc_4095
ERROR: type should be string, got "https://ibb.co/dUpFJF\n\n\n@charset \"utf-8\";\r\n\r\n/* CSS Document */\r\n\r\nbody {\r\n font-family: 'Droid Sans', sans-serif;\r\n margin-top: 0px;\r\n margin-left: 0px;\r\n margin-right: 0px;\r\n margin-bottom: 0px;\r\n min-height: 100%;\r\n}\r\n\r\n.div_top1 {\r\n height: 30px;\r\n margin: 0 auto;\r\n width: 100%;\r\n border-bottom: 1px solid #FFF;\r\n background-color: #2d2d2d;\r\n}\r\n\r\n.div_top2 {\r\n height: 150px;\r\n width: 100%;\r\n background-color: #072135;\r\n}\r\n\r\n.main_container {\r\n width: 100%;\r\n margin: 0 auto;\r\n background-color: #FFF;\r\n overflow: auto;\r\n min-height: 100%;\r\n display: inline-block;\r\n}\r\n\r\n.container_right {\r\n height: 100%;\r\n padding-left: 20px;\r\n margin: 0 auto;\r\n}\r\n\r\n.container_left {\r\n float: left;\r\n text-align: left;\r\n border-right: 2px solid #5a5c5d;\r\n border-bottom: 1px solid #5a5c5d;\r\n height: 100%;\r\n overflow: hidden;\r\n}\r\n\r\n.bk {\r\n border-top: 4px solid #da6161;\r\n display: table;\r\n height: 200px;\r\n margin: 0 auto;\r\n margin-top: 30px;\r\n padding: 8px;\r\n}\r\n\r\n.icon {\r\n float: left;\r\n display: block;\r\n}\r\n\r\n.icon-bar {\r\n width: 70px;\r\n /* Set a specific width */\r\n background-color: #FFF;\r\n /* Dark-grey background */\r\n height: 100%;\r\n}\r\n\r\n.icon-bar a {\r\n display: block;\r\n /* Make the links appear below each other instead of side-by-side */\r\n text-align: center;\r\n /* Center-align text */\r\n padding: 16px;\r\n /* Add some padding */\r\n transition: all 0.3s ease;\r\n /* Add transition for hover effects */\r\n color: black;\r\n /* White text color */\r\n font-size: 27px;\r\n /* Increased font-size */\r\n height: 100%;\r\n}\r\n\r\n.icon-bar a:hover {\r\n background-color: #5a5c5d;\r\n /* Add a hover color */\r\n}\r\n\r\n.active {\r\n background-color: #818384;\r\n /* Add an active/current color */\r\n}\r\n\r\n<style>\r\n/* Tooltip container */\r\n\r\n.tooltip {\r\n position: relative;\r\n display: inline-block;\r\n border-bottom: 1px dotted black;\r\n /* If you want dots under the hoverable text */\r\n}\r\n\r\n\r\n/* Tooltip text */\r\n\r\n.tooltip .tooltiptext {\r\n visibility: hidden;\r\n width: auto;\r\n background-color: #da6161;\r\n color: #fff;\r\n text-align: center;\r\n padding: 5px;\r\n border-radius: 6px;\r\n font-size: 20px;\r\n /* Position the tooltip text - see examples below! */\r\n position: absolute;\r\n z-index: 1;\r\n margin-left: 36px;\r\n}\r\n\r\n\r\n/* Show the tooltip text when you mouse over the tooltip container */\r\n\r\n.tooltip:hover .tooltiptext {\r\n visibility: visible;\r\n}\r\n\r\n.foot {\r\n background-color: #2d2d2d;\r\n position: absolute;\r\n color: #FFF;\r\n text-align: center;\r\n left: 0;\r\n bottom: 0;\r\n height: 35px;\r\n width: 100%;\r\n border-top: 3px solid #9c9d9e;\r\n padding-top: 3px;\r\n}\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\r\n\r\n<body>\r\n <div class=\"div_top2\"> </div>\r\n <div class=\"main_container\">\r\n <div class=\"container_left\">\r\n <div class=\"icon_menu\">\r\n <div class=\"icon-bar\">\r\n <a class=\"active tooltip\" href=\"#\">\r\n <span class=\"tooltiptext\">Home</span>\r\n <i class=\"fa fa-home\"></i>\r\n\r\n </a>\r\n <a class=\"tooltip\" href=\"#\">\r\n <span class=\"tooltiptext\">My Story</span>\r\n <i class=\"fa fa-black-tie\"></i>\r\n </a>\r\n <a href=\"#\" class=\"tooltip\">\r\n <span class=\"tooltiptext\">Companies</span>\r\n <i class=\"fa fa-building\"></i>\r\n </a>\r\n <a href=\"#\" class=\"tooltip\">\r\n <span class=\"tooltiptext\">Blog</span>\r\n <i class=\"fa fa-paper-plane\"></i>\r\n </a>\r\n\r\n\r\n <a href=\"#\" class=\"tooltip\">\r\n <span class=\"tooltiptext\">Ask Me Anything</span>\r\n <i class=\"fa fa-quora\"></i>\r\n\r\n </a>\r\n\r\n\r\n <a href=\"#\" class=\"tooltip\">\r\n <span class=\"tooltiptext\">Contact</span>\r\n <i class=\"fa fa-address-card\"></i>\r\n\r\n </a>\r\n\r\n\r\n\r\n\r\n\r\n </div>\r\n </div>\r\n\r\n\r\n </div>\r\n\r\n <div class=\"container_right\">\r\n\r\n <div class=\"bk\"></div>\r\n\r\n </div>\r\n\r\n\r\n\r\n </div>\r\n\r\n <div class=\"foot\">\r\n Copyright 2017\r\n\r\n </div>\n\n\n\nA: When using floats you disturb the normal document flow. Change the definition of .foot as follows:\n\n\n@charset \"utf-8\";\r\n\r\n/* CSS Document */\r\n\r\nbody {\r\n font-family: 'Droid Sans', sans-serif;\r\n margin-top: 0px;\r\n margin-left: 0px;\r\n margin-right: 0px;\r\n margin-bottom: 0px;\r\n min-height: 100%;\r\n}\r\n\r\n.div_top1 {\r\n height: 30px;\r\n margin: 0 auto;\r\n width: 100%;\r\n border-bottom: 1px solid #FFF;\r\n background-color: #2d2d2d;\r\n}\r\n\r\n.div_top2 {\r\n height: 150px;\r\n width: 100%;\r\n background-color: #072135;\r\n}\r\n\r\n.main_container {\r\n width: 100%;\r\n margin: 0 auto;\r\n background-color: #FFF;\r\n overflow: auto;\r\n min-height: 100%;\r\n display: inline-block;\r\n}\r\n\r\n.container_right {\r\n height: 100%;\r\n padding-left: 20px;\r\n margin: 0 auto;\r\n}\r\n\r\n.container_left {\r\n float: left;\r\n text-align: left;\r\n border-right: 2px solid #5a5c5d;\r\n border-bottom: 1px solid #5a5c5d;\r\n height: 100%;\r\n overflow: hidden;\r\n}\r\n\r\n.bk {\r\n border-top: 4px solid #da6161;\r\n display: table;\r\n height: 200px;\r\n margin: 0 auto;\r\n margin-top: 30px;\r\n padding: 8px;\r\n}\r\n\r\n.icon {\r\n float: left;\r\n display: block;\r\n}\r\n\r\n.icon-bar {\r\n width: 70px;\r\n /* Set a specific width */\r\n background-color: #FFF;\r\n /* Dark-grey background */\r\n height: 100%;\r\n}\r\n\r\n.icon-bar a {\r\n display: block;\r\n /* Make the links appear below each other instead of side-by-side */\r\n text-align: center;\r\n /* Center-align text */\r\n padding: 16px;\r\n /* Add some padding */\r\n transition: all 0.3s ease;\r\n /* Add transition for hover effects */\r\n color: black;\r\n /* White text color */\r\n font-size: 27px;\r\n /* Increased font-size */\r\n height: 100%;\r\n}\r\n\r\n.icon-bar a:hover {\r\n background-color: #5a5c5d;\r\n /* Add a hover color */\r\n}\r\n\r\n.active {\r\n background-color: #818384;\r\n /* Add an active/current color */\r\n}\r\n\r\n<style>\r\n/* Tooltip container */\r\n\r\n.tooltip {\r\n position: relative;\r\n display: inline-block;\r\n border-bottom: 1px dotted black;\r\n /* If you want dots under the hoverable text */\r\n}\r\n\r\n\r\n/* Tooltip text */\r\n\r\n.tooltip .tooltiptext {\r\n visibility: hidden;\r\n width: auto;\r\n background-color: #da6161;\r\n color: #fff;\r\n text-align: center;\r\n padding: 5px;\r\n border-radius: 6px;\r\n font-size: 20px;\r\n /* Position the tooltip text - see examples below! */\r\n position: absolute;\r\n z-index: 1;\r\n margin-left: 36px;\r\n}\r\n\r\n\r\n/* Show the tooltip text when you mouse over the tooltip container */\r\n\r\n.tooltip:hover .tooltiptext {\r\n visibility: visible;\r\n}\r\n\r\n.foot {\r\n background-color: #2d2d2d;\r\n color: #FFF;\r\n text-align: center;\r\n float: left;\r\n height: 35px;\r\n width: 100%;\r\n border-top: 3px solid #9c9d9e;\r\n padding-top: 3px;\r\n}\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\r\n\r\n<body>\r\n <div class=\"div_top2\"> </div>\r\n <div class=\"main_container\">\r\n <div class=\"container_left\">\r\n <div class=\"icon_menu\">\r\n <div class=\"icon-bar\">\r\n <a class=\"active tooltip\" href=\"#\">\r\n <span class=\"tooltiptext\">Home</span>\r\n <i class=\"fa fa-home\"></i>\r\n\r\n </a>\r\n <a class=\"tooltip\" href=\"#\">\r\n <span class=\"tooltiptext\">My Story</span>\r\n <i class=\"fa fa-black-tie\"></i>\r\n </a>\r\n <a href=\"#\" class=\"tooltip\">\r\n <span class=\"tooltiptext\">Companies</span>\r\n <i class=\"fa fa-building\"></i>\r\n </a>\r\n <a href=\"#\" class=\"tooltip\">\r\n <span class=\"tooltiptext\">Blog</span>\r\n <i class=\"fa fa-paper-plane\"></i>\r\n </a>\r\n\r\n\r\n <a href=\"#\" class=\"tooltip\">\r\n <span class=\"tooltiptext\">Ask Me Anything</span>\r\n <i class=\"fa fa-quora\"></i>\r\n\r\n </a>\r\n\r\n\r\n <a href=\"#\" class=\"tooltip\">\r\n <span class=\"tooltiptext\">Contact</span>\r\n <i class=\"fa fa-address-card\"></i>\r\n\r\n </a>\r\n\r\n\r\n\r\n\r\n\r\n </div>\r\n </div>\r\n\r\n\r\n </div>\r\n\r\n <div class=\"container_right\">\r\n\r\n <div class=\"bk\"></div>\r\n\r\n </div>\r\n\r\n\r\n\r\n </div>\r\n\r\n <div class=\"foot\">\r\n Copyright 2017\r\n\r\n </div>\n\n\n\nA: you made the footer element absolutely positioned relative to parent(body tag).\ntry wrapping your code in a after element\nhtml\n<body>\n<div class=\"wrapper\">\n<!-- your code here -->\n</div>\n</body> \n\ncss\n.wrapper\n{\nposition:relative;\n}\n\nhope this works...\n"
doc_4096
Should I use an Oracle trigger to notify WCF when a change is made to the table or should I use WCF to continually poll the DB table for changes? Also, how can get I WCF to communicate with Websphere MQ 5.3? I've researched enough to see that the newer version of Websphere MQ 7.1 comes with a custom channel for WCF but I don't know how to get WCF to work with 5.3. I've been told that we don't use Microsoft Biztalk or Oracle Database Change Notification(ODBN). Should I recommend to my supervisor that we upgrade Websphere MQ to 7.1 and also use Biztalk or ODBN? I am new to using WCF, Oracle, and Websphere MQ and am unsure which direction to take. Any links or resources to help me figure this out would be appreciated. A: MQ 5.3 is out of support. So it is not recommended to use an out of support product. As you found WCF support is not available in MQ v5.3. WCF support is available from MQ v7.0.1. So you have to upgrade to at least MQ v7.0.1. MQ WCF provides a custom channel using which web services can be hosted on MQ and clients can call those web services using the custom channel. If your intention is to use MQ WCF for just putting messages into a queue and not develop any web service, then it would be better to look at either MQ .NET classes or XMS .NET classes. MQ .NET classes provide OO API for messaging with MQ queue/topic whereas XMS .NET provides a JMS like API. My 2 cents on other part: It is better to receive notifications from Oracle DB when a change happens than polling. There could be way in Oracle where you could register a callback or listener that gets called when change occurs to a table.
doc_4097
I am new so don't know how to configure the routes. Rails.application.routes.draw do devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) devise_for :users get 'activities/index' get 'projects/index' get 'activities/new' resources :activities # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'dashboard#index' end First i need to stop redirecting to users/sign_in on page load. If i give localhost:3000/admin in browser path and don't redirect to user dashboard when logged in as admin.Thanks.
doc_4098
I think that the jenkins handle this in order to maintain security , but please someone let me know how this works .Since i dont have much knowledge on devops side. A: great question. in our company, we add another file .env.template will contain placeholders and also it will be very similar to the .env file so anyone who wants to deploy or set up his own .env could what keys he wants.
doc_4099
How can I declare a TypeScript type that will be compatible with this JavaScript array? interface A { foo: Foo, bar: Bar, } interface B { baz: Baz } interface Bat { // getArr(): [A, B, B, B], // tuple type puts types at specific indexes // but only supports a fixed number of elements // getArr(): Array<A | B>, // array type notation allows arbitrary number // of elements but doesn't require them to be // in specific positions } Edit: To clarify further, I am experimenting with using external TypeScript declarations with vanilla JavaScript code to identify issues in existing JavaScript code. I understand the representation may be unwise; if more wisdom had been employed in the creation of the original JavaScript code I would not have set out on this adventure. A: It is not possible to declare such in TypeScript's type system: arrays must have a homogenous type1 In this case the array (Array<c'>) is of a homogenous c', where c' = A | B. Of course, if the data-structure could be decomposed, then some additional/complex encoding might be "suitable", eg. [ A, Array<B> ] 1 I'm not aware of any programming language type system that allows such a restriction - for an unbound sequence - based on arbitrary pattern rules.