id
stringlengths
3
6
prompt
stringlengths
100
55.1k
response_j
stringlengths
30
18.4k
133169
I'm using [Restangular](https://github.com/mgonto/restangular) in my project and earlier this code worked well for retrieving array of objects: ``` var params = {name: "Stack", surname: "Overflow"} var service = Restangular.all('users') service.getList(params) ``` Response from server was just an array of objects: ``` [ {...}, {...} ] ``` But now I added pagination, and my response now contains not an array, but an object which includes array: ``` { totalCount: 500, data: [ {...}, {...} ] } ``` Also I changed `service.getList(params)` to `service.get(params)` (because `getList` expects only arrays). And after this changes my GET parameters are not stringified, i.e. I see in debugger request like this: `users/[object%20Object]` but earlier (when using `getList` method) it worked as I expected: `users?name=Stack&surname=Overflow` What is the problem here?
I was able to solve it using this: ``` var params = {name: "Stack", surname: "Overflow"} var service = Restangular.all('users') service.customGET("", params) // first parameter is required, so just provide empty string ```
133282
I am looking at this method in vb.net and I am quite knew to vb.net. I am trying to understand why integer "[to]" and "[step] "is defined in square brackets ? Can some one please explain this to me. Why can these be defined just To/Step. I have attached the code below. Thanks in advance. ``` ''' <summary> ''' Write to runtime output with loop information ''' Expected use when loop counter is incremented ''' </summary> Public Sub WriteToRuntimeOutput(counter As Integer, [to] As Integer, [step] As Integer) Dim message As New StringBuilder message.AppendFormat("Loop counter incremented. Loop {0}/{1}", counter, [to]) If loopStep <> 1 Then message.AppendFormat(" Step {0}", [step]) End If message.Append(".") return message.ToString() End Sub ```
Square brackets are used to create a variable that has the same name as a keyword. For example Dim [Integer] As Integer
133394
I am working on a simple program to just draw circles around some fixed points using the Python turtle package; however, I wanted to make it somewhat like a heat map where the colors get "cooler" as they get farther from the original point. My idea was to take the base white color, #FFFFFF, and subtract a percentage based from that on the distance away. I assumed hex color codes worked by getting lower in its hex value as the color gets "cooler", but I have now read that the first two mean its red value, the second its green, and the last its blue. How would I go around implementing a heat map the way I want it to work? I'm confident the distances are correct, I just think I'm using the color codes in the wrong way. The function I wrote to do the color calculation: ``` def findColor(dist): base = "FFFFFF" num = int(base, 16) percent = dist/800 #800 is the max distance away newNum = (num - (num*percent)) color = hex(int(newNum)) return color ``` The resulting map I get is: ![circle heat map](https://i.stack.imgur.com/D5Xav.jpg) With Ignacio Vazquez-Abrams' help about [HSV](http://en.wikipedia.org/wiki/HSL_and_HSV), I've got it looking like this :) : ![Updated color algorithm](https://i.stack.imgur.com/UtP8E.jpg)
You want to use [HSV](http://en.wikipedia.org/wiki/HSL_and_HSV) instead of RGB for the colors; slide across the hue dimension for your distances. [`colorsys`](http://docs.python.org/library/colorsys.html) can help.
133438
Here's [an example](https://plnkr.co/edit/BBKvCsdmTUcLavoxmjqH?p=preview) that introduces both regular Materialize `select` and Angular Materialize component: ``` @Component({ selector: 'my-app', styles: [` .select-wrapper { background-color: red; } `], template: ` <div class="row"> <div class="col s6"> <select materialize="material_select"> <option>...</option> </select> </div> <div class="col s6"> <select class="non-angular-materialize"> <option>...</option> </select> </div> </div> `, }) export class App { ngOnInit() { $('.non-angular-materialize').material_select(); } } ``` Styles are not applied. Although [same example](https://plnkr.co/edit/rLHDkg9vmWsNLPIGoLAU?p=preview) works with `/deep/`, this defies the purpose of components: ``` :host /deep/ .select-wrapper { background-color: red; } ``` Why does this happen? Is it possible to keep CSS encapsulation and avoid `/deep/` when styling the elements of component template? Is this problem specific to Materialize?
`ViewEncapsulation.Emulated` is used by default. To emulated css encapsulation angular addes some attributes to all elements within template. For example, the following template ``` <div class="col s6"> <select materialize="material_select"> <option>...</option> </select> </div> ``` becames ``` <div _ngcontent-c0="" class="col s6"> <select _ngcontent-c0="" materialize="material_select"> <option _ngcontent-c0="">...</option> </select> </div> ``` where `c0` is unique id of your component. And besides overwriting template angular also create specific css selectors from `styles|styleUrls` content. So ``` .select-wrapper { background-color: red; } ``` becames ``` .select-wrapper[_ngcontent-c0] { background-color: red; } ``` Eventually the CSS is not applied because your dynamically added HTML(after running plugin) doesn't have the attributes `_ngcontent-c0` applied Using the "shadow piercing" CSS combinators or having styles outside of `styles|styleUrls` properties should work around it.
133598
I have been trying to work with Programming Erlang , Version 2 ( Joe Armstrong's book). I am trying to solve the first problem in the Chap 13. As a solution to the problem - I came up with this - ``` -module(errorhandle1). -export([my_spawn/3,loop/1,test_func/0]). my_spawn(Mod,Fun,Args) -> %SpawnedPidRef = myspawn_helper(Mod,Fun,Args), %spawn(?MODULE , loop , [myspawn_helper(Mod,Fun,Args)]). spawn(fun() -> loop(myspawn_helper(Mod,Fun,Args)) end). myspawn_helper(Mod,Fun,Args) -> statistics(wall_clock), spawn_monitor(Mod,Fun,Args). loop({SpPid,SpRef}) -> io:format("Created Pid is : ~p~n",[SpPid]), receive {makeError,Msg} -> SpPid ! Msg, loop({SpPid,SpRef}); {'DOWN',SpRef, process,SpPid,Why} -> {_, Time1} = statistics(wall_clock), io:format("Down"), io:format("Process spawn time = ~p microsecond ~n",[Time1]) end. test_func() -> receive X -> list_to_atom(X) end. ``` The above code works and produces the desired output (first step is to solve the problem). Then I commented the line and came up with the following program , which is exactly same as the above one but , I use spawn/3 function instead of a spawn/1 and I dont seem to get the desired output. ``` -module(errorhandle1). -export([my_spawn/3,loop/1,test_func/0]). my_spawn(Mod,Fun,Args) -> %SpawnedPidRef = myspawn_helper(Mod,Fun,Args), spawn(?MODULE , loop , [myspawn_helper(Mod,Fun,Args)]). %spawn(fun() -> loop(myspawn_helper(Mod,Fun,Args)) end). myspawn_helper(Mod,Fun,Args) -> statistics(wall_clock), spawn_monitor(Mod,Fun,Args). loop({SpPid,SpRef}) -> io:format("Created Pid is : ~p~n",[SpPid]), receive {makeError,Msg} -> SpPid ! Msg, loop({SpPid,SpRef}); {'DOWN',SpRef, process,SpPid,Why} -> {_, Time1} = statistics(wall_clock), io:format("Down"), io:format("Process spawn time = ~p microsecond ~n",[Time1]) end. test_func() -> receive X -> list_to_atom(X) end. ``` Steps to execute the above module: c(errorhandle1). Pid = errorhandle1:my\_spawn(errorhandle1,test\_func,[]). Pid ! {makeError,test}. Can some please help me with my understanding of the usage of spawn/3 and spawn/1 ? Thanks, Sathish.
``` spawn(fun() -> loop(myspawn_helper(Mod,Fun,Args)) end). ``` is not an equivalent of ``` spawn(?MODULE , loop , [myspawn_helper(Mod,Fun,Args)]). ``` in the second case `[myspawn_helper(Mod,Fun,Args)]` is a parameter of function `spawn/3`. The value of a parameter is evaluated before a function call. It means the call `myspawn_helper(Mod,Fun,Args)` is made before the call to the `spawn/3` outside of a new process in the original one. You can see it as this code ``` SpawnedPidRef = myspawn_helper(Mod,Fun,Args), spawn(?MODULE , loop , [SpawnedPidRef]). ``` the equivalent with `spawn/1` would look like ``` SpawnedPidRef = myspawn_helper(Mod,Fun,Args), spawn(fun() -> loop(SpawnedPidRef) end). ``` Now you can see the difference. Only `loop(SpawnedPidRef)` is actually done inside a new process. But in your first version you perform `loop(myspawn_helper(Mod,Fun,Args))` in a new process. You can see it like ``` spawn(fun() -> SpawnedPidRef = myspawn_helper(Mod,Fun,Args), loop(SpawnedPidRef) end). ``` which is very different code. (See the last two blocks. The last one is you first version and other one is your second version.)
133621
Anybody knows how to convert this 2 dark / light theme "flatbutton" to one "raisedbutton" to switch the dark and light theme ? Dark / light theme code : ``` child: FlatButton( onPressed: () { Magazin.of(context).setBrightness(Brightness.dark); }, child: Text('DARK MODE', style: TextStyle(color: isDark ? Colors.black : Colors.white, fontFamily: "SampleFont", fontSize: 13.0)), ), child: FlatButton( onPressed: () { Magazin.of(context).setBrightness(Brightness.light); }, child: Text('LIGHT MODE', style: TextStyle(color: isDark ? Colors.black : Colors.white, fontFamily: "SampleFont", fontSize: 13.0)), ``` Raisedbutton sample code : ( [Flutter - How to convert "Switch" to "raised button" ( Push-Notifications )?](https://stackoverflow.com/questions/66287855/flutter-how-to-convert-switch-to-raised-button-push-notifications) ) ``` bool _enabled = false; // [...] RaisedButton( color: _enabled ? Colors.green : Colors.red, onPressed: () { setState(() { }); }, child: Text(_enabled? "On" : "Off")), ``` Enclosed a code that of course does not work , but should represent what I want so that it is easier to understand .. ``` RaisedButton( color: _light ? Colors.white : Colors.black, onPressed: () { setState(() { Magazin.of(context).setBrightness(Brightness.light); Magazin.of(context).setBrightness(Brightness.dark); }); }, child: Text(_light? "LIGHT THEME" : "DARK THEME")), style: TextStyle( fontFamily: "SampleFont", color: isDark ? Colors.green : Colors.red, fontSize: 35.0, ```
You cannot directly generate a lock file based on an import map yet. But you can pass the entry file of your program along with the import map to generate a lock file. Here's an example. `log.ts`: ```js import { green } from "colors"; console.log(`Status: ${green("OK")}`); ``` `deps.json` (import map): ```json { "imports": { "colors": "https://deno.land/std@0.88.0/fmt/colors.ts" } } ``` Now run the following command to generate a lock file. ```sh deno cache --import-map=deps.json --unstable --lock=lock.json --lock-write log.ts ``` The content of `lock.json` might look like below. ```json { "https://deno.land/std@0.88.0/fmt/colors.ts": "db22b314a2ae9430ae7460ce005e0a7130e23ae1c999157e3bb77cf55800f7e4" } ```
133972
Below is the code which i use in my edit text to take value only within a certain range ``` EditText.setFilters(new InputFilter[]{ new InputFilterMinMax(Min, Max)}); ``` this is my fuction: ``` public class InputFilterMinMax implements InputFilter { private int min, max; public InputFilterMinMax(int min, int max) { this.min = min; this.max = max; } public InputFilterMinMax(String min, String max) { this.min = Integer.parseInt(min); this.max = Integer.parseInt(max); } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { int input = 0; try { input = Integer.parseInt(dest.toString() + source.toString()); if (isInRange(min, max, input)) return null; } catch (NumberFormatException nfe) { } return ""; } private boolean isInRange(int a, int b, int c) { return b > a ? c >= a && c <= b : c >= b && c <= a; } } ``` This code works when min is 1 and max is 10, but it is not working when min is 20 and max is 30 please help,thanks in advance
You can do this with FrameLayout and for circle background you need to create a shape drawable file. Refer my answer here. ``` <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/round_shape" android:clickable="true" android:focusable="true" android:visibility="visible" android:foreground="?android:attr/selectableItemBackground" android:padding="4dp"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_star_border_black_24dp"/> </FrameLayout> ``` **round\_shape.xml** add this file in drawable folder ``` <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <gradient android:angle="270" android:startColor="@color/profile_grey" android:endColor="@color/profile_grey"/> </shape> ```
133987
I am trying to add a column to my table that increments in steps of four which would look like this: ``` 1 1 1 1 2 2 2 2 3 3 3 3 etc. ``` I have been reading about CREATE SEQUENCE, but that does not seem to be what I need. Does anyone have any suggestions how best to do this?
You could use `row_number()` and integer division: ``` select t.*, (3 + row_number() over(order by id)) / 4 rn from mytable t ``` This assumes that you have an ordering column called `id`. I would not actually recommend storing this derived information. You can compute it on the fly, or put in a view.
134452
I am working on a gesture recognition project. There is a C program that captures the gestures from video input and write them to the file. Now, I have an image viewer written in Python - GTK. It switches to the next or previous window according to gestures. This continuous file read and application update is defined as follows: ``` def ai(self): if self.mtime!=os.stat("input.txt").st_mtime: self.mtime=os.stat("input.txt").st_mtime inp=open("input.txt", "r"); line=inp.read() if len(line)!=0: line=line[0:len(line)-1] for x in line.split(' '): y=x.split('-') if(y[1]=="R"): self.next() print "Move Right" elif(y[1]=="L"): self.prev() print "Move Left" time.sleep(1) print "WakeUp" self.ai() ``` Now if I comment out the recursive call here, then application works after reading present file and updating images. Of course, then it doesn't update afterwards. But if I uncomment the recursive call, then the console keeps on working but image-viewer application stops responding. Is there any way to perform this function? Any event where i could bind this `ai()` function that could check for file updates every time that event is fired... Any help would be appreciated.
Not sure if I understand you correctly, but I would expect what you want to do is to **schedule a call to `ai()` in your main GTK loop**, so that your program checks if there is input on a regular base. If this is what you want you have two choices: scheduling the call periodically or schedule the call for when the program is idle (it is not doing anything else). Your code should look something like: ``` gobject.idle_add(callback, ...) #execute callback when idle gobject.timeout_add(interval, callback, ...) #execute callback every interval millisecs ``` The documentation should be [here](http://www.pygtk.org/pygtk2reference/gobject-functions.html) but presently there is a server error. Here are the relevant passages: > > The **`gobject.idle_add()`** function adds a function (specified by callback) to be called whenever there are no higher priority events pending to the default main loop. The function is given the default idle priority, gobject.PRIORITY\_DEFAULT\_IDLE. Additional arguments to pass to callback can be specified after callback. The idle priority can be specified as a keyword-value pair with the keyword "priority". If callback returns FALSE it is automatically removed from the list of event sources and will not be called again. > > > The **`gobject.timeout_add()`** function sets a function (specified by callback) to be called at regular intervals (specified by interval, with the default priority, gobject.PRIORITY\_DEFAULT. Additional arguments to pass to callback can be specified after callback. The idle priority may be specified as a keyword-value pair with the keyword "priority". > > > A catch: you have your callbacks to return `True` if you want to keep them in the scheduler, failing to do so will make them execute only once. HTH!
136218
I have something like this ``` edgesList = {{1, 3}, {1, 5}, {2, 1}, {2, 6}, {5, 2}, {5, 6}, {6, 1}, {6, 4}} ``` And I need something like this as output. ``` {Subscript[x, 1 \[RightArrow] 3] + Subscript[x, 1 \[RightArrow] 5] - Subscript[x, 2 \[RightArrow] 1] - Subscript[x, 6 \[RightArrow] 1], Subscript[x, 2 \[RightArrow] 1] + Subscript[x, 2 \[RightArrow] 6] - Subscript[x, 5 \[RightArrow] 2], -Subscript[x, 1 \[RightArrow] 3], -Subscript[x, 6 \[RightArrow] 4], -Subscript[x, 1 \[RightArrow] 5] + Subscript[x, 5 \[RightArrow] 2] + Subscript[x, 5 \[RightArrow] 6], -Subscript[x, 2 \[RightArrow] 6] - Subscript[x, 5 \[RightArrow] 6] + Subscript[x, 6 \[RightArrow] 1] + Subscript[x, 6 \[RightArrow] 4]} ``` I have accomplished this in procedural way, but I'm curious how to make it functional. ``` equations = Array[0 &, nVertexes]; For[i = 1, i <= nEdges, i++, equations[[edgesList[[i, 1]]]] = equations[[edgesList[[i, 1]]]] + Subscript[x, edgesList[[i, 1]] \[RightArrow] edgesList[[i, 2]]]; equations[[edgesList[[i, 2]]]] = equations[[edgesList[[i, 2]]]] - Subscript[x, edgesList[[i, 1]] \[RightArrow] edgesList[[i, 2]]];]; ```
``` Clear[x] equations = Array[0 &, 6]; edgesList = {{1, 3}, {1, 5}, {2, 1}, {2, 6}, {5, 2}, {5, 6}, {6, 1}, {6, 4}}; Fold[With[{i = First@#2, j = Last@#2}, ReplacePart[#1, {i -> #1[[i]] + Subscript[x, i \[RightArrow] j], j -> #1[[j]] - Subscript[x, i \[RightArrow] j]}]] &, equations, edgesList] ```
136295
I am an engineering student who loves physics but didn't quite enjoy chemistry. **a.** When I was in high school chemistry to me was something not as inspiring as physics but in which I couldn't solve problems well. Things looked no more than the arithmetics, but I got the answers wrong. **b.** Reading university chemistry textbooks (e.g. Oxtoby, Principles of Modern Chemistry 7E) I thought it was more of the physics behind the chemical objects and their reactions. Like quantum mechanics, electrodynamics, thermodynamics, statistical mechanics, ... they are just called differently - quantum chemistry, thermochemistry, chemical kinetics. **c.** So I question the significance of existence of chemistry. **No offence, it's a pure curiosity.** I now believe that all fields of study must be respected, and I want to take a step to do so by understanding the true meaning of chemistry. **Q1.** Why isn't chemistry as *science-looking* as other natural sciences? **Q2.** Why isn't chemistry a mere branch of physics? (Why is it distinguishable?) **Q3.** So what do chemists research? **Q4.** Please give me any important insight about chemistry as a discipline. Nowadays, I am very interested in chemistry, and want to learn it again at a broader viewpoint, with the proper philosophy of appreciating it. Could any chemist help. ***Edited 1**. I guess many people dislike and downvoted this post simply because I proposed a view (kind of) against chemistry. I will not delete the post - it is definitely worth leaving it as it is, because there is a nice answer and I consider that can help many other students ovecome difficulties of studying chemistry.* ***Edited 2 (My answer to this question)**.* *Now I fully understood the need for chemistry. Sadly I couldn't post my own answer as the question was closed, so I am simply adding it here. Studying some more quantum mechanics, I realised that it provides a good basis for the theoretical understanding of facts through idealised models, but perhaps the only way it can directly contribute to the real world is through experiments and useful numerical values. That's the experimental physics aspect of chemistry that makes it meaningful.* *Another important fact is chemistry itself being a theoretical basis for many other fields, such as molecular biology or chemical engineering. As an example, I would say that it is both practically and theoretically impossible and meaningful to think about the wave functions every single time we consider chemical processes. Various numerical measures in chemistry, such as the equilibrium constant, allow us to focus more on the essence of what's happening in other natural phenomena.* *The final thing I want to emphasise is that contemporarily the boundaries between all of the natural sciences and even engineering have become much less explicit and most research is being conducted under interdisciplinary circumstances. I realised this after learning some proper physics and general chemistry. And general chemistry is like a collection of 100-year-old theories. The interconnections between various fields of studies in the modern sciences are so complex that I cannot, or anybody else would also be unable to, express.*
Interesting question but keep in mind that it is normal to dislike a subject. You don't *have to* like chemistry. Many people loathe physics and mathematics. The world is not affected. I am sure your experience is limited to general chemistry and Oxtoby. In statistical terms, one cannot and should not trust a single sample (=experience). However, some of your complaints and thoughts are worth commenting. **a)** First of all beware that real life is greyish without clear cut boundaries and modern science is more so. One cannot separate the knowledge of physics and mathematics from chemistry. As someone jokingly said, "Chemistry is the physics of the outermost electron." So a "chemist" must *also* study the traditional topics studied by physics students such as quantum mechanics, thermodynamics, and statistical mechanics etc. Since they wish to study the applications of thermodynamics, quantum mechanics, kinetics it is fair to call that thermochemistry (=thermodynamics applied to chemical problems not engines), quantum chemistry (quantum mechanics applied to chemical problems, molecular structure), chemical kinetics (study of the time behaviour of chemical reactions, rate laws, differential equations). **b)** Using the same fallacious argument one may argue that engineering is an application of mathematics or it is a branch of applied mathematics. It does not have that science-looking characteristics. Why do engineering courses have differential equations? Matrices, Vectors? That is pure mathematics, Why do you need to learn programming, that is computer science, why do they need to learn English, this belongs to linguistics, why do you need to learn drawing, that is the artist's job. Again there are no clear cut boundaries in modern science and engineering. **(c)** Regarding the "existence" of chemistry: This is a major misconception and it means you have not looked around carefully. Most of the modern and indispensable objects owe their existence due to the knowledge generated by hundreds of thousands of dedicated chemists in 300-400 years around the world. I am not counting the contributions of medieval scientists. Just look at your own laptop, how many plastic/polymeric and metallic components do you have? How did it become possible to make pure silicon chips? Organic LEDs? What about medicines in your cabinet, printer inks, what color of clothes are you wearing? How many lives the knowledge of chemistry and biology has saved? ALL modern medicines owe their existence due to the *knowledge* of chemistry and *chemical synthesis* including this corona vaccine. Most of the early and important knowledge about atoms and elements came from people who were interested in chemistry. Coming to the unfortunate part of Chemical Education. Yes, the early undergraduate chemical education is indeed in shambles whether it is a rich country or an economically deprived country. General chemistry teaching should be abolished from the first year courses because it is a mere collection of random facts. Gillespie, the man behind VSEPR model and a well respect famous Canadian chemist had written an interesting article 50 years ago. *Chemistry-Fact or Fiction*. He complained that chemistry does not attract the brightest students because the way early chemistry courses are taught. He emphasizes the same thing that there the emphasis is more on memorization of facts. Basically he points out a lot a flaws in the current chemical educational system He is making a general remark. But any serious chemistry teacher should read this article for the sake of inner reflection. It does not by default mean that all engineers are bright by default. There is no shortage of incompetent engineers in the world, just as there is no shortage of gifted and bright chemists.
136308
I am trying to prove that the one-point compactification of the interval $(0,1)$ with the Euclidean Topology is $S\_{1} = \{(x,y)\in \mathbb{R}^{2}|x^{2}+y^{2}=1\}$ and I am having some trouble getting there. The process I am going by has two steps: 1. Show that $(0,1)$ is homeomorphic to $S\_{1} - \{ (1,0)\}$ 2. Show that the one-point compactification of $S\_{1} - \{(1,0)\}$ is $S\_{1}$ itself. Right now, I am stuck on Step 1: What I did was I set up a mapping $g: (0,1) \to S\_{1} - \{ (1,0) \}$ defined by $g: x \mapsto (\cos 2\pi x, \sin 2 \pi x)$. Now, I need to show that $g$ is a homeomorphism. To show that $g$ is onto, I said that if we let $X:= \cos 2 \pi x$ and $Y:= \sin 2 \pi x $, $X^{2}+Y^{2} = (\cos 2\pi x)^{2} + (\sin 2 \pi x)^{2} = \cos ^{2} 2\pi x + \sin^{2} 2 \pi x = 1$, so every point on the unit circle is given by $(X,Y)$. The only point on the unit circle we are not including is $X=1$, $Y=0$, but the preimage of this point under $g$ would be the point $x = 0$, which is not included in the domain. Therefore, the range consists solely of the image set of $g$, so $g$ is onto. To show that $g$ is one-to-one, literally what I did was, I drew graphs of the sine and cosine functions from $0$ to $2\pi$ side-by-side on the same plot, and pointed out that as the parameter $x$ ranges from $0$ to $1$, $X = \cos 2\pi x$ ranges from $\cos (0) $ to $\cos (2 \pi)$ and $Y = \sin 2 \pi x$ ranges from $\sin (0)$ to $\sin (2 \pi)$. Looking at the graphs, we see that for no $x\_{1} \neq x\_{2}$ do we obtain $(\cos (2\pi x\_{1}), \sin(2 \pi x\_{1})) = (\cos (2 \pi x\_{2}), \sin(2 \pi x\_{2}))$, so clearly $g$ is one-to-one as well. **I feel as though these two proofs are too handwavey - could anyone provide me with more rigorous looking way of proving these things?** Really, though, what I wanted to ask about is showing that $g$ is continuous and an open map. If I can show these two things, I can show that $g$ is a homeomorphism and thus I will have part 1 completed. However, normally, to show that $g$ is continuous, I would take an arbitrary open set in the range, so an arbitrary open set in $S\_{1}-\{ (1, 0) \}$ and show that its preimage is also open in the interval $(0,1)$. T**he problem here is that I don't know what an arbitrary open set in $S\_{1}-\{ (1,0) \}$ looks like! Can somebody please show me how to prove this part?** I imagine that once I've seen what this proof is supposed to look like, showing that an open set in $(0,1)$ maps to an open set in $S\_{1} - \{(1,0)\}$ won't be too hard. Although, if you want to provide me with a proof of that too, I won't complain! Thank you ahead of time for your help and patience!
Suppose instead we remove $(0,1)$ from $S^1$ and consider the sterographic projection $f:S^1-{(0,1)}\to\mathbb{R}$ given by $f(x,y)=\frac{x}{1-y}$ which is a homeomorphism (you should check this, but it is very standard). Can you show that $(0,1)$ and $\mathbb{R}$ are homeomorphic?
136452
I am using a `UIImagePicker` to present the users with camera to take photos which will be used in the app. My problem is that on the first time a user opens the image picker they are presented with a prompt saying: '"my App" Would like to Access your Camera' with two options, Don't allow and OK. My requirement is that when the user clicks Don't Allow, the Image picker gets dismissed leaving a black view. Is there a way to detect that the user has chosen Don't allow? Here is my code to present `UIImagePicker`: ``` var PhotoPicker:UIImagePickerController = UIImagePickerController() PhotoPicker.delegate = self PhotoPicker.sourceType = .Camera PhotoPicker.cameraFlashMode = .Off PhotoPicker.showsCameraControls = false PhotoPicker.cameraDevice = .Rear self.presentViewController(PhotoPicker, animated: false, completion: nil) ```
**To detect access to your library:** You need to use AssetsLibrary for that. First, import assets library framework: ``` import AssetsLibrary ``` Then, request authorization status, and if it is not determined, use blocks to catch those events, like this: ``` if ALAssetsLibrary.authorizationStatus() == ALAuthorizationStatus.NotDetermined { let library = ALAssetsLibrary() library.enumerateGroupsWithTypes(.All, usingBlock: { (group, stop) -> Void in // User clicked ok }, failureBlock: { (error) -> Void in // User clicked don't allow imagePickerController.dismissViewControllerAnimated(true, completion: nil) }) } ``` **To detect access to camera:** You need to use AVFoundation for that. First, import avfoundation framework: ``` import AVFoundation ``` Then, as previously, request user permission when you go to imagepicker and catch the event. ``` if AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) == AVAuthorizationStatus.NotDetermined { AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (videoGranted: Bool) -> Void in // User clicked ok if (videoGranted) { // User clicked don't allow } else { imagePickerController.dismissViewControllerAnimated(true, completion: nil) } }) } ``` Hope it helps!
136589
It is mentioned in the following article <https://cacm.acm.org/news/210107-in-memoriam-rudolf-kalman-19302016/fulltext> that (with attribution which I suspect is wrong) > > He also worked with Yu-Chi Ho on the minimal realization problem, resulting in what came to be known as the Ho-Kálmán algorithm. > > > I know that Yu-Chi Ho did work with Kalman, but on Kalman-Ho-Narendra Theorem, for example, [Reference for Kalman-Ho-Narendra Theorem](https://math.stackexchange.com/questions/2564694/reference-for-kalman-ho-narendra-theorem) On the other hand, in <http://www.ece.uah.edu/PDFs/news/RT-sprsum2002.pdf>, we can find the following mentioned by the mathematician R. W. Bass, > > During the years just before and after Kalman accepted a professorship at Stanford in 1964 he published algebraic results pertaining to realization theory, or modeling of linear input-output systems, which laid the groundwork for a stunning discovery by his graduate student B. L. Ho. I am referring to Ho's doctoral dissertation's main result, published in 1966 as a joint paper with Kalman, which I regard as the most profound theorem pertaining to the Systems Identification (ID) problem. > > > the said paper (that I can trace) is "Effective Construction of Linear State-Variable Models from Input/Output Functions". I know that Yu-Chi Ho is also called Larry Ho (at least according to wiki), and is a big shot in control theory. But he apparently is not Kalman's student, nor did he graduate from Stanford. The most recent news about B.L.Ho is in this article <http://www.sontaglab.org/FTPDIR/kalman_students_article_2010.pdf> where only his name appeared. I wonder who B.L. Ho is? (at least the full name) Am I right that he is not Yu-Chi Ho? Many thanks!
Yes, B.L. Ho is Bin-Lun Ho, my father. I only recently found out his association with Rudolf Kahman as I was looking over copies of his doctoral dissertation. He went on after his time at Stanford to work in the hard disk drive industry.
136610
Lets say we have the following List/IEnumerable ``` Program : CPE, ECE ``` Old list: ``` Name Assigned_Area Program Ivan Matala Mathematics CPE Ivan Matala Mathematics ECE Jeremy Cruz Science ECE Ivan Matala Science CPE NJ Aquino Engineering CPE MJ Catanaoan Engineering ECE ``` New list: ``` Name Assigned_Area Program Ivan Matala Mathematics All Programs Jeremy Cruz Science ECE Ivan Matala Science CPE NJ Aquino Engineering CPE MJ Catanaoan Engineering ECE ``` Basically, what I want to do is to merge every record whose 'Name' and 'Assigned\_Area' field are the same, and if each record has both programs (in our case: 'CPE' and 'ECE'), then it should just collapse into a single row whose Program is now 'All Programs'. How do we do it using LINQ? What I've tried so far is the following incomplete code ``` var newlist = oldlist.GroupBy(x => x.Assigned_Area); ``` basically, i was thinking of grouping those records that have the same assigned area, but the code above is incomplete since it only considers a single field (i need to consider 2 fields which are 'Name' and 'Assigned\_Area'), and then, ill count if the each grouping has a count of two,, and if it has a count of two, then i shall collapse it into one record and just replace the program with 'All Programs'. --- Followup question but is related to above.. The above question applies to non anonymous classes. Basically, my real problem is that, I have the following code ``` public IEnumerable GetOfficialList(int visitID) { db = new PACUCOADB5Entities(); var x = (from a in db.Accreditor_Program orderby a.Accreditor.Given_Name, a.Accreditor.Middle_Initial, a.Accreditor.Surname, a.Assigned_Area, a.Program.Requested_Program ascending where a.Program.Visit.VisitID == visitID select new { a.Accreditor.Title, a.Accreditor.Given_Name, a.Accreditor.Middle_Initial, a.Accreditor.Surname, a.Assigned_Area, a.Program.Requested_Program }).ToList(); return x } ``` As you can see, 'x' is my list/IEnumerable and Im trying to apply the same concept to the code I am working into... Basically, I want to do the same, but my attempt was unsuccessful with the following code ``` var newx = x.GroupBy(xx => new {xx.Title,xx.Given_Name,xx.Middle_Initial,xx.Surname,xx.Assigned_Area}) .Select(xx => new {xx.Key.Title, xx.Key.Given_Name, xx.Key.Middle_Initial, xx.Key.Surname, xx.Key.Assigned_Area, xx.Count() == 2 ? "All Programs" :x.First(y => y.Title == xx.Key.Title && y.Given_Name == xx.Key.Given_Name && y.Middle_Initial == xx.Key.Middle_Initial && y.Surname == xx.Key.Surname && y.Assigned_Area == xx.Key.Assigned_Area).Requested_Program)); ``` but Intellisense through me the error ![enter image description here](https://i.stack.imgur.com/9Al12.png) How do we fix it? How do we remove duplicates given that code. Thanks
``` oldList.GroupBy(x => new { x.Name, x.AssignedArea }) .Select(g => g.Count() == 1 ? new Entity(g.Key.Name, g.Key.AssignedArea, g.Single().Program) : new Entity(g.Key.Name, g.Key.AssignedArea, "All programs") ); ``` Here `Entity` is your class with `Name`, `AssignedArea`, and `Program` fields (there isn't its name in your code). All of this will work with the assumption that the count of programs may be either 1 or 2
136770
Today, we were asked to write a Python file which asks the user to input a positive integer and prints the list: ``` [[1], [1, 2], [1, 2, 3],..., [1, 2, 3,..., n]] ``` Here's my code: ``` A=[] n=int(input("Input a positive integer:")) if n>0: A=[[1]] B=[1] for i in range(2,n+1): B+=[i] A+=[B] print(A) ``` This seemed like it would work. But instead of the result it gives me: ``` [[1], [1, 2, 3,..., n], [1, 2, 3,..., n],..., [1, 2, 3,..., n]] ``` It seems to replace the "B"s which were appended to A with the new "B". I really don't understand why it does that. Can anybody here explain it to me?
This is because what you insert to A is a **reference** to B, you are not creating n separate lists. This means that when you are modifying B you modify all it's references, i.e. all the entries in the list A (except for the first that is a separate list). The following code works: ``` n=int(input("Input a positive integer:")) A=[range(1, i+1) for i in range(2, n+1)] print(A) ```
136782
I need to insert into an access database. But skip the row if column dup is already in the table. What I have so far is this: ``` <cfoutput query="hours"> <cfquery name="Employee" datasource="test"> INSERT INTO Tbl_Hours_Comments (ID, ship_num, dup) values(#hours.id#, #hours.ship#, #hours.dup#) </cfquery> </cfoutput> ``` If I don't make dup a Primary Key. Then it will INSERT duplicates. If I make dup a Primary Key. Then I get an error. I think I need something like MySQL. ON DUPLICATE KEY UPDATE. Or maybe dup\_val\_on\_index exception handling like in Oracle. @Gord Thompson I tried (Not sure if I'm doing it right): ``` <cfoutput query="hours"> <cfquery name="Insert_Employee" datasource="trung"> INSERT Tbl_Hours_Comments (ID, ship_num, dup) values(#hours.id#, #hours.ship#, #hours.dup#) SELECT ? as dup FROM( SELECT COUNT(*) as n from Tbl_Hours_Comments) as Dual WHERE NOT EXISTS ( SELECT * FROM Tbl_Hours_Comments WHERE dup = ? ) </cfquery> </cfoutput> ``` But I get [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect . What are the ? in your select statement?
If you are using the Microsoft Access ODBC driver to update the database then you can use `INSERT ... SELECT ... WHERE NOT EXISTS`. The following example is in Python, but it looks like you should be able to do something similar in ColdFusion. ```python import pyodbc cnxn = pyodbc.connect("DSN=db1") # Microsoft Access ODBC crsr = cnxn.cursor() hours_ship = "ship102" # test data hours_dup = 3 # sql = """\ INSERT INTO Tbl_Hours_Comments (ship_num, dup) SELECT ? as ship_num, ? AS dup FROM (SELECT COUNT(*) AS n FROM Tbl_Hours_Comments) AS Dual WHERE NOT EXISTS (SELECT * FROM Tbl_Hours_Comments WHERE dup = ?) """ params = (hours_ship, hours_dup, hours_dup) crsr.execute(sql, params) cnxn.commit() print("{} row(s) inserted".format(crsr.rowcount)) crsr.close() cnxn.close() ``` Note that this approach will *not* work using the Microsoft Access OLEDB provider.
137100
Im trying to retrieve the RSS feed from new.google.com, Im using working with the top stories feed right now: <http://news.google.com/news?ned=us&topic=h&output=rss> I can retrieve and process it right, using: <http://pastebin.com/YDNPXyVK> Here is my log of what im getting: <http://pastebin.com/a5HRsatX>, it seems when there is an apostrophe it stops... I thank you for any help you can offer me.
You might want to use the ROME library. Here's an example: ``` package com.infosys.hanumant.rome; import java.net.URL; import java.util.Iterator; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; /** * @author Hanumant Shikhare */ public class Reader { public static void main(String[] args) throws Exception { URL url = new URL("http://example.com/feed.xml"); XmlReader reader = null; try { reader = new XmlReader(url); SyndFeed feed = new SyndFeedInput().build(reader); System.out.println("Feed Title: "+ feed.getAuthor()); for (Iterator i = feed.getEntries().iterator(); i.hasNext();) { SyndEntry entry = (SyndEntry) i.next(); System.out.println(entry.getTitle()); } } finally { if (reader != null) reader.close(); } } } ``` The example is copied from [here](http://viralpatel.net/blogs/2009/04/reading-parsing-rss-feed-using-rome.html).
137833
I have program with asp.net c# but now i need to create an application in windows forms, I have tried to see some tutorials but they all show only one form. How is this concept done in windows forms? In asp.net you create a page and fill it with controls like text boxes, drop downs etc.. and maybe a button with "Go Next", then you would have another page with different controls and with its own functionality too. So when you click next you would do something like `Response.Redirect("SomePage.aspx");` for example.. How is this done in windows forms?, can I have several forms and navigate from one to the other? and if so how do you persist data when navigating from one to another?. Please excuse if the question is too basic but I am new to windows forms. Any help would be much appreciated Regards
**Follow this link for solution:** [Android Lint contentDescription warning](https://stackoverflow.com/questions/8500544/android-lint-contentdescription-warning) > > Resolved this warning by setting attribute android:contentDescription > for my ImageView > > > android:contentDescription="@string/desc" > > > Android Lint support in ADT 16 throws this warning to ensure that > image widgets provide a contentDescription > > > This defines text that briefly describes the content of the view. This > property is used primarily for accessibility. Since some views do not > have textual representation this attribute can be used for providing > such. > > > Non-textual widgets like ImageViews and ImageButtons should use the > contentDescription attribute to specify a textual description of the > widget such that screen readers and other accessibility tools can > adequately describe the user interface. > > > **This link for explanation:** [Accessibility, It's Impact and Development Resources](http://developer.android.com/guide/practices/design/accessibility.html) > > Many Android users have disabilities that require them to interact > with their Android devices in different ways. These include users who > have visual, physical or age-related disabilities that prevent them > from fully seeing or using a touchscreen. > > > Android provides accessibility features and services for helping these > users navigate their devices more easily, including text-to-speech, > haptic feedback, trackball and D-pad navigation that augments their > experience. Android application developers can take advantage of these > services to make their applications more accessible and also build > their own accessibility services. > > > **This guide is for making your app accessible:** [Making Apps More Accessible](http://developer.android.com/guide/topics/ui/accessibility/apps.html) > > Making sure your application is accessible to all users is relatively > easy, particularly when you use framework-provided user interface > components. If you only use these standard components for your > application, there are just a few steps required to ensure your > application is accessible: > > > 1. Label your ***ImageButton***, ***ImageView***, ***EditText***, ***CheckBox*** and other user > interface controls using the ***android:contentDescription*** attribute. > 2. Make all of your user interface elements accessible with a directional > controller, such as a trackball or D-pad. > 3. Test your application by turning on accessibility services like TalkBack > and Explore by Touch, > and try using your application using only directional controls. > > >
137960
I´m trying to create my own leaderboards sytem for my games so I´m working with PHP and requesting info with Ajax into the games, but as I´m not good at all with PHP I´m pretty confused about how to create a JSON object with all the info I need to handle in the javascript part. What I want to do, in the PHP part is to generate this JSON object: ``` {players: ["name1", "name2", ..., "name10"], scores:[score1, score2, ..., score10]} ``` So I can work in javascript with something like ``` dataReceived.players[0] ``` I´m storing and getting the data correctly from the database but I´m not being able to generate that JSON object to receive in the Ajax request. Basically, this is my PHP code: ``` $query = "SELECT * FROM leadersboards ORDER by score ASC LIMIT 10"; $result = mysql_query($query) or die('Query failed: ' . mysql_error()); $result_length = mysql_num_rows($result); $arrayScores = array(); $arrayPlayers = array(); for($i = 0; $i < $result_length; $i++){ $row = mysql_fetch_array($result); array_push($arrayPlayers, $row['player']); array_push($arrayScores, $row['score']); } $answer = json_encode(array('item' => $arrayPlayers, 'item' => $arrayScores), JSON_FORCE_OBJECT); ``` Sorry if I made something stupid in PHP, as I said, I don´t know PHP at all, just pretty basic stuff.
Solution in short, as kindly offered by Brandon Parmenter, goes as follows: `:bmark http://example.com/search#q=%s -keyword=example` --- Start of the longer/older answer Though the solution inspired by the following link does not change the entries for search engine, it does offer a fully functional **keyword** feature. [wikiHow:How to Add a Custom Search Engine to Firefox's Search Bar](http://www.wikihow.com/Add-a-Custom-Search-Engine-to-Firefox's-Search-Bar-(Windows-Version)) Unlike what has been suggested in the external link, no further add-on is needed. The following steps will complete the definition of a search-keyword: 1. Go to the page on which one can search. (Either google.com, or github.com, or whatever) 2. Right click the search box (through which one can type search inquiry) and select "Add a Keyword for this search" 3. Define the keyword and press enter This is not defining a search engine, but rather a search-keyword. Keywords defined in this way is stored as a `Bookmarks` entry. So far, it is yet unclear how would conflicting keywords between search-engines-keywords and one we just defined should be resolved. Hopefully, since Firefox is syncing `Bookmarks` items, search-keyword may be synced to other installations. Since the question to modifying the search-engine-keyword is yet unsolved, I will not accept my own answer. Additionally, if one would be interested to look into the Bookmark entry, `%s` is the "place-holder" in the "Location" field of such bookmark that will be subsituted by whatever one would like to search.
138161
I am trying to log in on a Drupal site, but the site doesn't have the login block enabled. How can I find the URL for the login form?
Drupal default login URL format, **example.com/user**
138284
I have an AWS S3 bucket called test33333 I need to lock down to minimum necessary permissions. I've created a bucket policy to Deny all except user account **MyUser** a role **MyRole**. (account name xxx out) ``` { "Version": "2012-10-17", "Id": "Policy1571158084375", "Statement": [ { "Sid": "Stmt1568227480842", "Effect": "Deny", "NotPrincipal": { "AWS": [ "arn:aws:iam::xxxxxxxxxxxxx:role/MyRole", "arn:aws:iam::xxxxxxxxxxxxx:user/MyUser" ] }, "Action": "s3:*", "Resource": "arn:aws:s3:::test33333" } ] } ``` Apparently this doesn't work, even though **MyRole** and **MyUser** both have full S3 read access and can read and write to this bucket when the above bucket policy is deleted. What am I missing? I thought this policy above should just refuse everyone but **MyUser** and **MyRole** and then use existing policies attached to the users to grant access. Ultimately I'd like for the bucket policy to control all access and not have to explicitly grant users or roles access to buckets via policies. I've tried everything I can think of thus far. Thanks!
TCP includes congestion control. It will limit traffic to prevent packet loss. UDP just sends all of the packets you request and hopes for the best. <https://www.geeksforgeeks.org/tcp-congestion-control/>
138649
My issue is I have a website that is linking to multiple tables in Oracle. I currently have PHP code that checks user input assigned to a variable to find data in a table, then the oci\_fetch\_row statement that grabs the row where the data matches. This works fine but I cannot find how to output more than one row from a table if some values are the same? Currently the one row it grabs is put into a simple HTML table. Any help in to how to fetch all rows that the data matches and output to table would be appreciated. My code is: ``` $userfeedback = "SELECT * FROM ASSET_FEEDBACK WHERE USER_EMAIL = '$userEmail' ORDER BY FEEDBACK_DATE"; $stmt3 = oci_parse($conn, $userfeedback); if(oci_execute($stmt3)) { $row=oci_fetch_row($stmt3) ; print"<h2 id='title'>This Users Feedback</h2>"; "<table border='2'>"; print"<tr><td><p>Feedback ID:</td><td>$row[0]</td></tr>"; print"<tr><td>Asset ID:</td><td>$row[1]</td></tr>"; print"<tr><td>Feedback:</td><td>$row[3]</td></tr>"; print"<tr><td>Date added:</td><td>$row[4]</td></tr>"; print"</table></br>"; } ```
Put the oci\_fetch\_row statement into a while loop. [OCI Fetch Array](http://www.php.net/manual/en/function.oci-fetch-array.php) for a code sample ``` print"<h2 id='title'>This Users Feedback</h2>"; print"<table border='2'>"; while ($row=oci_fetch_row($stmt3)) { print"<tr><td><p>Feedback ID:</td><td>$row[0]</td></tr>"; print"<tr><td>Asset ID:</td><td>$row[1]</td></tr>"; print"<tr><td>Feedback:</td><td>$row[3]</td></tr>"; print"<tr><td>Date added:</td><td>$row[4]</td></tr>"; } print"</table></br>"; ```
138696
as I checked the Python doc at [python logging](http://docs.python.org/2/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) and with some experiment, I don't quite under stand, > > When computing the next rollover time for the first time (when the handler is created), the last modification time of an existing log file, or else the current time, is used to compute when the next rotation will occur. > > > I found the rotation time for a hourly rotation is affected by the time I start logging, say 12:23:33 starts, and next rotation at 13:23:33, which will finally be confusing to the log file name. Code would be like , ``` TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False) ``` Any way to force the hourly log rotation starts from 00 minute like 13:00:00 rather than the time the logging starts, and every log will contain only the logs within the hour its log file name indicates?
Looking at the code for `TimedRotatingFileHandler`, you can't force it to rotate at a specific minute value: as per the documentation, the next rollover will occur at either `logfile last modification time + interval` if the logfile already exists, or `current time + interval` if it doesn't. But since you seem to know the filename, you could trick `TimedRotatingFileHandler` by first setting the last modification time of the logfile to the current hour: ``` from datetime import datetime import os, time thishour = datetime.now().replace(minute = 0, second = 0, microsecond = 0) timestamp = time.mktime(thishour.timetuple()) # this opens/creates the logfile... with file(filename, 'a'): # ...and sets atime/mtime os.utime(filename, (timestamp, timestamp)) TimedRotatingFileHandler(filename, ...) ``` (untested)
138863
I'm new to programming and have been taking online courses in swift and spritekit trying to create my first working game from scratch. Currently I'm having an issue trying to create a sequence of functions that run independently, wait so that only one is running at a time, and loops indefinitely. The first function: ``` func shootTwentyArrows() { var oneArrow = SKAction.runBlock{ self.shootArrow() } var waitBetweenArrows = SKAction.waitForDuration(arrowSpeed) var fireAnArrow = SKAction.sequence([oneArrow, waitBetweenArrows]) self.runAction(SKAction.repeatAction(fireAnArrow, count: 20)) } ``` And the second function: ``` func shootSpiral1() { var leftArrow = SKAction.runBlock{ self.arrowFromLeft() } var rightArrow = SKAction.runBlock{ self.arrowFromRight() } var waitBetweenArrows = SKAction.waitForDuration(arrowSpeed) var sequence = SKAction.sequence([leftArrow, waitBetweenArrows, rightArrow, waitBetweenArrows]) var spiral1 = SKAction.repeatAction(sequence, count: 5) self.runAction(spiral1) ``` to clarify, I'm trying to run something like: shootTwentyArrows() when that's done, shootSpiral1(), when that's done repeat. Thanks in advance for any responses.
I guess the most correct way to do that would be to refactor code a little bit: ``` func shootTwentyArrows() -> SKAction { let oneArrow = SKAction.runBlock{ self.shootArrow() } let waitBetweenArrows = SKAction.waitForDuration(arrowSpeed) let fireAnArrow = SKAction.sequence([oneArrow, waitBetweenArrows]) return SKAction.repeatAction(fireAnArrow, count: 20) } func shootSpiral1() -> SKAction { let leftArrow = SKAction.runBlock{ self.arrowFromLeft() } let rightArrow = SKAction.runBlock{ self.arrowFromRight() } let waitBetweenArrows = SKAction.waitForDuration(arrowSpeed) let sequence = SKAction.sequence([leftArrow, waitBetweenArrows, rightArrow, waitBetweenArrows]) let spiral1 = SKAction.repeatAction(sequence, count: 5) return spiral1 } ``` Then somewhere in the code you can just do something like that : ``` let spiralAction = shootSpiral1() let oneArrowAction = shootTwentyArrows() let sequence = SKAction.sequence([spiralAction, oneArrowAction]) let infiniteSequence = SKAction.repeatActionForever(sequence) self.runAction(infiniteSequence) ``` I left function names the same on purpose, so you get the idea. **P.S.** It is a common practice to declare a variable as `let`, declare it as `var` only when you have to modify it later.
138933
Looking for some guidance on a wcf 4 rest service which is based on the WCF REST Template 40(CS) extension in VS2010. I've spent the last couple of days trying to get this bugger to work, reviewing other posts, and while I've gotten close, I can't seem to cross the finish line. After much frustration, it is finally hitting the service and posting (using fiddler request builder) but the method parameter is coming across as null, but it's being set properly in the request builder. I'm guessing that it may be a config issue at this point, but as the deadline looms, I'm running out of time for more research. FWIW, in debugging, the jsonstring variable is null. Self admittedly kind of a noob question as this is the first time through REST for me, any help would be much appreciated! Thanks in advance. web.config ``` <system.web> '<compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true"> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </modules> </system.webServer> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/> </webHttpEndpoint> </standardEndpoints> </system.serviceModel> ``` global.asax.cs ``` public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { RegisterRoutes(); } private void RegisterRoutes() { RouteTable.Routes.Add(new ServiceRoute("Scoring", new WebServiceHostFactory(), typeof(ScoringSvc))); } } ``` Service code ``` [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class ScoringSvc { [OperationContract] [WebInvoke (Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)] public string BOB(string jsonstring) { return "Received: " + jsonstring; } } ``` Fiddler request header ``` Host: localhost Content-Length: 20 Content-Type: application/json; charset=UTF-8 ``` request body ``` {"Name":"Frank"} ``` Raw response from fiddler ``` HTTP/1.1 200 OK Cache-Control: private Content-Length: 12 Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Mon, 21 Mar 2011 21:31:14 GMT "Received: " ```
Stumbled across this link [WCF + REST: Where is the request data?](https://stackoverflow.com/questions/1850293/wcf-rest-where-is-the-request-data) and seen Glenn's response to pass a stream to the method and then rip that apart with a streamreader into a string to get the form post data. Modified the prototype service code as follows ``` [OperationContract] [WebInvoke (UriTemplate="/BOB", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)] public string BOB (Stream streamdata) { StreamReader reader = new StreamReader(streamdata); string res = reader.ReadToEnd(); reader.Close(); reader.Dispose(); return "Received: " + res; } ``` And that seems to do the trick, the full json array is passed in the stream, read into the local string, and I can then attack it using json.net to serialize into / from a dictionary to pass to the business logic. Not really pretty, but functional.
139050
I've currently got two computers. One computer is at home another one is where I work. On my breaks I like to work on my own projects at work, however my machine at work is Linux. My machine at home is Windows. I'd like to know if it is possible to simultaneously work on an Android Java project on both Windows and Linux? Clearly I could easily use mercurial or dropbox and just put my work there, but this is not what I'm asking. What I'm asking is, what IDE can I use that works in both linux and windows, will compile the same way so I won't have to change the code based on what operating system I'm using to compile, will let me achieve this goal? ==SUMMARY== Will Eclipse work the exact same way as it does in Linux (Linux Mint 16 to be exact), as it does in Windows? Will I be able to save a project in Linux from Eclipse, and open it up when I get home in Windows and continue working on it?
The easiest way to ensure that you only have polygons is to ensure that you only take the convex hull of groups where the groupid count is greater than 2. ``` SELECT groupid, ST_ConvexHull(ST_Collect(geom))) As hull_geom into hulledpoints FROM somepoints GROUP BY groupid HAVING count(groupid)>2; ``` This is because the convex hull of two points is a linestring, while the convex hull of a point is that same point, eg, ``` select ST_AsText(ST_ConvexHull(ST_Collect(St_MakePoint(1,1),St_MakePoint(2,2)))); ``` which returns LINESTRING(1 1,2 2). If you wanted to use a geometric rather than a sql approach, you could check the returned hulls were polygons. The following example returns nothing, as although there are three points, two are coincident, so the convex hull will still be a linestring. ``` with hulls as (select ST_ConvexHull(ST_Collect(Array[St_MakePoint(1,1), St_MakePoint(2,2), St_MakePoint(2,2)])) as hull) select * from hulls where ST_GeometryType(hull)='ST_Polygon'; ``` In your original example, you would write the above query along the lines of, ``` with hulls as (SELECT groupid, ST_ConvexHull(ST_Collect(geom)) As hull_geom FROM somepoints GROUP BY groupid) select * from hulls where ST_GeometryType(hull_geom)='ST_Polygon'; ```
139244
So Im working with a user interface where the user should be able to edit and delete it's data in the database. But when im trying to post the form, it doesnt save the changes. Here's some code: Model: ``` namespace Aviato.Models { using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public partial class TimesheetEntry { [Key] [Column(Order = 0)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int UserId { get; set; } [Key] [Column(Order = 1)] [StringLength(50)] public string ProjectId { get; set; } [Key] [Column(Order = 2, TypeName = "date")] public DateTime EntryDate { get; set; } public decimal HoursWorked { get; set; } public virtual Project Project { get; set; } public virtual User User { get; set; } } } ``` View: (Index) ``` @model IEnumerable<Aviato.Models.TimesheetEntry> @{ Layout = "~/Views/Shared/_Layout.cshtml"; } <h1>Tidrapportering</h1> <p> @Html.ActionLink("Skapa ny", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.UserId) </th> <th> @Html.DisplayNameFor(model => model.Project.ProjectName) </th> <th> @Html.DisplayNameFor(model => model.EntryDate) </th> <th> @Html.DisplayNameFor(model => model.HoursWorked) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.UserId) </td> <td> @Html.DisplayFor(modelItem => item.Project.ProjectName) </td> <td> @Html.DisplayFor(modelItem => item.EntryDate) </td> <td> @Html.DisplayFor(modelItem => item.HoursWorked) </td> <td> @Html.ActionLink("Redigera", "Edit", new { id=item.UserId, item.ProjectId, item.EntryDate }) | @Html.ActionLink("Ta bort", "Delete", new { id=item.UserId, item.ProjectId, item.EntryDate}) </td> </tr> } </table> <div> @Html.ActionLink("Tillbaka", "Index", "User") </div> ``` (Edit) ``` @model Aviato.Models.TimesheetEntry @{ Layout = "~/Views/Shared/_Layout.cshtml"; } <h1>Redigera</h1> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <hr /> @Html.ValidationSummary(true) @Html.HiddenFor(model => model.UserId) @Html.HiddenFor(model => model.Project) @Html.HiddenFor(model => model.User) <div class="form-group"> @Html.LabelFor(model => model.ProjectId, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ProjectId, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ProjectId) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EntryDate, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.EntryDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.EntryDate) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.HoursWorked, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.HoursWorked, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.HoursWorked) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Spara" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Tillbaka", "Index") </div> ``` Controller: ``` public ActionResult Edit(int? id, string projectId, DateTime entryDate) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var timesheetentry = _db.TimesheetEntries.Find(id, projectId, entryDate); if (timesheetentry == null) { return HttpNotFound(); } ViewBag.ProjectId = new SelectList(_db.Projects, "ProjectId", "ProjectName", timesheetentry.ProjectId); ViewBag.UserId = new SelectList(_db.Users, "UserId", "SocialSecurityNumber", timesheetentry.UserId); return View(timesheetentry); } [HttpPost] public ActionResult Edit(TimesheetEntry timesheetentry) { if (ModelState.IsValid) // So here's where the breakpoint skips. I get User and Project to be null in timesheetentry! { _db.Entry(timesheetentry).State = EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.ProjectId = new SelectList(_db.Projects, "ProjectId", "ProjectName", timesheetentry.ProjectId); ViewBag.UserId = new SelectList(_db.Users, "UserId", "SocialSecurityNumber", timesheetentry.UserId); return View(timesheetentry); } ``` Database: ``` CREATE TABLE [dbo].[TimesheetEntries] ( [UserId] INT NOT NULL, [ProjectId] NVARCHAR (50) NOT NULL, [EntryDate] DATE NOT NULL, [HoursWorked] DECIMAL (8, 1) CONSTRAINT [DF_TimesheetEntries_HoursWorked] DEFAULT ((0.0)) NOT NULL, CONSTRAINT [PK_TimesheetEntries] PRIMARY KEY CLUSTERED ([UserId] ASC, [ProjectId] ASC, [EntryDate] ASC), CONSTRAINT [FK_TimesheetEntries_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[Users] ([UserId]), CONSTRAINT [FK_TimesheetEntries_Projects] FOREIGN KEY ([ProjectId]) REFERENCES [dbo].[Projects] ([ProjectId]) ); ```
Ok, so I can kind of understand why its happening. In your edit page you have these lines ``` @Html.HiddenFor(model => model.Project) @Html.HiddenFor(model => model.User) ``` But this is not enough for it to be able to round trip all the data associated with these sub-objects. If you view source on the HTML page, you should see what I mean. A hidden HTML field cannot cope with a complex object. If you really want to round-trip these objects then you will need to output all their fields as hidden fields, or create a template to do this. Or simply have a view model that does not contain the sub objects.
139387
I am running into an issue trying to host two services on the same site. They have the same base uri, but different services names, and each has its own contract. While testing in my VS environment (IIS 7.5) everything works fine. However when I deploy to a server (IIS 8.5), both uri's are showing the same wsdl for some reason. It seems like the contract for the second service is ignored. There are two different .svc files with code behind. (all names have been changed to protect the innocent.) sites: <https://mysite/services/Service1.svc> <https://mysite/services/Service2.svc> Here is my config: ``` <services> <service name="Service1" behaviorConfiguration="DefaultBehavior"> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="DefaultBinding" contract="Namespace.IService1"/> <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/> </service> <service name="Service2" behaviorConfiguration="DefaultBehavior"> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="DefaultBinding" contract="Namespace.IService2"/> <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/> </service> </services> <bindings> <wsHttpBinding> <binding name="DefaultBinding" receiveTimeout="00:05:00" sendTimeout="00:05:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Mtom" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <reliableSession ordered="true" inactivityTimeout="00:5:00" enabled="false"/> <security mode="Transport"> <transport clientCredentialType="None" /> </security> </binding> <wsHttpBinding> <bindings> <serviceBehaviors> <behavior name="DefaultBehavior"> <serviceMetadata httpsGetEnabled="true" httpsGetBindingConfiguration="true" /> <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" /> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> <serviceThrottling maxConcurrentCalls="160" maxConcurrentInstances="160" maxConcurrentSessions="100" /> </behavior> </serviceBehaviors> ``` The problem is that both sites are reflecting the same WSDL, i.e. same methods for `contract="Namespace.IService1"` Any ideas on what is going on here to cause this?
You should, if possible, remove the spaces server-side. I hope you understand **no** javascript will run in the emails you send. ``` // This prevents multiple `window.onload` conflict window.addEventListener("load", clearLinks); // This allows you to call the function even later if needed function clearLinks() { // Get list of all links in the page var links = document.getElementsByTagName("a"); // Loop through links for(var i=0,l=links.length; i<l; i++) { // No need to use `getAttribute`, href is defined getter in all browsers links[i].href = links[i].href.replace(/\s/g, ""); } } ``` In modern browsers, you can replace the for loop with `Array.prototype.forEach`. This method can be normally called on arrays (`[ ... ]`), but the list returned by `getElementsByTagName` is not an array, so use this trick: ``` function clearLinks() { var links = document.getElementsByTagName("a"); // Loop through links Array.prototype.forEach.call(links, function(link) { link.href = link.href.replace(/[cC]/g, "c"); }); } ``` Search for `Function.prototype.call` to learn more about calling functions on objects.
139701
what does misning btime mean? ``` # ps aux | grep ssh missing btime in /proc/stat ``` I'm on an embedded system (ts-7600)running a Debian version via UART. ``` #uname -a Linux ts7600-4aa86d 2.6.35.3-571-gcca29a0+ #2 PREEMPT Thu Jan 22 12:21:50 PST 2015 armv5tejl GNU/Linux ``` I figured I should look at btime, and saw a post on a linux forum to do: ``` # cat /proc/stat␍␊ [21:14:57:236] cpu 3081 0 3263 217610 305 0 2 0 0 0␍␊ [21:14:57:236] cpu0 3081 0 3263 217610 305 0 2 0 0 0␍␊ [21:14:57:236] intr 307219 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 805 294809 0 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 2525 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9034 0 0 0 0 0 0 0 0 0 24 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0␍␊ [21:14:57:293] ctxt 558977␍␊ [21:14:57:293] btime 0␍␊ [21:14:57:293] processes 2774␍␊ [21:14:57:293] procs_running 1␍␊ [21:14:57:293] procs_blocked 0␍␊ [21:14:57:293] softirq 37073 0 25258 1 695 0 0 634 0 564 9921␍␊ ``` ok, so btime is 0, I also looked at time, and that is also zero. do I need to fix this? I just want to make ssh work on this thing. or how can I make time work? this device has an integrated RTC.
You might be the victim of a repository mirroring error. Or a Web filter (if your site has one) might be blocking the system's access to the Debian repository. `deb.debian.org` is a GeoIP redirector, that attempts to connect you to the Debian repository that is closest to you. The Web filter might not have full knowledge of all the addresses the redirector might send you. The InRelease file could be downloaded manually with a simple: ``` wget http://ftp.debian.org/debian/dists/buster/InRelease ``` or ``` curl http://ftp.debian.org/debian/dists/buster/InRelease > InRelease ``` As far as I can see, the resulting file has not changed since 2022-09-10 and should be exactly 121570 bytes in size. This agrees with the fact that Debian 10.12 was released on that day, and that release marked [the transition of Debian 10 to Long-Term Support.](https://www.debian.org/News/2022/20220910) The resulting file should be a PGP-signed text file, that starts with: ``` -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 Origin: Debian Label: Debian Suite: oldstable Version: 10.13 Codename: buster Changelogs: http://metadata.ftp-master.debian.org/changelogs/@CHANGEPATH@_changelog Date: Sat, 10 Sep 2022 11:30:54 UTC Acquire-By-Hash: yes ``` If you get something different, it might be a notification page from your local web filter proxy (if your site has one), or perhaps the mirror site you ultimately end up connecting to has had a disk failure and has not yet fully re-mirrored that file, possibly resulting an incomplete file. Your strace indicates the `stat()` system call is returning `st_size=56621`, so you seem to be getting an incomplete or different file. If the resulting file seems to be a HTML file, rename it as `something.html` and view it with a web browser. If it is a notification from a local Web filter, you may have to contact the administrator of that filter. If it is some other HTML error page, the repository `deb.debian.org` is pointing you at might be suffering a fault of some sort. If you cannot wait for the repository to get fixed, you could always go to <https://www.debian.org/mirror/list> and pick one or two mirrors close to you, temporarily configure your `sources.list` to use them instead of `deb.debian.org`, and so attempt to work around the faulty repository.
140157
Let's say I want to delete 10% of rows, is there a query to do this? Something like: ``` DELETE FROM tbl WHERE conditions LIMIT (SELECT COUNT(*) FROM tbl WHERE conditions) * 0.1 ```
I would simply return the total amount of filtered rows, calculate through php and use that value as a limit in my DELETE query. ``` $query = mysql_query("SELECT COUNT(*) FROM tbl WHERE conditions"); $int = reset(mysql_fetch_array($query)); $int = round($int * 0.1); mysql_query("DELETE FROM tbl WHERE conditions LIMIT {$int}"); ``` I'm not sure if DELETE allows an advanced query such as this one: ``` DELETE FROM ( SELECT h2.id FROM ( SELECT COUNT(*) AS total FROM tbl WHERE conditions) AS h JOIN ( SELECT *, @rownum := @rownum + 1 AS rownum FROM tbl, (SELECT @rownum := 0) AS vars WHERE conditions) AS h2 ON '1' WHERE rownum < total * 0.1) AS h3 ```
140252
I installed Ububtu 12.04LTS as dual boot along with my Windows 7. I need to remove Grub and restore Windows MBR but without uninstalling Ubuntu
To install a Windows bootloader, boot Windows and create a Repair CD. Boot from the repair CD (or from your original Windows DVD) to a repair prompt and run: ``` bootrec /fixmbr ``` (If you use Windows XP then the command is: `fixmbr`) If you can't boot Windows and can't create a repair CD, you can install something like `lilo` which works identically to the Windows boot loader when used as shown below. Boot from an Ubuntu CD/USB and select "Try Ubuntu", connect to the internet and drop to a terminal (Ctrl+Alt+T): ``` sudo apt-get update sudo apt-get install lilo sudo lilo -M /dev/sda mbr ``` Note, when you install lilo it will popup a big warning. You can ignore this (as it's not relevant when installing a Windows-style bootloader) - Tab to OK and hit enter. Also, if you don't boot from `/dev/sda` change as appropriate. If you're planning to continue to boot Ubuntu after replacing the Windows bootloader you can use [easyBCD](http://neosmart.net/EasyBCD/). Otherwise you'll need to boot a live CD/USB to reinstall Grub later.
140282
I have come across the "R cannot be resolved" error countless times but there has always been an easy fix. Sorry to trouble you but I'm stumped this time... I recently decided to dual boot my computer into Windows 7/Ubuntu (previously Windows 7 only) and load Eclipse for my Android app development, however I came across the infamous R cannot be resolved error. After a clean install of Ubuntu 12.10, I set up [Google's ADT Bundle](http://developer.android.com/sdk/installing/bundle.html) from the Android Developer website. I installed the Eclipse, SDK and ADB that were included in the package from the above download (ADT came pre-installed/setup). This is a special version of Eclipse provided by Google and includes the text "Android Developer Tools" when Eclipse is started. Eclipse runs Java Projects fine, the SDK Manager seems to be set up correctly because I can launch it directly from Eclipse (I have also installed all of Android SDKs 1.5-4.2), AVD Manager almost works correctly (it launches and allows me to create new devices but will not start with the message "PANIC: could not open: some\_device"), however any Android project will not compile with the error "R cannot be resolved to a variable". I have tried using my existing Android projects from two of my old workspaces as well as creating a new workspace but they all resort to the same error. Any advice? I would really like to begin working in a Linux-based environment and have spent several hours trying to get this to work... I would highly appreciate anyone's ideas/advice/solutions/pity/etc. EDIT: I'm starting to think this problem is probably connected to my other error when launching an Android Virtual Device where it states "PANIC: could not open: some\_device". Sadly I have no idea what's causing this nor how to fix it either...
I had the same issue. Fresh install of ADT Bundle, creating a new project using wizard, was giving me "R cannot be resolved to a variable" error. I tried everything explained in previous post. In my particular case, it was that I had another copy of Android SDK tools and ADT Bundle was pointing to that one, instead of the one that comes with the bundle. I just changed that, and all projects were working again. Hope this helps.
140331
I want to use the windows detours library to detour a non win api function. The function is part of the Qt library (QtGui4.dll). I am wondering how I would set up the function signature for : ``` void QPainter::drawText ( const QPointF & position, const QString & text ) ``` I had a go with this and it received my usual share of errors, a little explanation of requirements would be interesting as well: ``` void (QPainter * real_drawText)(const QPointF & position, const QString & text) = drawText ``` This is what they look like for TextOut, under the windows API: ``` BOOL (WINAPI * Real_TextOut)(HDC a0, int a1, int a2, LPCWSTR a3, int a4) = TextOutW; BOOL WINAPI Mine_TextOut(HDC hdc,int X,int Y,LPCWSTR text,int textLen) { BOOL rv = Real_TextOut(hdc, X, Y, text, textLen); HWND hWindow = WindowFromDC(hdc); SendTextMessage(hWindow, text); return rv; } ``` So, following on from Gene's suggestion I tried: ``` typedef void (QPainter::* Real_qp_drawText)(const QPointF & position, const QString & text); void Mine_drawText(const QPointF & position, const QString & text) { Real_qp_drawText(position,text); } ``` But got the error, 'a function-style conversion to a built-in type can only take one parameter. So anyway, they say a little public humiliation is good for the soul, my soul must be having the best time... Thanks.
The simplest solution is to use an external wrapper that reads a line with edition capabilities, then sends it to your program. A good wrapper is [rlwrap](http://utopia.knoware.nl/~hlub/rlwrap/). Using a separate tool is in keeping with the unix philosophy of using separate tools for separate purposes (line edition and whatever your program does). It's also simple: just make your shell wrapper run `rlwrap myprogram` instead of `myprogram`. The underlying [readline library](http://www.gnu.org/software/readline/) (no relation to any `readLine` method in Java; you'll want a Java wrapper such as [Java-Readline](http://java-readline.sourceforge.net/)) is more work to integrate, and constrains your program to be GPL. Go for that only if you want more than what a wrapper can provide — primarily application-specific completions.
140611
I am somewhat familiar with html but am not with java script I am wondering if there is a way to have a form with say for example a name field and based on the name that is input to the field use java script to redirect to an html page for that person. ``` <!DOCTYPE html> <html lang="en"> <head> <title>Redirect Form</title> <meta charset="utf-8"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <form> <p>Name:</p><input type="name" id="name"> <p>E-mail</p><input type="email" id="inputEmail"><br> <br> <button type="button">Redirect</button> </form> </body> ``` So I have this and i want to type in the name "John" in the name field and have it redirect to a page named john.html or if i type in the name "mary" have it redirect to a page named mary. I dont want to generate pages for each name this will be for the two specific names that will have their pages created beforehand. How do i create the java script to handle that for me?
I think that the main idea comes from that usual "B is A" class inheritance definition. You can rephrase it for member functions like "functions of A are functions of B", however statement with flipped A and B position is correct only for some items, that is "only some functions of B are functions of A". So `B::fn` fits into this category of functions of B that are functions of A. By writing function `fn` in class B we at the same time move `B::fn` out of this category into category of functions of B that are not functions of A. This allows one to check whether class overrides some method of base class: ``` const bool fn_is_overriden{::std::is_same<decltype(&A::fn), decltype(&B::fn)>::value}; ```
140768
I have been working on an application that caches an image from the web and shows it even when the user is offline. This worked pretty well until Android 4.4 came out. Now, all I see is a "Can not load the webpage" error. I suppose it might have to do something with the fact that Kitkat uses Chromium for loading webviews, but I am not very sure. Any fixes for this? Here is my code: ``` mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); mWebView.setWebViewClient(new MyWebViewClient()); mWebViewSettings = mWebView.getSettings(); mWebViewSettings.setJavaScriptEnabled(true); mWebViewSettings.setAllowFileAccess(true); mWebViewSettings.setAppCacheEnabled(true); if (Build.VERSION.SDK_INT < 18) mWebViewSettings.setAppCacheMaxSize(5 * 1024 * 1024); // 5MB mWebViewSettings.setLoadsImagesAutomatically(true); mWebViewSettings.setAppCachePath(getActivity().getApplicationContext() .getCacheDir().getAbsolutePath()); mWebViewSettings.setBuiltInZoomControls(true); if(Build.VERSION.SDK_INT<=18) mWebViewSettings.setDefaultZoom((WebSettings.ZoomDensity.FAR)); mWebViewSettings.setUseWideViewPort(true); mWebViewSettings.setLoadWithOverviewMode(true); ``` I am loading it using the following code: ``` if (NetworkUtil.IS_ONLINE_WITH_DATA_CONNECTION) { MyPrefs = getActivity().getSharedPreferences( "AHSelectionPreffs", Context.MODE_PRIVATE); Date CAMPUS_MAP_LAST_UPDATE_DATE = new Date(); String CAMPUS_MAP_LAST_UPDATE_DATE_STRING = MyPrefs .getString("CAMPUS_MAP" + String.valueOf(StorageHelper.ID), null); SimpleDateFormat simpleDateFormatter = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); if (CAMPUS_MAP_LAST_UPDATE_DATE_STRING != null) { try { CAMPUS_MAP_LAST_UPDATE_DATE = simpleDateFormatter .parse(CAMPUS_MAP_LAST_UPDATE_DATE_STRING); } catch (ParseException e1) { e1.printStackTrace(); System.out.println("Cant format date!!!!"); } int n = (int) ((curDate.getTime() - CAMPUS_MAP_LAST_UPDATE_DATE .getTime()) / (1000 * 60 * 60)); if (n < 24 * UPDATE_DURATION_IN_DAYS) { mWebView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK); } else { updateCampusMapData(); } } else { updateCampusMapData(); } } else { mWebView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK); } if (StorageHelper.campus_map_link.Mobile_Link_URL != null) { mWebView.loadUrl(StorageHelper.campus_map_link.Mobile_Link_URL); } private void updateCampusMapData() { mWebView.getSettings().setCacheMode( WebSettings.LOAD_NO_CACHE); MyPrefs = getActivity().getSharedPreferences( "AHSelectionPreffs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = MyPrefs.edit(); editor.putString("CAMPUS_MAP" + String.valueOf(StorageHelper.ID), curDate.toString()); editor.commit(); } ```
Got it solved myself. I figured out that Chromium is not caching images with size greater than 1 MB. In other cases, it works perfectly fine. Reported this to Google, for now.
141039
I am trying to set Environment Variables for a Nginx And Gunicorn Served Django Project on Ubuntu. The variables are set for the Ubuntu user and i am able to see the value using `printenv VAR_EMAIL`. But when i use them django settings it is not working , using them as `os.environ['VAR_EMAIL']`,This doesn't get the value of the variable in production and server doesn't work. However this works on Development side. UPDATE 1st May 2020: I used systemd and passed the variable like this in gunicorn.service file.This won't work still get key error,)Will post the exact error) as it is production on Ubuntu but i am developing on Windows and it works fine with Environment Variables in Development. is `os.environ['var_name']` correct way to access that ? I also tried `os.environ.get('var_name')` as i saw in some video that environ have `.get()` to access the value. I will try again maybe i made some mistake.Feel free to ask for any info required. [![Service File](https://i.stack.imgur.com/RIc41.png)](https://i.stack.imgur.com/RIc41.png) ANSWERED - It was error on my end.
What are you using to supervise and run the gunicorn process in Ubuntu? If you're not using any, I recommend you to use `systemd`, there's a small guide on how to setup in the gunicorn docs: <https://docs.gunicorn.org/en/stable/deploy.html#systemd> After that, you can set the environment variables in the systemd config file doing like the following, under the `[Service]` section of the systemd config file: ``` [Service] Environment="VAR_EMAIL=var-email" Environment="ANOTHER_VAR=another-var" ``` You can also use the `EnvironmentFile` directive if you prefer to have these variables in a separate file: <https://www.freedesktop.org/software/systemd/man/systemd.exec.html#EnvironmentFile=>
141227
I'm using this code but the value said "undefined" can anyone point me the problem? this is my java class codes ``` public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.frux.web.R.layout.activity_main); String value = "Isiah"; WebView web = (WebView) findViewById(R.id.web1); web.getSettings().setJavaScriptEnabled(true); web.loadUrl("file:///android_asset/www/index.html"); web.loadUrl("javascript:setValue(\""+ value +"\")"); } ``` and this is my webpage codes ``` <!DOCTYPE html> <html> <head> </head> <body> Whats your Name? <input id="name" value="" /> <button onclick = "setValue()">Submit</button> <script type="text/javascript"> function setValue(value){ var myValue = value; document.getElementById("name").value = myValue; } </script> </body> </html> ``` I also try this one ``` web.loadUrl("javascript:setValue('"+ value +"')"); ``` any thoughts will be highly appreciated I used the codes in this HTML codes and its display nothing unlike the other codes above that I post. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <script type="text/javascript"> function setValue(amount1) { myValue = amount1; document.getElementById("amount").value = myValue; } function rand ( n ) { document.getElementById("orderRefId").value = ( Math.floor ( Math.random ( ) * n + 1 ) ); } </script> </head> <body onLoad="rand(200000);setValue();"> <!-- Note: https://www.pesopay.com/b2c2/eng/payment/payForm.jsp for live payment URL https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp for test payment URL --> <form method="POST" name="frmPayment" action="https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp"> <table> <tbody> <tr> <td>Order Reference No. (your reference number for every transaction that has transpired):</td> <td><input type="text" id="orderRefId" name="orderRef" value="Test-001"/></td> </tr> <tr> <td>Amount:</td> <td><input type="text" name="amount" id="amount" value=""/></td> </tr> <tr> <td>Currency Code - "608" for Philippine Peso, "840" for US Dollar:</td> <td><input type="text" name="currCode" value="608"/></td> </tr> <tr> <td>Language:</td> <td><input type="text" name="lang" value="E"/></td> </tr> <tr> <td>Merchant ID (the merchant identification number that was issued to you - merchant IDs between test account and live account are not the same):</td> <td><input type="text" name="merchantId" value="18056869"/></td> </tr> <tr> <td>Redirect to a URL upon failed transaction:</td> <td><input type="text" name="failUrl" value="http://www.yahoo.com?flag=failed"/></td> </tr> <tr> <td>Redirect to a URL upon successful transaction:</td> <td><input type="text" name="successUrl" value="http://www.google.com?flag=success"/></td> </tr> <tr> <td>Redirect to a URL upon canceled transaction:</td> <td><input type="text" name="cancelUrl" value="http://www.altavista.com?flag=cancel"/></td> </tr> <tr> <td>Type of payment (normal sales or authorized i.e. hold payment):</td> <td><input type="text" name="payType" value="N"/></td> </tr> <tr> <td>Payment Method - Change to "ALL" for all the activated payment methods in the account, Change to "BancNet" for BancNet debit card payments only, Change to "GCASH" for GCash mobile payments only, Change to "CC" for credit card payments only:</td> <td><input type="text" name="payMethod" value="ALL"/></td> </tr> <tr> <td>Remark:</td> <td><input type="text" name="remark" value="Asiapay Test"/></td> </tr> <!--<tr> <td>Redirect:</td> <td><input type="text" name="redirect" value="1"/></td> </tr>--> <tr> <td></td> </tr> <input type="submit" value="Submit"> </tbody> </table> </form> </body> </html> ```
Wrap your passed value in double quotes: ``` web.loadUrl("javascript:setValue(\""+value+"\")"); ``` I got this! When you call `loadUrl` for the second time the page has not loaded yet. The solution would be attaching your `setValue` call to `window.onload` event: ``` super.loadUrl("javascript:window.onload = function(){setValue(\"haha\");};"); ``` This code loads 'haha' into input correctly.
141363
I am making a JavaFX based game that shoots drones using a spaceship to defend your base. I want to wrap a shape around an image to create a hitbox for it. This will allow the laser to cause damage to the drone whenever it touches the hitbox. It will make the game look better than the laser hitting an invisible wall (the shape's dimensions), and not the actual image. My question is, is there any built-in library that JavaFX provides to solve this problem, or do you have to use a calculus formula to solve this? I have tried to look over the API's of JavaFX, but I cannot seem to find anything useful. ``` // Getting the images for the shapes Image spaceCity = new Image("com/images/spaceCity.jpg"); Image spaceShip = new Image("com/images/spaceShip.png"); // Making the graphics Rectangle space_Ship = new Rectangle(0, positionOfShipY, 191, 300); Rectangle background = new Rectangle(0, 0, STAGE_WIDTH, STAGE_HEIGHT); ``` I have my example here (I do not know why Stack overflow does not allow me to upload images): <https://docs.google.com/document/d/1A8HJ61jhthBhd7wr6xrZNLlsTcQJNLUhTzrucvNY3BY/view?usp=sharing>
Set the shape's dimensions based on image, and place both in a `StackPane`: ``` import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class FxTest extends Application { @Override public void start(Stage primaryStage) throws Exception{ String imagePath = "https://png.pngtree.com/png-clipart/20190118/ourmid/" + "pngtree-hand-drawn-spaceship-grey-spaceship-alien-spaceship-blue" + "-spaceship-border-png-image_450067.jpg"; Image image = new Image(imagePath); Rectangle rec = new Rectangle(0, 0, 50+image.getWidth(), 50+image.getHeight()); rec.setFill(Color.AQUA); StackPane root = new StackPane(); root.getChildren().add(rec); root.getChildren().add(new ImageView(image)); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(null); } } ``` [![enter image description here](https://i.stack.imgur.com/Rchal.png)](https://i.stack.imgur.com/Rchal.png)
141809
Currently I am creating a forest scene in the dark, and the trees are shining far away, but when I get close they are fine. I have the shaders set to "Nature/Tree Soft Occlusion [bark/leaves]", but they are still rendering strange far away, but close they are fine. ![enter image description here](https://i.stack.imgur.com/vdRbq.png) I tried placing the trees in a folder named "Ambient-Occlusion" like said [here](https://stackoverflow.com/questions/12110274/why-do-my-trees-shine-bright-white-in-the-background/12113805#12113805), but no luck. Also fog is turned off. Thanks in advance. **UPDATE** When I looked at the trees using the "Render Paths" camera, they appeared red while everything else was green. ![picture](https://i.imgur.com/qM2pi.png) **UPDATE 2** I have tried re-installing the package I downloaded these from, but still no luck. **UPDATE 3** I have added some trees manually, and they work fine, but when adding them by painting on the terrain I get the problem. **FINAL UPDATE** I tried building the game to see if this had the effect on the .exe, and it didn't. So I just have to ignore when I am debugging it, as it works fine on the build. Thanks for all the help, it just seems like an error with unity. Picture of build: ![image](https://i.imgur.com/ZNqmA.png)
Turns out that it was rendered fine in the builds of the project, just not in the debugger in unity. I am planning on reporting this as an error on unity's site, as it was messed up in the debugger only, not the game.
142238
I have a TextField on my screen when keyboard open on it its showing overflow error and keyboard is closing automatically due to this issue. My code ``` Scaffold( backgroundColor: Color(0xfff3f2f8), body: Form( key: formKey, child: Container( child: Column( children: <Widget>[ SizedBox( height: Height * 0.175, ), Container( width: MediaQuery.of(context).size.width * 0.7, child: Image.asset('images/splash-logo.png')), SizedBox( height: Height * 0.025, ), Text( 'Please enter your phone number', style: TextStyle(fontFamily: 'PoppinsMedium', fontSize: 18), ), Spacer(), SingleChildScrollView( child: ClipShadowPath( shadow: Shadow(blurRadius: 10.0, color: Colors.grey), clipper: RoundedDiagonalPathClipper(), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(30.0)), color: Colors.white, ), child: Column( children: [ SizedBox( height: Height * 0.125, ), Align( alignment: Alignment.bottomLeft, child: Padding( padding: const EdgeInsets.only(left: 13), child: Text( 'Phone Number', style: TextStyle( fontFamily: 'PoppinsBold', fontSize: 20), ), )), Align( alignment: Alignment.center, child: Container( width: MediaQuery.of(context).size.width * 0.9, child: InternationalPhoneNumberInput( onInputChanged: (PhoneNumber number) { setState(() { TypePhoneNumber = number.phoneNumber; }); }, onInputValidated: (bool value) { if (!value) { setState(() { numberValidate = false; }); } if (value) { setState(() { numberValidate = true; }); } }, selectorConfig: SelectorConfig( selectorType: PhoneInputSelectorType.BOTTOM_SHEET, ), ignoreBlank: false, autoValidateMode: AutovalidateMode.disabled, selectorTextStyle: TextStyle(color: Colors.black), initialValue: number, textFieldController: controller, formatInput: false, keyboardType: TextInputType.numberWithOptions( signed: true, decimal: true), onSaved: (PhoneNumber number) { print('On Saved: $number'); }, ), ), ), SizedBox( height: Height * 0.06, ), Align( alignment: Alignment.bottomLeft, child: MaterialButton( onPressed: () async {}, child: Padding( padding: const EdgeInsets.only(bottom: 25), child: Container( height: Height * 0.07, width: Width * 0.6, decoration: BoxDecoration( color: Color(0xffef1334), borderRadius: BorderRadius.only( topLeft: Radius.circular(25), topRight: Radius.circular(25), bottomLeft: Radius.circular(25), bottomRight: Radius.circular(25)), ), child: Center( child: Text( 'Register', style: TextStyle( fontSize: 15, fontWeight: FontWeight.bold, fontFamily: 'PoppinsRegular', color: Colors.white), )), ), ), ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( width: 10, ), Image.asset( 'images/cutLogo.png', width: 120, ), ], ) ], ), ), ), ), ], ), ), ), ); ``` If i wrap my main Column which is inside Form with SingleChildScrollView my whole display dissapear. I also try to add SingleChild in clipper but its also not work
To offset longer sentences and to make sure overlap at word level you should rather use `token_set_ratio`. Also if you want full word overlap then increase the `MIN_MATCH_SCORE` to close to 100. ``` from fuzzywuzzy import fuzz MIN_MATCH_SCORE = 90 heard_word = 'i5-1135G7' possible_words = ['11th Generation Intel® Core™ i5-1135G7 Processor (2.40 GHz,up to 4.20 GHz with Turbo Boost, 4 Cores, 8 Threads, 8 MB Cache)', 'windows 10 64 bit', 'intel i7'] print ([word for word in possible_words if fuzz.token_set_ratio(heard_word, word) >= MIN_MATCH_SCORE]) ``` Output: ``` ['11th Generation Intel® Core™ i5-1135G7 Processor (2.40 GHz,up to 4.20 GHz with Turbo Boost, 4 Cores, 8 Threads, 8 MB Cache)'] ```
142519
In [How can I repair a split in a board?](https://woodworking.stackexchange.com/questions/889/how-can-i-repair-a-split-in-a-board), the accepted response suggests a "dutchman patch," but I'm getting mixed messages from various sources. Some show a dutchman as being the removal of damaged material and insertion of a patch of the same size. Others seem to specifically be a bowtie/butterfly shape reinforcing a crack in wood. For instance, both of these images are being referred to as dutchman patches: ![rectangular patch](https://i.stack.imgur.com/JFF6R.jpg) Source: <https://makezine.com/projects/dutchman-wood-repair/> ![hourglass-shaped patch](https://i.stack.imgur.com/4tdJJ.jpg) Source: <http://www.woodworkingtalk.com/f5/pre-dovetail-butterfly-dutchman-joints-question-36119/#post306942> So which is it? Is there a difference between a dutchman patch and a butterfly patch? Is this just a case of the same phrase meaning two different things? Is a dutchman a general term and the buttefly specifically that *shape* of dutchman?
> > So which is it? Is there a difference between a dutchman patch and a butterfly patch? > > > Yes and no. A Dutchman can be the shape of a butterfly (also called a bowtie) as well as many other shapes. But a butterfly *in modern usage* typically means a wooden fixing to secure or stabilise a crack. This is yet another example (of many!) of terminology being used loosely or irregularly in woodworking. Note: Dutchmen patches are usually thin, and can in fact be made from veneer, butterflies or bowties are typically thick because of their structural requirement.
143028
I'm trying to checkout a submodule from another project in azure devops. ``` steps: - checkout: self submodules: true persistCredentials: true clean: true ``` Checking out another repository in the same project works. **GOAL** Add as submodule REPOSITORY A in REPOSITORY B. [![Projects](https://i.stack.imgur.com/GAEC0.png)](https://i.stack.imgur.com/GAEC0.png) However i get the error: ``` Cloning into 'E:/build/Agent5/_work/16/s/.azuredevops'... fatal: could not read Username for 'https://dev.azure.com': terminal prompts disabled fatal: clone of 'https://dev.azure.com/ORGANIZATION/PROJECTA/_git/REPOSITORYA' into submodule path 'E:/build/Agent5/_work/16/s/.azuredevops' failed ``` How can i achieve this using YAML in Azure DevOps Repositories?
When adding a submodule i found out that the url in the .gitmodules were not correct. ``` path = .azuredevops url = https://dev.azure.com/ORGANIZATION/PROJECTA/_git/REPOSITORYA ``` Should be: ``` path = .azuredevops url = https://ORGANIZATION@dev.azure.com/ORGANIZATION/PROJECTA/_git/REPOSITORYA ```
143134
I have code that searches for all users in a department: ``` string Department = "Billing"; DirectorySearcher LdapSearcher = new DirectorySearcher(); LdapSearcher.PropertiesToLoad.Add("displayName"); LdapSearcher.PropertiesToLoad.Add("cn"); LdapSearcher.PropertiesToLoad.Add("department"); LdapSearcher.PropertiesToLoad.Add("title"); LdapSearcher.PropertiesToLoad.Add("memberOf"); LdapSearcher.Filter = string.Format("(&(objectClass=user)(department={0}))", Department); SearchResultCollection src = LdapSearcher.FindAll(); ``` What would the filter need to look like if I only wanted everyone in the "Manager Read Only" AD Group? Am I going about this all wrong?
I've always found [Howto: (Almost) Everything In Active Directory via C#](http://www.codeproject.com/KB/system/everythingInAD.aspx) helps for most AD questions.
143559
In my code here, I consume WCF rest using dataGridView, and by the code below, I want to filter conditions to show only events in last 5 days, so I need to add filter in the link, but I don't know how. My problem : \* how add filter to show event last 5 days. My code: ``` public void button1_Click(object sender, EventArgs e) { try { dataGridView1.DataSource = GetRESTData("http://localhost:55495/EventService.svc/GetAllEvents"); } catch (WebException webex) { MessageBox.Show("Es gab so ein Schlamassel! ({0})", webex.Message); } } private JArray GetRESTData(string uri) { var webRequest = (HttpWebRequest)WebRequest.Create(uri); var webResponse = (HttpWebResponse)webRequest.GetResponse(); var reader = new StreamReader(webResponse.GetResponseStream()); string s = reader.ReadToEnd(); return JsonConvert.DeserializeObject<JArray>(s); } ``` Image of dataGridView [![enter image description here](https://i.stack.imgur.com/W2z8Z.png)](https://i.stack.imgur.com/W2z8Z.png)
If you can see the inside of the array you can use linq to filter I think your best bat would be to create a class and bind it to class but you can try this ``` JObject eventob= JObject.Parse(s); var events = (from p in (JArray)eventob["ParentObjectYouHave"] orderby (DateTime?)p.["Start_Date"] descending select p).Take(5); ```
143813
So i am building a personal website and am using Materialize for web designing. At first it was good and my pages look good, but then I added some new pages and i found that the css is not applied in these new pages, can anybody help me in solving this. Actually both are same pages(categories.html) but the path are different. header.html (main html file, have not changed the name yet) ``` <<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="static/main/materialize.css" media="screen,projection"/> </head> <body> {% load static %} {% include "main/includes/navbar.html" %} {% include "main/includes/messages.html" %} <main> <div style="background-image: url('https://www.google.com/url?sa=i&url=https%3A%2F%2Fwallpapersafari.com%2Fw%2FcU6JWo&psig=AOvVaw1eBAulQvnXOrIK1yQueVX5&ust=1623841457736000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCPje9_--mfECFQAAAAAdAAAAABAD')"> <div class = "container"> <br> {% block content %} {% endblock %} </div> </div> </main> {% include "main/includes/footer.html" %} <script type="text/javascript" src="static/main/materialize.js"></script> </body> </html> ``` views.py ``` from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Item, ItemSeries, ItemCategory from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm def single_slug(request, single_slug): categories = [c.category_slug for c in ItemCategory.objects.all()] if single_slug in categories: matching_series = ItemSeries.objects.filter(item_category__category_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Item.objects.filter(item_series__item_series=m.item_series).earliest("item_update") series_urls[m] = part_one.item_slug return render(request, "main/category.html", {"part_ones": series_urls}) items = [c.item_slug for c in Item.objects.all()] if single_slug in items: this_item = Item.objects.get(item_slug=single_slug) return render(request, "main/item.html", {"item":this_item}) return HttpResponse(f"{single_slug} does not correspond to anything.") def product(request): return render(request = request, template_name = "main/categories.html", context ={"categories": ItemCategory.objects.all}) def homepage(request): return render(request = request, template_name = "main/categories.html", context ={"categories": ItemCategory.objects.all}) def about(request): return render(request = request, template_name = "main/about.html", context ={"categories": ItemCategory.objects.all}) def contact(request): return render(request = request, template_name = "main/contact.html", context ={"categories": ItemCategory.objects.all}) def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, f"New Account Created: {username}") login(request, user) messages.info(request, f"You are now logged in as: {username}") return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") form = NewUserForm return render(request, "main/register.html", context = {"form": form}) def logout_request(request): logout(request) messages.info(request, "Logged out successfully!") return redirect("main:homepage") def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data = request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username = username, password = password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as: {username}") return redirect("main:homepage") else: messages.error(request, "Invalid username or password") else: messages.error(request, "Invalid username or password") form = AuthenticationForm() return render(request, "main/login.html", {"form": form}) ``` navbar.html ``` {% load static %} <!-- Dropdown Structure --> <ul id='dropdown1' class='dropdown-content'> <li><a href="#!">one</a></li> <li><a href="#!">two</a></li> <li class="divider" tabindex="-1"></li> <li><a href="#!">three</a></li> <li><a href="#!"><i class="material-icons">view_module</i>four</a></li> <li><a href="#!"><i class="material-icons">cloud</i>five</a></li> </ul> <nav> <div id="nav-wrapper"> <div> <ul class="center hide-on-med-and-down"> <li> <a href="">Home</a> </li> <li> <a href="about/">About Us</a> </li> <li> <a href="product/">Products</a> </li> <li> <a href="services/">Services</a> </li> <li> <a href="contact/">Contact</a> </li> <li> <a class='dropdown-trigger btn' href='#' data-target='dropdown1'>Drop Me!</a> </li> </ul> </div> </div> </nav> ``` categories.html ``` {% extends "main/header.html" %} {% block content %} <div class="row"> {% for cat in categories %} <div class="col s12 m6 l4"> <a href="{{cat.category_slug}}", style="color:#000"> <div class="card hoverable"> <div class="card-content"> <div class="card-title">{{cat.item_category}}</div> <p>{{cat.category_summary}}</p> </div> </div> </a> </div> {% endfor %} </div> {% endblock %} ``` [When CSS worked This is home page](https://i.stack.imgur.com/gR1UG.png) [When CSS did not work This is the same homepage after clicking 'about us' link form navbar](https://i.stack.imgur.com/31l49.png) I am stuck and don't know what to do next, any help would be appretiated.
Facebook Audience Network SDK in the app-level `build.gradle` file. ```js repositories { google() mavenCentral() } ... dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.gms:play-services-ads:20.2.0' implementation 'com.google.ads.mediation:facebook:6.5.1.0' } ... ``` Then, add a Network Security Configuration File location :- `res/xml/network_security_config.xml` ```js <?xml version="1.0" encoding="utf-8"?> <network-security-config> ... <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">127.0.0.1</domain> </domain-config> ... </network-security-config> ``` Then in your application manifest `AndroidManifest.xml`, add the configuration to your application attribute as follows: ```js <?xml version="1.0" encoding="utf-8"?> <manifest ... > <application android:networkSecurityConfig="@xml/network_security_config" ... > ... </application> </manifest> ```
144074
Whenever I boot, it show Plymouth then goes to a screen full of boot log, I -think- the only relevant part is `Starting Wait for Plymouth Boot Screen to Quit...es.ileged Tasks.s..p link was shut down...` (If someone know where this file is logged, I can upload it, I copied this by hand. Everything else is over SSH) It had been going to to this then low graphics mode with Nvidia drivers, and it booted properly without them, but after I messed around with I only get this. I can get to the terminal with `ctrl+alt+1`, so I tried to re-run lightdm, and I got this: ``` aidan@cinnabar:~$ sudo lightdm [sudo] password for aidan: /etc/modprobe.d is not a file /etc/modprobe.d is not a file /etc/modprobe.d is not a file /etc/modprobe.d is not a file update-alternatives: error: no alternatives for x86_64-linux-gnu_gfxcore_conf ``` These are the contents of modprobe.d: ``` aidan@cinnabar:~$ ls /etc/modprobe.d/ alsa-base.conf blacklist-framebuffer.conf blacklist-watchdog.conf iwlwifi.conf blacklist-ath_pci.conf blacklist-modem.conf dkms.conf mlx4.conf blacklist.conf blacklist-oss.conf fbdev-blacklist.conf vmwgfx-fbdev.conf blacklist-firewire.conf blacklist-rare-network.conf intel-microcode-blacklist.conf ``` I also tried to run `sudo service lightdm restart`, and it gave me `Job for lightdm.service failed. See "systemctl status lightdm.service" and "journalctl -xe" for details.` output of `systemctl status lightdm.service`: ``` aidan@cinnabar:~$ systemctl status lightdm.service ● lightdm.service - Light Display Manager Loaded: loaded (/lib/systemd/system/lightdm.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/display-manager.service.d └─xdiagnose.conf Active: failed (Result: start-limit) since Thu 2015-09-17 21:02:58 CDT; 1min 13s ago Docs: man:lightdm(1) Process: 2299 ExecStart=/usr/sbin/lightdm (code=exited, status=1/FAILURE) Process: 2294 ExecStartPre=/bin/sh -c [ "$(basename $(cat /etc/X11/default-display-manager 2>/dev/null))" = "lightdm" ] (code=exited, status=0/SUCCESS) Main PID: 2299 (code=exited, status=1/FAILURE) Sep 17 21:02:58 cinnabar systemd[1]: lightdm.service failed. Sep 17 21:02:58 cinnabar systemd[1]: lightdm.service holdoff time over, scheduling restart. Sep 17 21:02:58 cinnabar systemd[1]: start request repeated too quickly for lightdm.service Sep 17 21:02:58 cinnabar systemd[1]: Failed to start Light Display Manager. Sep 17 21:02:58 cinnabar systemd[1]: Unit lightdm.service entered failed state. Sep 17 21:02:58 cinnabar systemd[1]: Triggering OnFailure= dependencies of lightdm.service. Sep 17 21:02:58 cinnabar systemd[1]: lightdm.service failed. ``` [Output of `journalctl -xe` on pastebin here.](http://pastebin.com/i4QPaynV) I'm happy to provide anything else! If anyone know's whats wrong, i'd be really grateful. Machine: * MSI GE70 2PE Apache Pro * Nvidia 860M
For me the analisis of: "cat /var/log/lightdm/x-0-greeter.log" showed that I had to create the lightdm directory. It was missing. After running the following commands I fixed my machine. ``` mkdir -p /var/lib/lightdm chown -R lightdm:lightdm /var/lib/lightdm chmod 0750 /var/lib/lightdm ```
144338
I am using Maven 3, FlyWay and Oracle in a java application. I am trying to call an Oracle procedure from my sql script. The file is called `V1.0.0__test.sql`, and contents are: ``` execute pkg_test.pr_do_task('TEST_VALUE'); ``` Is the correct format? I only get a generic error when I run ``` mvn -P DEV clean compile flyway:migrate ``` Which is: ``` [ERROR] Failed to execute goal com.googlecode.flyway:flyway-maven-plugin:2.0.3:migrate (default-cli) on project bambi-ex man-sql: Flyway Error: com.googlecode.flyway.core.api.FlywayException: Migration to version 4.0.0 failed! Please restore backups and roll back database and code! -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal com.googlecode.flyway:flyway-maven-plugin :2.0.3:migrate (default-cli) on project bambi-exman-sql: Flyway Error: com.googlecode.flyway.core.api.FlywayException: M igration to version 4.0.0 failed! Please restore backups and roll back database and code! at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196) at org.apache.maven.cli.MavenCli.main(MavenCli.java:141) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352) Caused by: org.apache.maven.plugin.MojoExecutionException: Flyway Error: com.googlecode.flyway.core.api.FlywayException: Migration to version 4.0.0 failed! Please restore backups and roll back database and code! at com.googlecode.flyway.maven.AbstractFlywayMojo.execute(AbstractFlywayMojo.java:200) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209) ... 19 more Caused by: com.googlecode.flyway.core.api.FlywayException: Migration to version 4.0.0 failed! Please restore backups and roll back database and code! at com.googlecode.flyway.core.migration.DbMigrator.migrate(DbMigrator.java:186) at com.googlecode.flyway.core.Flyway$1.execute(Flyway.java:856) at com.googlecode.flyway.core.Flyway$1.execute(Flyway.java:820) at com.googlecode.flyway.core.Flyway.execute(Flyway.java:1259) at com.googlecode.flyway.core.Flyway.migrate(Flyway.java:820) at com.googlecode.flyway.maven.MigrateMojo.doExecuteWithMigrationConfig(MigrateMojo.java:159) at com.googlecode.flyway.maven.AbstractMigrationLoadingMojo.doExecute(AbstractMigrationLoadingMojo.java:162) at com.googlecode.flyway.maven.AbstractFlywayMojo.execute(AbstractFlywayMojo.java:191) ... 21 more ``` I cant seem to get the full stack trace. Thanks
``` Try this, begin pkg_test.pr_do_task('TEST_VALUE'); end; / ```
144455
I have a table like this: ``` -------------------------------------------- | Job | Class | Employee | PayType | Hours | | 212 A John 1 20 | | 212 A John 2 10 | | 911 C Rebekah 1 15 | | 911 C Rebekah 2 10 | -------------------------------------------- ``` I want to convert this table so i can get following output ``` ------------------------------------ | Job | Class | Employee | OT | ST | | 212 | A | John | 20 | 10 | | 911 | C | Rebekah | 15 | 10 | ------------------------------------ ``` Here I've set 1 for OT and 2 for ST
You can conditional aggregation: ``` select job, class, employee sum(case when paytype = 1 then hours else 0 end) ot, sum(case when paytype = 2 then hours else 0 end) st from mytable group by jobs, class, employee ```
144603
I want to use a TikZ element to place absolutely on the page. Unfortunately, no matter what I do, the TikZ picture is treated like a character, which causes it to be treated like a paragraph when not placed in another paragraph. I am aware of the following question, but their solutions do not work here (unless I missed something): * [How to draw a TikZ diagram that does not occupy space](https://tex.stackexchange.com/q/167561/28608) * [Reduce white space around TikZ picture?](https://tex.stackexchange.com/q/95649/28608) ### Minimal example ``` \documentclass{article} \usepackage{tikz} \begin{document} \section{Some section} \subsection{Some subsection}% \tikz[remember picture,overlay,baseline]{\node at (current page.center){bla};}% \begin{quote} This text has too much distance to the subsection heading. \end{quote} \end{document} ``` [![Output of minimal example](https://i.stack.imgur.com/fSHsk.png)](https://i.stack.imgur.com/fSHsk.png) Note the big gap before the text. It disappears if I remove the TikZ command. (The text “bla” placed by TikZ is not visible in the example, but it is not of concern here.) Of course, in this minimal example, I could just place the TikZ picture after the quote, but my actual situation is more complex, involving some macros and similar, which makes moving the TikZ command no generally applicable solution. If it helps, just imagine that the entire `quote` environment is dynamically via `\input` and the `\section` and `\subsection` commands must not be touched.
It also works completely without `hyperref`. You first have to declare a `\newcounter` in the preamble. Then, instead of setting the PDF page labels at the first numbering change, you set the counter. You then set the PDF page labels at the second numbering change, using the counter's value for the start of the second entry. ``` \documentclass{report} \pagenumbering{Alph} \newcounter{lastAlphpage} \begin{document} \chapter{chap1} Bla bla bla \clearpage % Set your counter at the space between \clearpage and \pagenumbering \setcounter{lastAlphpage}{\value{page}} \pagenumbering{Roman} \chapter{chap2} bla bla bla \clearpage % Using Heiko Oberdiek's solution from the other thread: % Best place at the start of the Arabic numbered pages % after \cleardoublepage and before the page number is % reset in \pagenumbering{arabic}. \pdfcatalog{% /PageLabels<<% /Nums[% % Page numbers are zero based. % Alphabetic numbers starting with first page. 0<</S/A>>% % Roman numbers starting with the page saved in the counter. \the\numexpr\value{lastAlphpage}-1\relax<</S/R>>% % Arabic numbers starting with current page. % Don't forget to add the counter. \value{page} contains the % current "roman" page number. You have to subtract two because % each of the values include one page "too much". \the\numexpr(\value{lastAlphpage}+\value{page})-2\relax<</S/D>>% ]% >>% } \pagenumbering{arabic} \chapter{chap3} bla bla bla \end{document} ``` (This used [this answer](https://tex.stackexchange.com/a/247692/96537) by Heiko Oberdiek)
144700
I manage a server with Plesk 12.5 since a couple of years. Everything (emails, websites, etc.) works perfectly with our main domain (let's call it **myfirstdomain.com**). Since a couple of weeks, I added a new domain (let's cal it **myseconddomain.fr**) and everything seems to work too (emails and websites), except the following error: when a sender sends an email to us, he receives the following error after 5 days: ``` This is the mail system at host myfirstdomain.com. I'm sorry to have to inform you that your message could not be delivered to one or more recipients. It's attached below. For further assistance, please send mail to postmaster. If you do so, please include this problem report. You can delete your own text from the attached returned message. The mail system <fabrice@myseconddomain.fr>: Message can not be delivered at this time Reporting-MTA: dns; myfirstdomain.com X-Postfix-Queue-ID: DC0B1702585 X-Postfix-Sender: rfc822; xxx@xxx.net Arrival-Date: Tue, 5 Mar 2019 21:18:00 +0100 (CET) Final-Recipient: rfc822; fabrice@myseconddomain.fr Original-Recipient: rfc822;fabrice@myseconddomain.fr Action: failed Status: 4.2.1 Diagnostic-Code: x-unix; Message can not be delivered at this time De: XXX XXX <xxx@uxxxvi.net> Objet: Testing title Date: 5 mars 2019 à 21:17:58 UTC+1 À: Fabrice Troilo <fabrice@myseconddomain.fr> Testing body ``` You can see that the reporting-MTA is myfirstdomain.com, so maybe there is confusion between the two domains? Here is our SPF: ``` "v=spf1 a mx include:_spf.google.com ip4:XX.XX.XX.XX ~all" ``` I will try with this update for the two domains: ``` "v=spf1 +a +mx +a:myfirstdomain.com +a:myseconddomain.fr include:_spf.google.com ip4:62.210.16.40 ~all " ``` Also, the email address is simply forwarding to a gmail address. Do you please have any clue to look at?
If you can send mail from the domain, but not receive it, it's not related to SPF. SPF authenticates when you send mail, not receive it. Have you ensured that an MX record is set up for the secondary domain? You can test this using the terminal on Linux or macOS with `host -t MX myseconddomain.fr` If you are on Windows, then open a command prompt, type `nslookup`. Then when in nslookup, switch to query MX types with `set q=mx` and press enter. Then enter your domain `myseconddomain.fr`and press enter. If the MX records looks correct, then it must be some configuration in Plesk. We can test this by trying to deliver mail ourselves with `telnet`. Open a terminal/command prompt and type `telnet <myserverIP> 25` and press enter. This connects to your mailserver. It should respond with a line beginning with 220, and it's hostname. Then you can try and deliver a simple test mail, let's say from account1@example.net ``` EHLO example.NET MAIL FROM:<account1@example.net> RCPT TO:<fabrice@myseconddomain.fr> DATA This is a test email. To test delivery. . QUIT ``` The first few lines introduces yourself, sender and receiver to the mail server. `DATA` indicates you want to start the body of your email. And the period on a line by itself indicates that you are done with the body. QUIT then terminates the connection. Then watch what your server says in reply to each command. If you can successfully deliver this way, then it's like a problem with your MX record.
145613
This is my iptables script which i run in bash. The saving of the configurations is part of the script. ``` #!/bin/bash # # iptables-konfigurasjon # # Set default rule to ACCEPT to avoid being locked out iptables -P INPUT ACCEPT # Flush all excisting rules iptables -F # New default rules iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT # localhost: iptables -A INPUT -i lo -j ACCEPT # Not entirely shure what this is about....: iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Allow SSH. iptables -A INPUT -p tcp --dport 22 -j ACCEPT # Allow http traffic for tomcat: iptables -A INPUT -p tcp --dport 8080 -j ACCEPT # Save rules: /sbin/service iptables save ``` But, after testing it seems that these rules have no effect after all. Example: If I comment out the line for allowing traffic to my tomcat server, I can still reach my tomcat server from outside.... even after a reboot. What's wrong with my script? BTW: I'm using CentOS 6.
// For what its worth, this works on CentOS 6.5 php 5.3.3. ``` $fname = "/dev/null"; if(file_exists($fname)) print "*** /dev/null exists ***\n"; if (is_readable($fname)) print "*** /dev/null readable ***\n"; if (is_writable($fname)) print "*** /dev/null writable ***\n"; if (($fileDesc = fopen($fname, "r"))==TRUE){ print "*** I opened /dev/null for reading ***\n"; $x = fgetc($fileDesc); fclose($fileDesc); } if (($fileDesc = fopen($fname, "w"))==TRUE) { print "*** I opened /dev/null for writing ***\n"; $x = fwrite($fileDesc,'X'); fclose($fileDesc); } if (($fileDesc = fopen($fname, "w+"))==TRUE) { print "*** I opened /dev/null for append ***\n"; $x = fwrite($fileDesc,'X'); fclose($fileDesc); } ```
146106
I'm using wkhtmltopdf to download a webpage as pdf. But the css property letter-spacing seems doesn't work ``` font-size:20px; letter-spacing:0px; ``` [![enter image description here](https://i.stack.imgur.com/ctswV.png)](https://i.stack.imgur.com/ctswV.png) ``` font-size:20px; letter-spacing:1px; ``` [![enter image description here](https://i.stack.imgur.com/gERqK.png)](https://i.stack.imgur.com/gERqK.png) The spacing is very large for 1px... I tried with 2 differents font-family
in the CSS add the Following Code for Body ```css body { font-kerning: normal; text-rendering: optimizeLegibility; } ``` and the --dpi 200. This Worked for Me.
146177
I have a private Go repo at `https://github.com/myorg/myrepo` that is used by another Go repo and defined in `go.mod`. When I try to run `$ go mod tidy` to download all the dependencies, it returns me the following error: ``` go: github.com/myorg/myrepo@v0.10.1: reading github.com/myorg/myrepo/go.mod at revision v0.10.1: unknown revision v0.10.1 ``` The same thing happens when I try to "go get" this module. **What have I tried so far?** * Set my git config to use SSH: `git config --global url.git@github.com:.insteadOf https://github.com/` * Set the `GOPRIVATE` env var: `export GOPRIVATE=github.com/myorg/*` Refer: <https://stackoverflow.com/a/27501039/4927751> I have been stuck with this for a day now and would highly appreciate if someone can suggest me ways to fix this.
Finally resolved this thanks to a colleague. **Issue**: Local module caching in Go - not sure how its managed internally by the `go` tool. **Solution**: 1. Delete the `($GOPATH)/pkg/mod/cache` repo. 2. Reinstall the dependencies.
146217
> > ### The issue is with Internet Explorer 8 and below. Have found a decent working solution. > > > ### Issue Internet Explorer 8 and below is not triggering `click()` event set by jQuery (or even may be inline, not sure) on `<input />` elements, which have CSS property, `display` set to `none`. It works in Internet Explorer 9, Mozilla Firefox, and Google Chrome. Weird. This is how the code is and is there any work-around for Internet Explorer 8 and below? ### Context The `input` to be clicked is given a style `display: none;`. And the function is given in the `click` event of the `input`. Since the whole stuff is inside the `label`, it triggers the `click` event on the `input` when the `label` clicked. You can take this as some kind of pretty selector, hiding the `input`. The `label` implicitly transfers the `click` event to the first `input` by default, and that is what I wanna use it here. I don't want the users to see the ugly `input` here. Expected browser behaviour, but not working. ### HTML ``` <ul> <li> <label> <input type="button" value="Button 1" /> Hello! This is a list item #1. </label> </li> <li> <label> <input type="button" value="Button 2" /> Hello! This is a list item #2. </label> </li> <li> <label> <input type="button" value="Button 3" /> Hello! This is a list item #3. </label> </li> </ul>​ ``` ### The Exact CSS which caused the Issue ``` ul li, ul li label {display: block; padding: 5px; cursor: pointer;} ul li label input {display: none;} ul li {border-bottom: 1px solid #ccc;} ul li:hover {background-color: #eee;}​ ``` ### JavaScript ``` $(document).ready(function(){ $("input").click(function(){ alert("Hey you! " + $(this).attr("value")); }); });​ ``` ### Fiddle: <http://jsfiddle.net/qSYuP/> --- ### Update #1: Tried giving `for` attribute: ``` <label for="btn1"> <input type="button" value="Button 1" id="btn1" /> ``` Still doesn't work! --- ### Update #2: Tried CSS `visibility: hidden;`: ``` ul li label input {visibility: hidden;} ``` Breaks layout. But, still doesn't work! --- ### Update #3: Tried CSS `position: absolute;`: ``` ul li label {overflow: hidden;} ul li label input {position: absolute; left: -99em;} ``` **Works!** I am not in a position to use `overflow: hidden;`, seriously caught! --- ### Update #4: Manually triggering the `click()` function: ``` $(document).ready(function(){ $("input").click(function(){ console.log("Hey you! " + $(this).attr("value")); }); $("label").click(function(){ $(this).find("input").click(); }); }); ``` Well, IE 8 goes out of stack after printing `LOG: Hey you! Button 3` for **1209** times! ``` LOG: Hey you! Button 3 LOG: Hey you! Button 3 LOG: Hey you! Button 3 LOG: Hey you! Button 3 LOG: Hey you! Button 3 SCRIPT28: Out of stack space ``` **Works Infinitely!** Should be an issue with my script! --- ### Solution: Kind of crappy fix, but did the trick! Since it is because IE 8, which supports `opacity`, I had to use `display: inline-block;` with `opacity: 0;`. ``` ul li label input { opacity: 0; width: 0px; height: 0px; display: inline-block; padding: 0; margin: 0; border: 0; } ``` Now the `input`'s box is hidden, literally. This fix is only for IE 8! Had to fix using the **IE 8 and below Hack**: ``` ul li label input { opacity: 0\9; width: 0px\9; height: 0px\9; display: inline-block\9; padding: 0\9; margin: 0\9; border: 0\9; } ``` ### Fiddle: <http://jsfiddle.net/VSQbD/>
I think this is pretty straightforward. You just have to use click handlers on visible items. If you want a click on the `<label>` or the `<li>` to work when the `<input>` object is hidden and you want it to work in all browsers, then you just need to put a click handler on either the `<label>` or the `<li>` because that is a visible object that will receive the click when the `<input>` is hidden.
146274
![enter image description here](https://i.stack.imgur.com/KBct9.png) I am getting error as > > The type org.hamcrest.Matcher cannot be resolved. It is indirectly referenced from required .class files > > > for Rest Assured Api Testing .
Download the jar from below link and place it in project build path <https://mvnrepository.com/artifact/org.hamcrest/hamcrest-all/1.3> This worked for me.
146401
I want to represent model data as different images using Angular but having some trouble finding the "right" way to do it. The Angular [API docs on expressions](http://docs.angularjs.org/guide/expression) say that conditional expressions are not allowed... Simplifying a lot, the model data is fetched via AJAX and shows you the status of each interface on a router. Something like: ``` $scope.interfaces = ["UP", "DOWN", "UP", "UP", "UP", "UP", "DOWN"] ``` So, in Angular, we can display the state of each interface with something like: ``` <ul> <li ng-repeat=interface in interfaces>{{interface}} </ul> ``` BUT - Instead of the values from the model, I'd like to show a suitable image. Something following this general idea. ``` <ul> <li ng-repeat=interface in interfaces> {{if interface=="UP"}} <img src='green-checkmark.png'> {{else}} <img src='big-black-X.png'> {{/if}} </ul> ``` *(I think Ember supports this type of construct)* Of course, I could modify the controller to return image URLs based on the actual model data but that seems to violate the separation of model and view, no? [This SO Posting](https://stackoverflow.com/questions/13781685/angularjs-ng-src-equivalent-for-background-imageurl/13782311#13782311) suggested using a directive to change the bg-img source. But then we are back to putting URLs in the JS not the template... All suggestions appreciated. Thanks. *please excuse any typos*
Instead of `src` you need `ng-src`. AngularJS views support binary operators ``` condition && true || false ``` So your `img` tag would look like this ``` <img ng-src="{{interface == 'UP' && 'green-checkmark.png' || 'big-black-X.png'}}"/> ``` **Note** : the quotes (ie 'green-checkmark.png') are important here. It won't work without quotes. [plunker here](http://plnkr.co/edit/vwNAE3tQxE6VzO0TLDsk?p=preview) *(open dev tools to see the produced HTML)*
146707
In using the new `Html.EnumDropDownListFor` extension method in MVC 5.1, I'm running into a problem where the selected value isn't updating in the drop down based on the route attribute I'm passing to my controller action. **View** ``` @model MemberReconWebDemo.Models.EnvironmentsModel @{ ViewBag.Title = "Environments"; } <h2>Environments</h2> <div class="row"> <div class="col-md-12"> @Html.EnumDropDownListFor(p => p.Environment) @Model.Environment.ToString() </div> </div> ``` **Controller Action** ``` [Route("environments/{environment?}")] public ActionResult Environments(string environment) { Domain.Environment env; Enum.TryParse(environment, true, out env); return View(new EnvironmentsModel{Environment = env}); } ``` If I navigate to the route without the optional attribute and I have the `Model.Environment` property set to a static value in the controller action, that selected value shows without issue. If I pass in a valid route attribute value, assign that to the `Model.Environment` property, the drop down isn't updated to the property value upon rendering--even though I've confirmed that the property does have a value other than the default enum value.
I too encountered this problem today. Renaming the routes parameter to a name different from the models property worked for me. **Controller Action** ``` [Route("environments/{envparm?}")] public ActionResult Environments(string envparam) { Domain.Environment env; Enum.TryParse(envparam, true, out env); return View(new EnvironmentsModel{Environment = env}); } ```
146751
I have an array of Id' and i need to get the details for each of them. i currently have this. ``` const redis = require('redis'); const redisClient = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST); const arrayList = [ { id: 3444 }, { id: 3555 }, { id: 543666 }, { id: 12333 }, ]; async function getDetails(element) { await redisClient.hgetall(element.id, (err, user) => { if (err) { console.log('Something went wrong'); // Handle Error return err; } console.log('Done for User'); return user; }); } arrayList.forEach((element) => { console.log('element'); await getDetails(element).then((res) => { // Do Something with response for each element }); }); ``` This is the response i get right now. its not async. What am i doing wrong please. ``` element element element element Done for User Done for User Done for User Done for User ```
Take a look at `NuGet.Build.Tasks.Pack` You can use a .nuspec file to pack your project if you reference at `NuGet.Build.Tasks.Pack`. I've done this to roll up multiple projects in my solution into one nuget package. You can pack with `dotnet.exe`: `dotnet pack <path to .csproj file> /p:NuspecFile=<path to nuspec file> /p:NuspecProperties=<> /p:NuspecBasePath=<Base path>` Or MSBuild: `msbuild /t:pack <path to .csproj file> /p:NuspecFile=<path to nuspec file> /p:NuspecProperties=<> /p:NuspecBasePath=<Base path>` More details can be found here: <https://learn.microsoft.com/en-us/nuget/reference/msbuild-targets#packing-using-a-nuspec>
147426
I'm trying to write a script that highlights everything on a webpage that matches the input to a search box whilst ignoring case in the search for matches. My html page looks like - ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Index Page</title> <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">--> <!-- Bootstrap core CSS --> <link href="Content/bootstrap.min.css" rel="stylesheet"> <!-- Your custom styles (optional) --> <link href="Content/style.css" rel="stylesheet"> <!-- custom javascript --> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.quicksearch/2.3.1/jquery.quicksearch.js"></script> <script src="Scripts/script.js"></script> </head> <body> <!--Main Navigation--> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" id="txt_query" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </nav> </header> <!--Main Navigation--> <div class="container-fluid"> <div class="searchable"> Hello <div> test1 </div> <div> test2 </div> <div> Test3 <div> teest4 </div> </div> </div> </div> </body> </html> ``` And the javascript (JQuery) code is - ``` $(function () { $('input#txt_query').on('input', function () { if (this.value !== null) { var search_value = this.value; var search_regexp; if (this.value !== "") { search_regexp = new RegExp(search_value + "+(?![^<]*\>)", "gi"); } $('.searchable').each(function () { $(this).find('*').each(function () { if ($(this).data('old-state') == null) { $(this).data('old-state', $(this).html()); } if (this.value !== "") { var html = $(this).data('old-state').replace(search_regexp, "<span class = 'highlight'>" + search_value + "</span>"); //alert(html); $(this).html(html); } }); }); } }); }); ``` And the CSS to highlight the word is - ``` .highlight { font-weight: bold; color: green; } ``` This currently has 2 problems. 1. Where matching terms are adjacent, the items are treated as a single item. So when searching for 'e', the 'ee' gets replaced with a highlighted 'e'. 2. A search for 't' finds the capital 'T' but replaces it with a highlighted 't' (small t). I think both problems could be solved by modification of the following line of code: ``` var html = $(this).data('old-state').replace( search_regexp, "<span class = 'highlight'>" + search_value + "</span>" ); ``` Instead of 'search\_value' I'd like to use the text found by the regex pattern, but I don't know how to access that text.
Try [replace callback function](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) to capture matches and replace with it so `e` become `ee` and `t` keep original case or `T` ``` var html = $(this).data('old-state').replace(search_regexp, function(match, contents, offset) { return "<span class = 'highlight'>" + match + "</span>"; }); ``` demo: ```js $(function() { $('input#txt_query').on('input', function() { if (this.value !== null) { var search_value = this.value; var search_regexp; if (this.value !== "") { search_regexp = new RegExp(search_value + "+(?![^<]*\>)", "gi"); } $('.searchable').each(function() { $(this).find('*').each(function() { if ($(this).data('old-state') == null) { $(this).data('old-state', $(this).html()); } if (this.value !== "") { var html = $(this).data('old-state').replace(search_regexp, function(match, contents, offset) { return "<span class = 'highlight'>" + match + "</span>"; }); //alert(html); $(this).html(html); } }); }); } }); }); ``` ```css .highlight {font-weight: bold;color: green;} .searchable {font-size: 24px} ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="txt_query" type="search"> <div class="container-fluid"> <div class="searchable"> Hello <div> test1 </div> <div> test2 </div> <div> Test3 <div> teest4 </div> </div> </div> </div> ```
147850
I trie to get the documents stored with a message in the message\_document table with a doctrine request but the request loops and ends up filling my memory I tried the same request with sql on Dbeaver and it runs with no problem great thanks for your help My message.php `enter code here`<?php ``` namespace App\Entity; use DateTime; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use App\Repository\MessageRepository; use Doctrine\Common\Collections\ArrayCollection; /** * @ORM\Entity(repositoryClass=MessageRepository::class) */ class Message { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="text") */ private $content; /** * @ORM\Column(type="datetime") */ private $createdAt; /** * @ORM\ManyToOne(targetEntity=Conversation::class, inversedBy="messages") */ private $conversation; /** * @ORM\ManyToOne(targetEntity=User::class, inversedBy="messages") */ private $user; /** * @ORM\OneToMany(targetEntity=MessageDocument::class, mappedBy="messages") */ private $messageDocuments; public function __construct( string $content, User $user, Conversation $converstation) { $this->content = $content; $this->user = $user; $this->conversation = $converstation; $this->createdAt = new \DateTime('now'); $this->messageDocuments = new ArrayCollection(); } public function getId():?int { return $this->id; } public function getContent():?string { return $this->content; } public function setContent(string $content):self { $this->content = $content; return $this; } public function getCreatedAt():?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt):self { $this->createdAt = $createdAt; return $this; } public function getConversation():?Conversation { return $this->conversation; } public function setConversation(?Conversation $conversation):self { $this->conversation = $conversation; return $this; } public function getUser():?User { return $this->user; } public function setUser(?User $user):self { $this->user = $user; return $this; } /** * @return Collection|MessageDocument[] */ public function getMessageDocuments(): Collection { return $this->messageDocuments; } public function addMessageDocument(MessageDocument $messageDocument): self { if (!$this->messageDocuments->contains($messageDocument)) { $this->messageDocuments[] = $messageDocument; $messageDocument->setMessages($this); } return $this; } public function removeMessageDocument(MessageDocument $messageDocument): self { if ($this->messageDocuments->removeElement($messageDocument)) { // set the owning side to null (unless already changed) if ($messageDocument->getMessages() === $this) { $messageDocument->setMessages(null); } } return $this; } } ``` my MessageDocument.php `enter code here`<?php ``` namespace App\Entity; use App\Repository\MessageDocumentRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=MessageDocumentRepository::class) */ class MessageDocument { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $fileName; /** * @ORM\Column(type="datetime") */ private $updatedAt; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $type; /** * @ORM\ManyToOne(targetEntity=Message::class, inversedBy="messageDocuments") */ private $message; /** * @ORM\ManyToOne(targetEntity=User::class, inversedBy="messageDocuments") */ private $sender; public function getId(): ?int { return $this->id; } public function getFileName(): ?string { return $this->fileName; } public function setFileName(string $fileName): self { $this->fileName = $fileName; return $this; } public function getUpdatedAt(): ?\DateTimeInterface { return $this->updatedAt; } public function setUpdatedAt(\DateTimeInterface $updatedAt): self { $this->updatedAt = $updatedAt; return $this; } public function getType(): ?string { return $this->type; } public function setType(?string $type): self { $this->type = $type; return $this; } public function getMessage(): ?Message { return $this->message; } public function setMessage(?Message $message): self { $this->message = $message; return $this; } public function getSender(): ?User { return $this->sender; } public function setSender(?User $sender): self { $this->sender = $sender; return $this; } } ``` the request on MessageDocument join Message ``` /** * @return MessageDocument[] Returns an array of MessageDocument objects */ //$qb->expr()->eq('md.id = :val') //,Join::WITH,$qb->expr()->eq('md.id = :val') public function findDocByMessageId($messageId) { return $this->createQueryBuilder('md') ->select('md') ->join('md.message','m') ->where('m.id =:val') ->setParameter('val', $messageId) ->setMaxResults(20) ->getQuery() ->getResult(); } ``` the calling of the repo request ``` $allMessages = new ArrayCollection(); $docs=[]; foreach ($messages as $messageUnique) { $messId = $messageUnique->getId(); $documentsMessages = $messageRepository->findDocByMessageId($messId); if($documentsMessages !== null){ foreach($documentsMessages as $document){ $docs=$document; } //$messageUnique->addMessageDocument($document); } $conversation->setLastMessage($messageUnique); $messageUnique = array( 'id' => $messageUnique->getId(), 'author' => $messageUnique->getUser()->getFullName(), 'authorId' => $messageUnique->getUser()->getId(), 'content' => $messageUnique->getContent(), 'createdAt' => $messageUnique->getCreatedAt() ); $allMessages->add($messageUnique); } ```
I have changed my code and now error message is about circular reference Message entity <?php ``` namespace App\Entity; use DateTime; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use App\Repository\MessageRepository; use Doctrine\Common\Collections\ArrayCollection; /** * @ORM\Entity(repositoryClass=MessageRepository::class) */ class Message { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="text") */ private $content; /** * @ORM\Column(type="datetime") */ private $createdAt; /** * @ORM\ManyToOne(targetEntity=Conversation::class, inversedBy="messages") */ private $conversation; /** * @ORM\ManyToOne(targetEntity=User::class, inversedBy="messages") */ private $user; /** * @ORM\OneToMany(targetEntity=MessageDocument::class, mappedBy="message") */ private $messageDocument; public function __construct( string $content, User $user, Conversation $converstation) { $this->content = $content; $this->user = $user; $this->conversation = $converstation; $this->createdAt = new \DateTime('now'); $this->messageDocuments = new ArrayCollection(); } public function getId():?int { return $this->id; } public function getContent():?string { return $this->content; } public function setContent(string $content):self { $this->content = $content; return $this; } public function getCreatedAt():?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt):self { $this->createdAt = $createdAt; return $this; } public function getConversation():?Conversation { return $this->conversation; } public function setConversation(?Conversation $conversation):self { $this->conversation = $conversation; return $this; } public function getUser():?User { return $this->user; } public function setUser(?User $user):self { $this->user = $user; return $this; } /** * @return Collection|MessageDocument[] */ public function getMessageDocument(): Collection { return $this->messageDocument; } public function addMessageDocument(MessageDocument $messageDocument): self { if (!$this->messageDocument->contains($messageDocument)) { $this->messageDocument[] = $messageDocument; $messageDocument->setMessages($this); } return $this; } public function removeMessageDocument(MessageDocument $messageDocument): self { if ($this->messageDocuments->removeElement($messageDocument)) { // set the owning side to null (unless already changed) if ($messageDocument->getMessages() === $this) { $messageDocument->setMessages(null); } } return $this; } } ``` MessageDocument entity ``` <?php namespace App\Entity; use App\Repository\MessageDocumentRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=MessageDocumentRepository::class) */ class MessageDocument { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $fileName; /** * @ORM\Column(type="datetime") */ private $updatedAt; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $type; /** * @ORM\ManyToOne(targetEntity=Message::class, inversedBy="messageDocument") */ private $message; /** * @ORM\ManyToOne(targetEntity=User::class, inversedBy="messageDocument") */ private $sender; public function getId(): ?int { return $this->id; } public function getFileName(): ?string { return $this->fileName; } public function setFileName(string $fileName): self { $this->fileName = $fileName; return $this; } public function getUpdatedAt(): ?\DateTimeInterface { return $this->updatedAt; } public function setUpdatedAt(\DateTimeInterface $updatedAt): self { $this->updatedAt = $updatedAt; return $this; } public function getType(): ?string { return $this->type; } public function setType(?string $type): self { $this->type = $type; return $this; } public function getMessage(): ?Message { return $this->message; } public function setMessage(?Message $message): self { $this->message = $message; return $this; } public function getSender(): ?User { return $this->sender; } public function setSender(?User $sender): self { $this->sender = $sender; return $this; } } ``` js use to call controller from twig ``` function getMessages(conversationId , userId) { superConversationId = conversationId; userIdEnCours = userId; //* On vide ce qu'il y avait avant removeAllChildNodes(document.querySelector('.msg_history')); //* On remet toutes les conversations en blanc let allDivs = document.getElementsByClassName('chat_list'); for (let div of allDivs) { div.style.background = '#f8f8f8'; } //* background-color light-grey quand conversation selectionné $("#"+ conversationId).css('background', "#e1e1e1") let xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { //si requête validé on traite la réponse if (this.readyState == 4 && this.status == 200) { let messages = JSON.parse(this.response); let discussion = document.querySelector('.msg_history'); for (let message of messages) { let dateMessage = new Date(message.createdAt) var lastMessageId = message.id; //* Affichage selon envoyé ou reçu if (message.authorId == userIdEnCours) { discussion.innerHTML += "<div class=\"outgoing_msg col-12 \"\><div class=\"sent_msg col-6 m-0\">" + "<p class='m-0'>" + message.content + "</p>" + "<span class=\"time_date\"> De " + message.author + " | " + dateMessage.toLocaleString() + "</span>" + "</div>" ; } else { discussion.innerHTML += "<div class=\"incoming_msg col-12 \">" + "<div class=\"received_msg col-12\"\><div class=\"received_withd_msg col-6\">" + "<p>" + message.content + "</p>" + "<span class=\"time_date_receiver\"> De " + message.author + " | " + dateMessage.toLocaleString() + "</span>" + "</div></div>" ; } } //* scroll dernier message let divMessagerie = document.querySelector(".msg_history"); divMessagerie.scrollTop = divMessagerie.scrollHeight; //vl le 13/09 // ne voyant pas l'utilité ... /* Interval = setInterval( () => { $.ajax({ type: "POST", url : "/checkMessage/" + lastMessageId, success: function (response) { if (response === true) { clearInterval(Interval); getMessages( superConversationId, userIdEnCours ); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); } }); }, 5000); */ } }; //! Ouverture de la requete (MOCK VERS PROD) //* PROD // xmlhttp.open("GET", "http://www.generation-boomerang.com/messagerie/conv/" + conversationId); //* DEV xmlhttp.open("GET", "/messagerie/conv/" + conversationId); xmlhttp.send(); } ``` The controller to get the messages from a conversation ``` /** * @Route("/messagerie/conv/{id}" , name="messagerie_getMessagesOfConv") * @Security("is_granted('ROLE_ABONNE') or is_granted('ROLE_ADMIN')", message="Merci de vous abonner au portail pour bénéficier de cette super fonctionnalité !") */ public function getMessagesOfConv(int $id, EntityManagerInterface $entityManager, ConversationRepository $conversationRepository, ParticipantRepository $participantRepository,MessageDocumentRepository $messageRepository) { //* Récup du user + check à faire $userEncours = $this->getUser(); $userId = $userEncours->getId(); //* Ckeck si la conversation appartient bien au user $check = $participantRepository->checkBelongs($id, $userId); if ($check != 1) { return $this->json('cette conv ne te regarde pas !'); } $conversation = $conversationRepository->find($id); $messages = $conversation->getMessages(); // $documentsMessages = new ArrayCollection();//vl $allMessages = new ArrayCollection(); // $docs=; foreach ($messages as $messageUnique) { $messId = $messageUnique->getId(); $documentsMessages = $messageRepository->findDocByMessageId($messId); if($documentsMessages !== null){ foreach($documentsMessages as $document){ // $docs=$document; $messageUnique->addMessageDocument($document); } } $conversation->setLastMessage($messageUnique); $messageUnique = array( 'id' => $messageUnique->getId(), 'author' => $messageUnique->getUser()->getFullName(), 'authorId' => $messageUnique->getUser()->getId(), 'content' => $messageUnique->getContent(), 'createdAt' => $messageUnique->getCreatedAt(), 'messageDocuments'=>$messageUnique->getMessageDocument() ); $allMessages->add($messageUnique); } $entityManager->persist($conversation); $entityManager->flush(); //echo '<pre>'; var_dump( $conversation);exit;echo '</pre>';// return $this->json($allMessages); } ``` conversation entity ``` <?php namespace App\Entity; use App\Repository\ConversationRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=ConversationRepository::class) */ class Conversation { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\OneToOne(targetEntity=Message::class, cascade={"persist", "remove"}) */ private $lastMessage; /** * @ORM\OneToMany(targetEntity=Message::class, mappedBy="conversation") */ private $messages; /** * @ORM\OneToMany(targetEntity="Participant", mappedBy="conversation") */ private $participants; /** * @ORM\Column(type="string" , length=50) */ private $title; /** * @ORM\Column(type="datetime") */ private $createdAt; public function __construct() { $this->participants = new ArrayCollection(); $this->messages = new ArrayCollection(); $this->createdAt = new \DateTime('now'); } public function getId():?int { return $this->id; } public function getLastMessage():?Message { return $this->lastMessage; } public function setLastMessage(?Message $lastMessage):self { $this->lastMessage = $lastMessage; return $this; } /** * @return Collection|Message[] */ public function getMessages():Collection { return $this->messages; } public function addMessage(Message $message):self { if (!$this->messages->contains($message)) { $this->messages[] = $message; $message->setConversation($this); } return $this; } public function removeMessage(Message $message):self { if ($this->messages->contains($message)) { $this->messages->removeElement($message); // set the owning side to null (unless already changed) if ($message->getConversation() === $this) { $message->setConversation(null); } } return $this; } /** * @return Collection|Participant[] */ public function getParticipants():Collection { return $this->participants; } public function addParticipant(Participant $participant):self { if (!$this->participants->contains($participant)) { $this->participants[] = $participant; $participant->setConversation($this); } return $this; } public function removeParticipant(Participant $participant):self { if ($this->participants->contains($participant)) { $this->participants->removeElement($participant); // set the owning side to null (unless already changed) if ($participant->getConversation() === $this) { $participant->setConversation(null); } } return $this; } /** * Get the value of title */ public function getTitle() { return $this->title; } /** * Set the value of title * @return self */ public function setTitle($title) { $this->title = $title; return $this; } public function getCreatedAt():?\DateTimeInterface { return $this->createdAt; } public function setCreatedAt(\DateTimeInterface $createdAt):self { $this->createdAt = $createdAt; return $this; } } ``` and participant entity ``` <?php namespace App\Entity; use App\Repository\ParticipantRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=ParticipantRepository::class) */ class Participant { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\ManyToOne(targetEntity="User", inversedBy="participants") */ private $user; /** * @ORM\ManyToOne(targetEntity="Conversation", inversedBy="participants") */ private $conversation; private $messageReadAt; /** * Get the value of id */ public function getId() { return $this->id; } /** * Get the value of user */ public function getUser() { return $this->user; } /** * Set the value of user * * @return self */ public function setUser($user) { $this->user = $user; return $this; } /** * Get the value of conversation */ public function getConversation() { return $this->conversation; } /** * Set the value of conversation * * @return self */ public function setConversation($conversation) { $this->conversation = $conversation; return $this; } /** * Get the value of messageReadAt */ public function getMessageReadAt() { return $this->messageReadAt; } /** * Set the value of messageReadAt * * @return self */ public function setMessageReadAt($messageReadAt) { $this->messageReadAt = $messageReadAt; return $this; } } ``` there is also a CreateMessageHandler and GetMessageHanler (but I don't understand how it works) CreateMessageHandler <?php ``` namespace App\MessageHandler; use App\Entity\User; use App\Entity\Message; use App\Entity\Conversation; use App\Message\CreateMessage; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Messenger\Handler\MessageHandlerInterface; class CreateMessageHandler implements MessageHandlerInterface { private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } public function __invoke(CreateMessage $createMessage) { $conversation = $this->entityManager->getRepository(Conversation::class)->find($createMessage->getConversationId()); if(is_null($conversation)) { $conversation = new Conversation(); $this->entityManager->persist($conversation); $this->entityManager->flush(); } else { $message = new Message( $createMessage->getContent(), $this->entityManager->getRepository(User::class)->find($createMessage->getUserId()), $conversation, ); // if () } // Debug // echo $createMessage->getContent(); // echo $message->getUser()->getId(); // echo $message->getConversation()->getId(); $this->entityManager->persist($message); $this->entityManager->flush(); } } ``` GetMessageHandler <?php ``` namespace App\MessageHandler; use App\Entity\Message; use App\Message\GetMessages; use App\Repository\MessageRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Messenger\Handler\MessageHandlerInterface; class GetMessagesHandler implements MessageHandlerInterface { private $entityManager; private $messageRepository; public function __construct(EntityManagerInterface $entityManager, MessageRepository $messageRepository) { $this->entityManager = $entityManager; } public function __invoke(GetMessages $message) { //Récupérer les messages de la conversation return $this->entityManager->getRepository(Message::class)->findBy(['conversation' => $message->getConversationId()]); } } ``` I think everything is there. A little long sorry... Hope somebody could find the reason why I have this circular reference Thanks
147952
Some days ago i tried to install git on my Debian system. The instalation aborted and since this moment i get a locales error everytime i try do install/remove something via apt -.- ``` apt-get remove git Reading package lists... Done Building dependency tree Reading state information... Done The following packages will be REMOVED: git 0 upgraded, 0 newly installed, 1 to remove and 75 not upgraded. 18 not fully installed or removed. After this operation, 0B of additional disk space will be used. Do you want to continue [Y/n]? y perl: warning: Setting locale failed. perl: warning: Please check that your locale settings: LANGUAGE = (unset), LC_ALL = "de_DE", LANG = "de_DE@euro" are supported and installed on your system. perl: warning: Falling back to the standard locale ("C"). locale: Cannot set LC_CTYPE to default locale: No such file or directory locale: Kann LC_ALL nicht auf die Standard-Lokale einstellen: Datei oder Verzeichnis nicht gefunden dpkg: error processing git (--remove): Package is in a very bad inconsistent state - you should reinstall it before attempting a removal. Errors were encountered while processing: git E: Sub-process /usr/bin/dpkg returned an error code (1) ``` i tried to reconfigure locales but i get the same error... how can i fix this? greetz
the locale warning doesn't have anything to do with the git problem. following the instructions, you would want to try `apt-get install --reinstall git` or `aptitude reinstall git`, then try removing it again. If you have the git package in /var/cache/apt/archives, you could also try reinstalling with somehting like `dpkg -i /var/cache/apt/archives/git_....deb` (the exact filename would vary based on arch and version of git)
148857
I heard that two objects are homeomorphic if one could be deformed into the other by continuous transformation. [For example in this link](http://www-history.mcs.st-and.ac.uk/%7Ejohn/MT4521/Lectures/L21.html), it is shown > > a sphere and a torus are not homeomorphic > > > "Proof" > Removing a circle from a sphere always splits it into two parts -- not so for the torus. > > > However, I may imagine the following operations ![enter image description here](https://i.stack.imgur.com/uF7FG.png) to let the points around the inner circle of the continuous torus merge to a sphere. I see no reason merging is not continuous. Why not this transformation follow the definition of homeomorphic?
Because when you merge many points into a single one, you do not have a bijection; a homeomorphism is a continuous map with a continuous inverse, and a non-bijective map cannot have a (two-sided) inverse. Besides, if this operation was a homeomorphism, then its inverse --tearing a circle to turn it into a torus would be a homeomorphism.
148972
I've been trying to get a simple cloud function to delete an entity in Datastore and for some reason it doesn't work, despite not throwing an error. My code is fairly simple: ``` const keyToDelete = datastore.key({ namespace: 'alerts', path: ['alerts', entId] }); datastore.delete(keyToDelete, (err, apiResp) => { if (err) console.log(JSON.stringify(err)); else { console.log('Deleted ', JSON.stringify(apiResp)); } }); ``` I've triple checked and the key definitely points to a valid entity, and .delete isn't throwing an error - it's just not updating anything, and the response confirms this saying no indexes have been updated: ``` { "mutationResults": [ { "key": null, "version": "1598396828478034", "conflictDetected": false } ], "indexUpdates": 0 } ``` I thought the issue was that the key was returning null, but when I spelled something wrong in the key it threw an error. After some Googling I've also seen a few people that were getting that and the deletions were still working, so I don't think that's the issue. I'm using this exact same code to delete a different entity in a different cloud function, and that one's working perfectly. The only difference between the two is that one that works doesn't have a namespace in the key, as the entities being deleted are in the default namespace. Surely that's not the issue though?
Got this to work by setting an ID for the entity that was a string and not a number, and which therefore turned it into a name and not an ID. I only did this because I noticed the key was only setting a name, and couldn't figure out a way to change this to ID for some reason. Seems a bit odd as everything else works using the ID, but this works for now.
149743
Wikipedia on “Puranas” have shown classification of the Mahapuranas on the basis of the three gunas of Sat, Rajo and Tamo with the caveat “Scholars consider the Sattva-Rajas-Tamas classification as "entirely fanciful" and there is nothing in each text that actually justifies this classification.” Sattva ("truth") : Vishnu Purana, Bhagavata Purana, Naradeya Purana, Garuda Purana, Padma Purana, Varaha Purana Rajas ("passion"): Brahmanda Purana, Brahma Vaivarta Purana, Markandeya Purana, Bhavishya Purana, Vamana Purana, Brahma Purana Tamas ("ignorance"): Matsya Purana, Kurma purana, Linga Purana, Shiva Purana, Skanda Purana, Agni Purana ***[Since Wikipedia is not the final word on our Puranas, hence this question]*** **My question is, “Are there any commentaries, shrutis or other scriptural references for this classification?”**
Since you mentioned other scriptural references, I am quoting what Garuda Purana says on the classification of Puranas according to Gunas. Garuda Purana classify Puranas according to Gunas in completely different manner. > > **Garuda Purana, Brahma Khanda, Chapter 1:** > > > The Puranas devoted to Vishnu are called Satvikas. These should be > preached to peoples but not to those who cause suffering. (42) > > > In the Kali age only three principal Puranas are devoted to Vishnu. > Among these the Bhagavata Purana renders more good to the people. (43) > > > The Vishnu Purana comes next then comes Garuda Purana. Garuda contains > some additional matters. (46) > > > Next in the order of merit is the Matsya Purana, then comes Kurma > Purana then comes Vayu. T**hese three are also Satvika Puranas. O best > of sages! In the sixfold series of Satvika Puranas**, a lot of knowledge > to be discovered. (52) > > > > > --- > > > Skanda, Padma, Varaha, Vamana, Agni and Bhavishya are Rajasa Puranas. > Each of these contains sections on Rajasa and Tamasa materials. (54) > > > > > --- > > > Brahma, Brahmananda, Brahmavaivarta, Linga, Markandeya and Aditya are > Tamasa Puranas. Parts of these Puranas are Satvika and Rajasika. (55) > > > So, according to Garuda Purana: * Bhagavata, Vishnu, Garuda, Matsya, Kurma and Vayu are Satvika Puranas. * Skanda, Padma, Varaha, Vamana, Agni and Bhavishya are Rajasa Puranas * Brahma, Brahmananda, Brahmavaivarta, Linga, Markandeya and Aditya are Tamasa Puranas. For those who say why Siva Purana is missing here, it looks like Garuda Purana considers Siva Purana as an Upa-Purana and classify this Siva Purana as Tamasika Upa-purana in the succeeding verses. The term Bhagavata, Brahmananda, Vayu, Bhavishya are also included when listing the Upa-Puranas.
149903
I'm trying to write some code that makes a call to an API, which will then return some URLs, from each of which I'll then need to make a new call. To avoid nesting loads of callbacks everywhere I've tried using async/await, but it doesn't seem to be working for some reason despite the extremely simple setup I've tried. I've tried to create two async functions, one of which makes the call to any url and returns the response, and another one which will then call the first function several times depending on the response (i.e. how many urls are returned). ``` const request = require('request'); init(); async function init() { const username = "x"; const archiveUrl = "https://someurl.com"; const archiveResponse = await apiCall(archiveUrl) const archives = archiveResponse.archives; console.log(archives); } async function apiCall(url) { request(url, { json: true }, (err, res, body) => { if (err) { return console.log(err); } console.log(body); return body; }); } ``` This is literally my entire code at the moment and I'm not sure where it's going wrong. The error I'm getting is that it can't read .archives from undefined, and after that error message it's then logging the body from the apiCall function (making me fairly sure that the function isn't awaiting as expected). That said I can't see what I'm doing wrong. Any tips on general best practice would be much appreciated, I've used async/await before but it's always been hacky and self-taught so I'm sure there's a better way of doing this.
In the `apiCall` function you are using `callback` instead of `Promise`, You need to promisify that function so that `const archiveResponse = await apiCall(archiveUrl)` actually works: ``` function apiCall(url) { return new Promise((res, rej) => { request(url, { json: true }, (err, res, body) => { if (err) { return rej(err)} console.log(body); return res(body); }); }) } ``` If you are using `async-await` please handle errors by enclosing this in `try..catch` **Note:** Or you can use `request-promis` or `axios` they support promise out of the box.
150014
I need to evaluate some strings (items titles) in order to decide if the item matches or not with some rules. Regarding the rules, think about something like this. ``` ((ball | balls) & messi) -ronaldo ``` The meaning is, if the title contains either `ball` or `balls` and `messi` (but `not ronaldo`) means that match. What do you think is the best way to achieve this? (the rule must be written by end users and with a clear syntax, no regex) Thanks!
In short, **yes**. PHP isn't (at the moment) that explicit about declaring data types when creating variables - unlike other languages, although I'm sure PHP are changing their ways. Although you can do this, it's advised (good practice) to declare the data type of the variable before assigning value(s) to it.
150095
I have a web service that returns an object of a custom class (user): **Web service code** ``` public class User { public string login { get; set; } public string firstName { get; set; } public string lastName { get; set; } public string email { get; set; } } [WebMethod] public User GetUserInfo(int userID) { ITDashboardDataContext db = new ITDashboardDataContext(); User usr = (from u in db.tl_sb_users where u.userID == userID select new User { firstName = u.firstName, lastName = u.lastName, email = GetUserEmail(userID), login = u.login }).FirstOrDefault(); return usr; } ``` I want to cast the result as a user object when I call the web service from another application (I've redefined the user class in this app, too): **Calling application code** ``` public class User { public string login { get; set; } public string firstName { get; set; } public string lastName { get; set; } public string email { get; set; } } ``` I'm trying to bring back a user object with this: ``` RolloutWriter.RolloutWriter rw = new RolloutWriter.RolloutWriter(); rw.Credentials = new NetworkCredential("myuser", "mypassword", "mydomain"); var vu = rw.GetUserInfo(userID); User u = (from v in vu select new User { email = vu.email, firstName = vu.firstName, lastName = vu.lastName, login = vu.login }).FirstOrDefault(); ``` this doesn't work - it tells me: ``` Could not find an implementation of the query pattern for source type 'amstaffsite.RolloutWriter.User'. 'Select' not found. ``` How can I get back a user object?
Your method `GetUserInfo()` returns a single user, not a colection. So you can't use LINQ on the result. In your second section you don't need LINQ: ``` RolloutWriter.RolloutWriter rw = new RolloutWriter.RolloutWriter(); rw.Credentials = new NetworkCredential("myuser", "mypassword", "mydomain"); User u = rw.GetUserInfo(userID); ``` ``` // User u = (from v in vu // select new User { // email = vu.email, // firstName = vu.firstName, // lastName = vu.lastName, // login = vu.login // }).FirstOrDefault(); ```
150112
So I'm trying to make a program that takes some random number of entered seconds and converts it to Days, Hours, Minutes, and Seconds. I had to use symbolic constants to define the hours in a day, minutes in an hour, and seconds in a minute. I passed the value through but it's not being recieved so I end up with some huge negative number. Here's the code. If anyone can tell me where the problem lies I would be ever thankful. I used the random bit of code in the function definitions code to oput total seconds to see if it was being recieved and it's not. ``` #ifndef SECONDS_H_ #define SECONDS_H_ #define HOURS_IN_DAY 24 #define MINUTES_IN_HOUR 60 #define SECONDS_IN_MINUTES 60 #include <iostream> using namespace std; class Seconds { private: long totalSeconds; public: Seconds(); ~Seconds(){}; Seconds(int totalSeconds); void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds); }; #endif ``` ... ``` #include <conio.h> #include <string> #include <iostream> #include "seconds.h" #define HOURS_IN_DAY 24 #define MINUTES_IN_HOUR 60 #define SECONDS_IN_MINUTE 60 Seconds::Seconds(int totalSeconds) { totalSeconds = totalSeconds; } void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds) { cout << endl; cout << "Total Seconds: " << totalSeconds; cout << endl; days = totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE / HOURS_IN_DAY; hours = (totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE) % HOURS_IN_DAY; minutes = (totalSeconds / MINUTES_IN_HOUR) % SECONDS_IN_MINUTE; seconds = (totalSeconds % SECONDS_IN_MINUTE); } ``` ... ``` #include <iostream> #include <conio.h> #include <string> #include "seconds.h" #define HOURS_IN_DAY 24 #define MINUTES_IN_HOUR 60 #define SECONDS_IN_MINUTES 60 using namespace std; int main () { int totalSeconds; int days = 0, hours = 0, minutes = 0, seconds = 0; cout << "Enter a random massive amount of seconds: "; cin >> totalSeconds; Seconds sec(totalSeconds); sec.convertSeconds(days, hours, minutes, seconds); cout << "That is equivalent to " << days << " days, " << hours << " hours, " << minutes << " minutes, " << seconds << " seconds." << endl; cout << "Press any key to continue..."; cin.sync(); _getch(); return 0; } ```
This is a problem: ``` Seconds::Seconds(int totalSeconds) { totalSeconds = totalSeconds; } ``` The function parameter `totalSeconds` shadows the class member, so this code is like doing `x = x;`, it has no effect on `this->totalSeconds`. To fix this either use different variable name, or preferably use constructor initialization syntax: ``` Seconds::Seconds(long totalSeconds) : totalSeconds(totalSeconds) { } ``` In this version, shadowing does not occur because the constructor initialization lists are smart.
151238
I am trying to set up smooth scroll using jquery on my webpage. I am working from this example here:<https://css-tricks.com/snippets/jquery/smooth-scrolling/> When I copy and paste this into a js fiddle, it works fine. But for some reason it is not working on my website at all. As you can see I've linked my scripts.js file to my index.html, and i checked this in the console with a console.log message. Here is my html: ``` !DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700|Ubuntu:400,500" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript" src="scripts.js"></script> <title>Zane Mersky</title> </head> <body> <header> <div class="wrapper"> <div class="heading"> <div class="logo"> <h1>Heading</h1> </div> <nav> <ul> <li><a href="#philosophy">My Philosophy</a></li> <li><a href="">My Classroom</a></li> <li><a href="">Professional Development</a></li> <li><a href="">About</a></li> <li><a href="">Contact</a></li> </ul> </nav> </div> </div> <div class="intro"> <div class="img-container"> <img src="/assets/IMG_6543.JPG" alt=""> </div> <div class="left-intro"></div> <div class="right-intro"> <div class="quote"> <h3>"Childhood is not a race to see how quickly a child can read, write and count. It is a small window of time to learn and develop at the pace that is right for each individual child. <br class="break"> Earlier is not better."</h3> <h3 class="author">-Magda Gerber</h3> </div> </div> </div> </header> <main> <section class="philosophy"> <h1 id="philosophy">My Philosophy</h1> <div class="paragraph wrapper"> </div> </section> <section class="about"> <h1>About Me</h1> </section> </main> </body> </html> ``` And here is the jquery I am using: ``` // Select all links with hashes $('a[href*="#"]') // Remove links that don't actually link to anything .not('[href="#"]') .not('[href="#0"]') .click(function(event) { // On-page links if ( location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname ) { // Figure out element to scroll to var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); // Does a scroll target exist? if (target.length) { // Only prevent default if animation is actually gonna happen event.preventDefault(); $('html, body').animate({ scrollTop: target.offset().top }, 1000, function() { // Callback after animation // Must change focus! var $target = $(target); $target.focus(); if ($target.is(":focus")) { // Checking if the target was focused return false; } else { $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable $target.focus(); // Set focus again }; }); } } }); ``` Does anyone know what I am doing wrong?
Your little note in italics is actually quite relevant: > > *(This is simplified, since the SQL statement would become too long to be accepted by MySQL. You need to split it up in sections of about 5000 values and execute them. But this is not important for the problem I'm talking about here.)* > > > I think your "unprepared statement" (not a real term) approach is faster because you're bulk-loading 5000 records at a time rather than one-by-one, not because it's not a prepared statement. Try building a prepared statement with 5000 `?`s like this: ``` my $SQL = 'INSERT INTO `mytable`(`word`) VALUES ' . '(?),'x4999 . '(?)'; ``` Then build a list of 5000 words at a time and execute your prepared statement with that. You'll have to deal with the last set of (presumably) less than 5000 words with a second dynamically-generated prepared statement of the appropriate number of words in the last batch. You could also look into `LOAD DATA INFILE` for bulk loading.
151355
By default, httpd contains the following configuration: ``` <IfModule mime_module> # # TypesConfig points to the file containing the list of mappings from # filename extension to MIME-type. # TypesConfig conf/mime.types ... </IfModule> ``` This file contains a mapping from filename extensions to MIME types. Normally this is what I want, but I'd like to disable mapping for reverse proxies. **How can I instruct mime\_module to process `/*` but exclude `/proxy/*`**? --- Why? ---- mime\_module contains the following line: ``` application/x-msdownload exe dll com bat msi ``` The application being proxied accepts `PUT /proxy/rest/email@gmail.com` and returns `200 OK` without setting `Content-Type` or a response body. According to <https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-p2-semantics-24#section-3.1.1.5> this is perfectly legal (since there is no response body). `mime_module` thinks the URL applies to a `.com` file and mistakenly applies `Content-Type: application/x-msdownload`. Since I know that `/proxy/rest/` never returns files, I'd like to disable `mime_module` for that path.
I can think of three ways to achieve this. 1. Within a directory, virtualhost or .htaccess context, you can use `RemoveType .com` to remove the mapping. I'm not certain whether it will work within a proxy context as that's not an actual directory. But if it doesn't, you could go the opposite route of removing .com from the general list, and then specifically adding it for those directories where it's wanted. 2. However, in your situation it might be more useful to have a look at [mod\_mime\_magic](http://httpd.apache.org/docs/2.2/mod/mod_mime_magic.html). What it basically does is that instead of having an extension-to-type mapping, it actually looks at the contents of the file to see what it really is. The downside is that it does increase processing, so your performance will take a small hit. If you're at all close to your limits, you'll want to do some performance testing/load testing first. 3. If all data in that directory or location always have the same type, you can set a `ForceType` for the entire directory/location: . ``` <Location /proxy> ForceType image/gif </Location> ```
151489
I have to do a calculation, here is a simplification of what I am trying to achieve: ``` $box['dim1'] = 1; $box['dim2'] = 1; $box['dim3'] = 1; $volume = (($box["dim1"]/100) * ($box["dim2"]/100) * ($box["dim3"]/100)); echo $volume; ``` In this case I see: ``` 1.0E-6 ``` Rather than 0.000001 as I would expect. This is a rather extreme example and dim1, dim2 and dim3 are unlikely to ever all equal 1 but I need the value of $volume to be a number as this is passed to a 3rd party API and they don't like 1.0E-6. Is there anyway I can get $volume to equal 0.000001 and not 1.0E-6?
Scientific notation is PHP's default for printing extremely large, or extremely small, numbers as strings. Use [`printf()`](http://php.net/manual/en/function.printf.php) to print your float in decimal format: ``` printf('%f', $volume); ```
151655
I am trying to import a [vegetation data raster](http://www.fs.usda.gov/rds/archive/Product/RDS-2014-0002/) in Esri GRID format from the USDA into QGIS. One file ("w0001.adf") can be added using "add raster", but the attribute table and other info register as error or errors. Using the "ArcInfo/Binary directory" does not work either.
The .adf file is one component of an Esri GRID 'file', much like the .shp is one component of a shapefile. The other component files generally aren't or don't need to be accessed individually. If you can load that w0001.adf file and see the raster image, I suspect you're seeing all the data. I opened/added the file in Arc with no issue. In looking at the attribute table for the raster there, there's just a second, coded, numeric value field - you won't see the text strings describing what those coded values are (that info is listed in the metadata).
151746
I have a few managed bean (ViewScoped) that are currently initialized with data in the session. I would like to initialize them with a URL GET parameter so I can provide URLs with the entity ID I want to display in my view. Something like `displayClient.xhtml?entityId=123`. Right now I am thinking of something like this in the getter of the view main entity : ``` public clientModel getclientM() { if (this.clientM == null) { // TODO: Check for empty, non-integer or garbage parameters... // Anything exists to "sanitize" URL parameters? int entityId = Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("entityId")); // I guess I should check here if the logged user is authorized to // load client entity with this entityId... anything else to check? this.clientM = this.clientS.find(entityId); } return this.clientM; } ``` Any hint or suggestion of best practices would be greatly appreciated.
I'd think something along these lines are best practice: displayclient.xhtml: ``` <f:metadata> <f:viewParam name=“entityId” value="#{bean.clientM}” required="true" converter=“clientModelConverter” converterMessage="Bad request. Unknown ClientModel.” requiredMessage="Bad request. Please use a link from within the system."> </f:viewParam> </f:metadata> ``` Converter: ``` @ManagedBean @RequestScoped public class ClientModelConverter implements Converter { @EJB private ClientService clientService; @Override public String getAsString(FacesContext context, UIComponent component, Object value) { // TODO: check if value is instanceof ClientModel return String.valueOf(((ClientModel) value).getId()); } @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { // TODO: catch NumberFormatException and throw ConverterException return clientService.find(Integer.valueOf(value)); } } ``` Call the page with for example: ``` <h:link value=“Display” outcome="displayClient"> <f:param name=“entityId" value=“#{…}” /> </h:link> ``` or just a raw url for example `displayClient.xhtml?entityId=123`. Heavily inspired by [What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?](https://stackoverflow.com/questions/6377798/what-can-fmetadata-and-fviewparam-be-used-for) and [JSF 2.0 view parameters to pass objects](https://stackoverflow.com/questions/8609378/jsf-2-0-view-parameters-to-pass-objects).
152106
How do you filter a list of items with RxJava ? I have the following code and `loadData()` emits a `List<Chatroom>` : ``` repository.loadData() .subscribe(chatrooms -> { view.showData(chatrooms); view.showEmptyState(chatrooms.size() == 0); }, throwable -> Log.i("OnError", "onLoadChatrooms ", throwable))); ``` and I want to apply filter after `loadData()`. You can see my solution on the next code snippet but maybe there's a better way ? ``` repository.loadData() .map(chatrooms -> { List<Chatroom> openChatrooms = new ArrayList<>(); for (Chatroom chatroom: chatrooms){ if (!chatroom.getBlocked().equals(IS_BLOCKED)) { openChatrooms.add(chatroom); } } return openChatrooms; }) .subscribe(chatrooms -> { view.showData(chatrooms); view.showEmptyState(chatrooms.size() == 0); }, throwable -> Log.i("OnError", "onLoadChatrooms ", throwable))); ```
``` loadData() // Opther operations if any .filter((chatroom -> { return !chatroom.getBlocked().equals(IS_BLOCKED);}) .toList() .subscribe(getObserver()); // implement your getObserver() method for observer. ``` This should help.
152272
I am selecting records from my table that have been posted within the past day. This is for an internal site, where there are no posts on Saturdays or Sundays. ``` SELECT * FROM table WHERE date >= DATE_SUB(CURDATE(), INTERVAL 1 DAY) ``` This works fine if today is a weekday or Saturday (where the previous day is Friday). If today is Sunday, I'd like to get records for Friday but currently my code shows records for Saturday (which are obviously blank, given that no one posts on Saturday). How can I fix that? Thanks!
Have a look at the [`WEEKDAY`](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_weekday) operator. It returns the index of the day in the week. 0 = Monday and 6 = Sunday ``` SELECT * FROM table WHERE date = CASE WEEKDAY(CURDATE()) -- Switch on day index WHEN 6 THEN DATE_SUB(CURDATE(), INTERVAL 2 DAY) -- If sunday, back 2 days WHEN 0 THEN DATE_SUB(CURDATE(), INTERVAL 3 DAY) -- If monday, back 3 days ELSE DATE_SUB(CURDATE(), INTERVAL 1 DAY) -- Else back 1 day END ```
152293
According to the [Wikipedia article on the proposed Istanbul Canal](https://en.wikipedia.org/wiki/Istanbul_Canal), it is said that the Bosporus has nearly 3 times the amount of ship traffic as the Suez Canal. Presumably this ship traffic comes primarily from Russia and Ukraine. Why does Russia choose to be so dependent on a water passage that it does not control? Why hasn't Russia (and historically, the USSR) tried to orient their economy to use the Baltic Sea instead? Are there economic and political obstacles to minimizing this dependence?
Because the Baltic Sea ices over every winter. In theory, you could continue year-round operations with icebreakers and cargo ships with a [sufficient ice class](https://en.wikipedia.org/wiki/Ice_class) but that's expensive and there are only so many ice rated cargo ships out there. Alternatively, you could use the St. Petersburg port heavily during the summer months and the Black Sea heavily during the winter but then you'd need all of the infrastructure at both ports which, again, gets expensive. Plus, in order to get to the ocean, Russian traffic would still need to go through a relatively narrow straight owned by foreign powers (Norway, Sweden, and Denmark in this case). There is common wisdom from Western academics and politicians that the [drive to own warm water ports](https://www.globalsecurity.org/military/world/russia/warm-water-port.htm) has been a key driver of much of modern Russian history precisely because sea traffic into and out of the country is subject to such external bottlenecks. [Not everyone agrees](https://www.jstor.org/stable/44642451?seq=1#metadata_info_tab_contents) with this thesis but it is pretty common thinking in political science circles (and there are plenty of memes available if you do a search).
152388
I have a dataset 'df' that looks something like this: ``` MEMBER seen_1 seen_2 seen_3 seen_4 seen_5 A 1 1 0 1 0 B 1 1 1 0 1 C 1 1 1 1 0 D 0 0 0 1 0 ``` As you can see there are several rows of ones and zeros. Can anyone suggest me a code in python such that I am able to count the number of times '1' occurs continuously before the first occurrence of a 1 and 0 in order. For example for the fist member 'A' there are two ones occurring consequently before the first 1 and 0 appearance. Similarly for member 'B' there are three 1s that occur before a 1 and zero combination. The resultant table should have a column something like this: ``` MEMBER seen_1 seen_2 seen_3 seen_4 seen_5 event A 1 1 0 1 0 2 B 1 1 1 0 1 3 C 1 1 1 1 0 4 D 0 0 0 1 0 1 ```
With streams, it is much more difficult because you are now dealing with the `Stream` and `Optional` and you also want to handle the case where the Optionals are empty which also means handling empty streams...it's just a mess so I'd recommend not to do it. This is one way with `Optionals`. I initially thought it couldn't be done with optionals, but I guess, it can be done with just map. ``` public Fob getFob(String paramString) { getFoo(paramString) .map(foo -> foo.fooParamString) .map(fps -> getBar(fps)) .orElseGet(() -> { // Foo not found return Optional.empty(); }) .map(bar -> bar.barParamString) .map(bps -> getFob(bps)) .orElseGet(() -> { // bar not found return Optional.empty(); }) .orElseGet(() -> { // fob not found return null; }); } ``` I honestly can't say I'm a fan of it, but it can be done with optionals. There is also the risk of returning `null` when expecting Optional. For example with the last case: if you decide in the future to add a new operation and don't change the `return null` to `return Optional.empty()`, you run the risk of `NullPointerException`.
152545
PDF allows you to set permissions such as a document can be printed just once or just 10 times etc. I believe Adobe Acrobat Professional allows you to set those. My question is it possible to do so in Python programmatically? If so how?
There doesn't seem to be a way to restrict the number of times a PDF file can be printed (outside Adobe LiveCycle or some other very controlled hosted solution). Although there is lots of discussion about this e.g. <https://superuser.com/questions/37216/restrict-print-copies-on-a-pdf> If you have other info please indicate a reference. There is an open source pypdf module <http://pybrary.net/pyPdf/> But no hints there about print restriction.
152649
I am trying to setup Nhibernate with an oracle database so far i have the following: **App.config (ive commented out the username and password for protection)**: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/> </configSections> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property> <property name="query.substitutions">hqlFunction=SQLFUNC</property> <property name="connection.driver_class">NHibernate.Driver.OracleDataClientDriver</property> <property name="connection.connection_string">Data Source=CTIR;Persist Security Info=True;User ID=****;Password=****;Unicode=True</property> <property name="show_sql">true</property> <mapping assembly="TestNhibernate" /> </session-factory> </hibernate-configuration> </configuration> ``` **Agenter.cs**: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestNhibernate { class Agenter { public virtual int ID {get; set;} public virtual String Initialer { get; set; } public virtual String Fornavn { get; set; } public virtual String efternavn { get; set; } } } ``` **AGENTER\_LISTE.hbm.xml**: ``` <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="TestNhibernate" namespace="TestNhibernate"> <class name="Agenter"> <id name="ID" column="ID"> <generator class="identity" /> </id> <property name="Initialer" /> <property name="Fornavn" /> <property name="Efternavn" /> </class> </hibernate-mapping> ``` **Form1.cs:** ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using NHibernate.Cfg; using NHibernate; namespace TestNhibernate { public partial class Form1 : Form { private Configuration myConfig; private ISessionFactory mySessionFactory; private ISession mySession; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { myConfig = new Configuration(); myConfig.Configure(); mySessionFactory = myConfig.BuildSessionFactory(); <--- this is where it goes wrong mySession = mySessionFactory.OpenSession(); using (mySession.BeginTransaction()) { Agenter agent = new Agenter {Fornavn = "Marc", Initialer = "MRCR212", ID = 999, efternavn = "Rasmussen" }; mySession.Save(agent); mySession.Transaction.Commit(); } } } } ``` i get the following error: ``` Could not create the driver from NHibernate.Driver.OracleDataClientDriver. ``` What am i missing?
Finally, as this UITextView as "read-only", I used an UIWebView, doing like this : ``` NSString *contentView = [[NSString alloc] init]; contentView = [NSString stringWithFormat:@"<html><body ><p style=\"color:grey; font-style:italic;\">Some datas</p><hr/><p style=\"font-size:14px;\"> Total: %0.3f </p></body></html>", total]; [self.myUITextView loadHTMLString:contentView baseURL:nil]; [self webViewDidFinishLoad:self.existingEntries]; ```
152758
I am trying to encrypt a string using the code below. The issue is I get this error and I have no clue (I'm just learning about encryption) what to do or even where to look. The SharedKey and the IV have been supplied as Hex values. The SharedKey is 64 bytes and the IV is 32 bytes. System.Security.Cryptography.CryptographicException: 'Specified initialization vector (IV) does not match the block size for this algorithm.' ``` Public Function Encrypt(ByVal strValue As String) As String 'Create instance of a Rijndael Managed object Dim aes As New RijndaelManaged 'Set appropriate values of object aes.Padding = PaddingMode.PKCS7 aes.KeySize = 256 aes.Mode = CipherMode.CBC 'Create streams to work with encryption process Dim msEncrypt As New MemoryStream() 'SharedKey = "64 byte string" 'IV = "32 byte string" Dim SharedKey As Byte() = Encoding.GetEncoding(1252).GetBytes(strSharedKey) Dim IV As Byte() = Encoding.GetEncoding(1252).GetBytes(strIV) Dim csEncrypt As New CryptoStream(msEncrypt, aes.CreateEncryptor(SharedKey, IV), CryptoStreamMode.Write) 'Convert string value to byte array Dim toEncrypt As Byte() = Encoding.GetEncoding(1252).GetBytes(strValue) toEncrypt = Encoding.Convert(Encoding.GetEncoding(1252), Encoding.UTF8, toEncrypt) 'Perform encryption csEncrypt.Write(toEncrypt, 0, toEncrypt.Length) csEncrypt.FlushFinalBlock() 'Return Base64 string Return Convert.ToBase64String(msEncrypt.ToArray()) 'Dim u As System.Text.UnicodeEncoding = System.Text.Encoding.Unicode 'Dim a As System.Text.ASCIIEncoding = System.Text.Encoding.ASCII 'Return a.GetByteCount(SharedKey) '64 bytes End Function ```
It seems you need your data size that the node holds to change each time. You can achieve this by using a constant size node that holds a pointer to dynamically allocated data. Note that in the example below the struct size stays sizeof(void\*)+ sizeof(node\*) but the size of data allocated for each node changes using the user input. ``` typedef struct Dnode { void* data; struct Dnode* next; }Dnode; Dnode* CreateDnode(size_t data_size_bytes) { Dnode* newNode = NULL; newNode = malloc(sizeof(Dnode));/*always the same*/ if(NULL == newNode) { return NULL; } newNode->data = malloc(data_size_bytes);/*changes by input*/ if(NULL == newNode->data) { return NULL; } newNode->next = NULL; return newNode; } ```
152860
I am facing an issue while consuming a java web service from .NET. I am able to provide the input to the web serive but not able to get back the result. The result is a custom object which is created in Java with one long, one short and one string variable. But the output I am getting from .NET is that long and short are always defaulted to 0 and string to null string. Any pointers should be appreciated. In addition when I make the return as just plain int, it is working fine. Regards, Bijesh
Maybe something like: ``` std::string FormatNum(double num) { int numToDisplay ((int)((num + 0.005) * 100.0)); stringstream ss; int digitsToDisplay(abs(numToDisplay) % 100); ss << ((num > 0) ? '+' : '-') << (abs(numToDisplay) / 100) << '.' << (digitsToDisplay / 10) << (digitsToDisplay % 10); return ss.str(); } stringstream ss; ss << FormatNum(0.95637) << ' ' << FormatNum(+0.00123) << ' ' << FormatNum(-0.02935); ```
153392
I'm working with a REST API, that returns 2 different kinds of XML responses for the same request. For example if I ask for a ticket using some ticket number, say `12345` to this API, it either returns: 1. The ticket: ![](https://i.stack.imgur.com/UmB20.png/200) 2. Or says that it doesn't have the ticket: ![](https://i.stack.imgur.com/PXwhC.png/200) (I couldn't format my XML for some reason so just pasted the screenshot.) Note that the status code comes to be `Ok` in both the cases. I'm aware that it's a bad api design but we can't change anything about it. With some help from this [JSON2Csharp](https://json2csharp.com/xml-to-csharp) website, I came up with these classes to represent the response: The Ticket class: ``` [XmlRoot(ElementName = "Tickets")] public class TicketsResponse { public List<Ticket> Tickets { get; set; } = new List<Ticket>(); public bool HasTickets() => Tickets.Any(); } [XmlRoot(ElementName = "Ticket")] public class Ticket { [XmlElement(ElementName = "Field1", IsNullable = true)] public string Field1 { get; set; } public bool ShouldSerializeField1() { return Field1 != null; } [XmlElement(ElementName = "TicketNumber")] public int TicketNumber { get; set; } [XmlElement(ElementName = "SomeOtherDetails")] public SomeOtherDetails SomeOtherDetails { get; set; } [XmlElement(ElementName = "Accessorials")] public object Accessorials { get; set; } } [XmlRoot(ElementName = "SomeOtherDetails")] public class SomeOtherDetails { [XmlElement(ElementName = "SomeOtherField1", IsNullable = true)] public string SomeOtherField1 { get; set; } public bool ShouldSerializeSomeOtherField1() { return SomeOtherField1 != null; } } ``` The Error class: ``` [XmlRoot(ElementName = "response")] public class ErrorResponse { public byte requestId { get; set; } public byte errorCode { get; set; } public string errorDesc { get; set; } public ErrorResponseBody body { get; set; } public bool HasErrors() { var hasTopLevelError = errorCode != 0; var hasErrorBody = body?.errors?.Any() ?? false; if (hasTopLevelError || hasErrorBody) { return true; } return false; } public string ErrorMessage() { var hasTopLevelError = errorCode != 0; var hasErrorBody = body?.errors?.Any() ?? false; if (hasTopLevelError) { return errorDesc; } else if (hasErrorBody) { return string.Join(", ", body.errors.Select(e => e.errorDescription)); } return null; } } [XmlRoot(ElementName = "body")] public class ErrorResponseBody { [XmlElement("errors")] public List<Error> errors { get; set; } } [XmlRoot(ElementName = "Error")] public class Error { public byte errorId { get; set; } public string errorDescription { get; set; } public string errorObjectId { get; set; } } ``` I then call the API using a `TicketNumber` that *exists*. I'm using [RestSharp](https://restsharp.dev/) for calling the api: ``` public async void SendRequestAndReceiveResponse() { var restClient = new RestClient("https://someapiaddress.net"); var requestXMLBody = "<request><request_id>1</request_id><operation>retrieve</operation><method /><entity>ticket</entity><user>someuser</user><password>somepassword</password><body><ticket><TicketNumber>12345</TicketNumber></ticket></body></request>"; var request = new RestRequest("somexmlwebservice!process.action", Method.POST); request.AddParameter("xmlRequest", requestXMLBody, "text/xml", ParameterType.QueryString); var response = await restClient.ExecuteAsync<TicketsResponse>(request); // Do other stuffs with this response... } ``` Now this works very well. Because I know my response will have the ticket and that will correctly deserialize to `TicketsResponse` object. But if I call the API using a `TicketNumber` that doesn't exist, I simply get `TicketsResponse` object that has an empty list of `Tickets` because this time I'm getting error response. The status code comes to be `OK` in this case too. What I want to do here is that I want to capture the error message from the error response. (Response of either *Ticket* or *Error* applies to bunch of other processes as well, so it's important to grab this information in a single call.) And if I knew this ticket doesn't exist, I could simply call the API this way and capture the `errors`. But that's not ideal nor even a good idea: ``` var response = await restClient.ExecuteAsync<ErrorResponse>(request); ``` So I thought of combining `TicketsResponse` and `ErrorResponse`, like this: ``` [XmlRoot] public class CombinedResponse { [XmlElement(ElementName = "Tickets")] public TicketsResponse Data { get; set; } [XmlElement(ElementName = "response")] public ErrorResponse NonData { get; set; } } ``` And get the response using that class: ``` var response = await restClient.ExecuteAsync<CombinedResponse>(request); ``` The Status code comes `OK` (when it returns either data or error message) and I get my correct response in `response.Content`, but the deserialization doesn't work, so my `response.Data` will show 2 fields `Data` and `NonData` both as `null`. Ideally I should have gotten either my *Ticket* data or *Error* data in `response.Data`. **So my question is:** Is it possible to make this work using a single class for deserialization? I have spent too much time on this so any help is appreciated. Also please look at my model classes and suggest if there's better way of doing things.
This is how I solved this issue. I'm posting here so others may find it helpful. If there's a better way of doing this, please advise. I created a method to call the API and deserialize the response to multiple types: ``` public async Task<(T1, T2)> SendRequestAndReceiveResponse<T1, T2>(RestRequest request) { // This can be done in the constructor so we don't instantiate new client for every request. var restClient = new RestClient("https://someapiaddress.net"); // Get response: var response = await restClient.ExecuteAsync(request); // Log request and response here if you want. if (response.ErrorException != null) { var message = $"An error occured during this request. Check request response entries for more details."; var newException = new Exception(message, response.ErrorException); throw newException; } else { var xmlDeserilizer = new RestSharp.Deserializers.XmlDeserializer(); var data = xmlDeserilizer.Deserialize<T1>(response); var nonData = xmlDeserilizer.Deserialize<T2>(response); return (data, nonData); } } ``` And used it, by sending the types I need: ``` public async Task<IEnumerable<Ticket>> FetchTickets() { var xmlRequestBody = "<request><request_id>1</request_id><operation>retrieve</operation><method /><entity>ticket</entity><user>someuser</user><password>somepassword</password><body><ticket><TicketNumber>12345</TicketNumber></ticket></body></request>"; var request = new RestRequest("somexmlwebservice!process.action", Method.POST); request.AddParameter("xmlRequest", xmlRequestBody, "text/xml", ParameterType.QueryString); var apiCallResult = await SendRequestAndReceiveResponse<TicketsResponse, ErrorResponse>(request); if (apiCallResult.Item1 != null && apiCallResult.Item1.HasTickets()) { // Do something with the tickets... } else if (apiCallResult.Item2 != null && apiCallResult.Item2.HasErrors()) { // Do something with the errors... } // And so on... } ```
153417
You can find my dataset [here](https://drive.google.com/open?id=0B8clGpnMSCjUdTRXNjBNMktkdVE). From this data, I wish to plot (one line for each): ``` x$y[,1] x$y[,5] x$y[,1]+x$y[,5] ``` Therefore, more clearly, in the end, each of the following will be represented by one line: ``` y0, z0, y0+z0 ``` My x-axis (time-series) will be from `x$t`. I have tried the following, but the time-series variable is problematic and I cannot figure out how I can exactly plot it. My code is: ``` Time <- x$t X0 <- x$y[,1] Z0 <- x$y[,5] X0.plus.Z0 <- X0 + Z0 xdf0 <- cbind(Time,X0,Z0,X0.plus.Z0) xdf0.melt <- melt(xdf0, id.vars="Time") ggplot(data = xdf0.melt, aes(x=Time, y=value)) + geom_line(aes(colour=Var2)) ```
The most simple solution, I think, will be ``` If(mixmatch(id,'blue','green','red') and place='A','Group A', If(mixmatch(id,'blue','green','yellow') and place='B','Group B')) as allPl ```
153527
When doing `apt-get -y upgrade` on a new Ubuntu 14.04 machine with the `ubuntu:latest` (Xenial) image, it raised an error: ``` Setting up makedev (2.3.1-93ubuntu2~ubuntu16.04.1) ... mv: cannot move 'console-' to 'console': Device or resource busy makedev console c 5 1 root tty 0600: failed ``` --- I've a fresh install of docker on a fresh Ubuntu 14.04, using these command: ``` sudo apt-get remove docker docker-engine sudo apt-get update sudo apt-get install linux-image-extra-$(uname -r) linux-image-extra-virtual wget -qO- https://get.docker.com/ | sudo sh su - $USER # To logout and login ``` Docker for `hello-world` runs fine: ``` $ docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from library/hello-world 78445dd45222: Pull complete Digest: sha256:c5515758d4c5e1e838e9cd307f6c6a0d620b5e07e6f927b07d05f6d12a1ac8d7 Status: Downloaded newer image for hello-world:latest Hello from Docker! This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash Share images, automate workflows, and more with a free Docker ID: https://cloud.docker.com/ For more examples and ideas, visit: https://docs.docker.com/engine/userguide/ ``` When I create an empty docker container with: ``` docker run -it ubuntu bash ``` and ran the following: ``` apt-get update apt-get install -y debconf-utils echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections apt-get update apt-get -y upgrade ``` The error: ``` Setting up makedev (2.3.1-93ubuntu2~ubuntu16.04.1) ... mv: cannot move 'console-' to 'console': Device or resource busy makedev console c 5 1 root tty 0600: failed ``` is raised when doing the last `apt-get -y upgrade` The full docker log is on: <https://gist.github.com/alvations/ebe7175b984213d6f64a3c779ba3249e>
Agree with other answers/comments that `apt-get -y upgrade` isn't as good an idea as pulling a newer/updated image. Where a particular package is required but out of date in an image, installing that particular package is often enough (since dependencies will be updated as necessary). **However**, there really is no reason that you shouldnt be able to use `apt-get -y upgrade` and in fact, I'd consider this a bug, similar to but not exactly the same as: <https://bugs.launchpad.net/ubuntu/+source/makedev/+bug/1675163> The part that is failing is the first call to MAKEDEV in the postinst script but this is handled and the script continues. Ultimately this means there is no current issue with installing makedev. **But this may not always be true** so probably requires a bug to be raised with Ubuntu to have docker containers detected as well (somehow). **Note:** if you care about makedev ruining your docker /dev/ directory currently or want to make sure you get rid of any error condition from installing makedev, the fix for the bug I linked to can be used to trick the postinstall script into not running. The check in the script says: ``` # don't stomp on LXC users if grep -q container=lxc /proc/1/environ then echo "LXC container detected, aborting due to LXC managed /dev." exit 0 fi ``` so if you were to add an environment variable whose name ends in container with the value lxc, then the check would be tripped and no new devices would be installed ``` docker run -ti -e "ImNotAnLXCcontainer=lxc" ubuntu ``` This will cause the script to exit, not create a whole bunch of /dev/ entries, and output the message: ``` Setting up makedev (2.3.1-93ubuntu2~ubuntu16.04.1) ... LXC container detected, aborting due to LXC managed /dev. ```
153595
I need to create a new column that establishes relationships between entities in a delimited list ( any delimiter works except a comma ). Dataframe: ``` df1 = pd.DataFrame(np.array([[1000, 'Jerry', 'BR1','BR1'], [1001, 'Sal', 'BR2', 'BR1'], [1002, 'Buck', 'BR3', 'BR2'], [1003, 'Perry','BR4','BR1']]), columns=['ID', 'Name', 'Branch', 'Member of']) ``` The final result should be: ``` ID Name Branch Member of Members ==== ==== ====== ========= ======= 1000 Jerry BR1 BR1 Jerry, Sal, Perry 1001 Sal BR2 BR1 Buck 1002 Buck BR3 BR2 NaN 1003 Perry BR4 BR1 NaN ``` I need to create the "members" column by finding all matches in "Member of", but returning the "Name", then populate a list that ends up in "members". Would np.where be a good place to start? * `np.where(df['Branch'] == df['Member of'], ??, np.nan)`
This question is tagged with "ServiceNow" and none of the previous answers are sensitive to the nuances of ServiceNow's Rhino engine. ES6 syntax will throw the following error in any server-side script `Javascript compiler exception: syntax error`. At present (Jan. 2022), ServiceNow only supports ES5 JavaScript. You should use ServiceNow's JSON wrapper for parsing and stringifying your objects. The JSON wrapper code lives in a Script Include called `JSON` which you can peruse. Several ES5 methods are available to you - including the `forEach()` method. Because entity is an array, we use `forEach()` to iterate over the entity array of objects. Note that this is only one of several ways to iterate over this array. I've updated your code snippet and added comments to reflect the answer to your question. ```js var results = { "id": "92-4dac-4307-9038-c50e829a022a", "funa": ["4667"], "entity": [ {"id":"98","en": "com","type": "AAF"}, {"id":"99","en": "com","type": "AAF"} ]}; gs.info(">> raw result: " + results.funa[0]); // output : 4667 var resultsStr = global.JSON.stringify(results); // Convert result to string var resultsObj = global.JSON.parse(resultsStr); // Convert resultStr to an object gs.info(" >> after parse mots: " + resultsObj.funa[0]); // output : 4667 gs.info(" >> after parse id0: " + resultsObj.entity.length); //output : 2 resultsObj.entity.forEach(function(entity) { // Use forEach() to iterate through each obj in the entity array for (var key in entity) { // Iterate through each key in the current array element gs.info("Key is: " + key + " and value is: " + entity[key]); // Access entity array element value from the parsed resultsObj } }); ```
154785
There are 4 columns on my excel. For every element in column A, I would like to loop through every element column C. If the element in column C equal to column A, then it return the value of column D in column B. For example, B4 should return "dog". B5 should return "egg". B6 should return "cat". ![enter image description here](https://i.stack.imgur.com/OLz23.png) ![enter image description here](https://i.stack.imgur.com/gfUR2.png) I ran my VBA code. All the value in column B returns "egg". Could someone have a look with my below VBA code please? ``` Sub testing_click() Dim x As Variant Dim arr1 As Variant Dim i , r As Long arr1 = Worksheets("testing").Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row).Value For Each x In arr1 For r = 1 To 5 If x = Trim(Worksheets("testing").Cells(r, "c").Value) Then For i = 1 To Worksheets("testing").Range("a1048576").End(xlUp).Row Worksheets("testing").Cells(i, "b").Value = Worksheets("testing").Cells(r, "d").Value Next i End If Next r Next x End Sub ```
Try to add `margin: 0;` to `h2`. ``` h2 { background-color:#000000; color:#d9d9d9; text-align:center; font-size: 2.8em; margin: 0; } ``` [Example in JSFiddle](http://jsfiddle.net/f5t5nov9/)
154881
I have a MySQL query that sometimes takes over 1 second to execute. The query is as follows: ``` SELECT `id`,`totaldistance` FROM `alltrackers` WHERE `deviceid`='FT_99000083426364' AND (`gpsdatetime` BETWEEN 1341100800 AND 1342483200) ORDER BY `id` DESC LIMIT 1 ``` This query is run in a loop to retrieve rows on certain days of the month and such. This causes the page to take over 25 seconds to load sometimes... The table structure is as follows: ``` CREATE TABLE IF NOT EXISTS `alltrackers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deviceid` varchar(50) NOT NULL, `lat` double NOT NULL, `long` double NOT NULL, `gpsdatetime` int(11) NOT NULL, `version` int(11) DEFAULT NULL, `totaldistance` int(11) NOT NULL DEFAULT '0', `distanceprocessed` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `id_deviceid` (`id`,`deviceid`), UNIQUE KEY `deviceid_id` (`deviceid`,`id`), KEY `deviceid` (`deviceid`), KEY `deviceid_gpsdatetime` (`deviceid`,`gpsdatetime`), KEY `gpsdatetime_deviceid` (`gpsdatetime`,`deviceid`), KEY `gpsdatetime` (`gpsdatetime`), KEY `id_deviceid_gpsdatetime` (`id`,`deviceid`,`gpsdatetime`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=677242 ; ``` I have added all kinds of index combinations (please tell me which to remove) in order to try and get MySQL to use indices for the query, but to no avail. Here is the EXPLAIN output: ``` id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE alltrackers index deviceid_id,deviceid,deviceid_gpsdatetime,gpsdatet... PRIMARY 4 NULL 677238 Using where ``` The reason I'm using ORDER BY ASC/DESC LIMIT 1 is because I need the first and last rows of the query. Would it be faster to just run the query without LIMIT 1 and use PHP to retrieve the first and last rows? Many thanks for your help!
You need to have Apple development certificate and .p12 file of that account of which that provisioning profile exists. If you don't have, you need to create it from keychain, by requesting a certificate from authorised authority->generate csr and submit in you developer account. hope it helps you........
154939
I have the following worksheet #1 (simplified for the question) of person and age: ``` Person Age Bob 40 Brett 35 Brian 38 ``` I would like to setup another worksheet where I have the following: ``` Person Age Spot #1 FORMULA ``` The user will enter a name in Spot #1 and I want a formula/code in the cell titled FORMULA where the formula/VBA code will look at the table in worksheet #1 and pull in the appropriate age based on the person entered in . What formula can I use to do this? Thanks for your help!
Use the [VLOOKUP](http://office.microsoft.com/en-us/excel/HP052093351033.aspx) function. This example below assumes that your data table is in Sheet1!A1:B4. Although I would recommend that you make your data table a [Named Range](http://office.microsoft.com/en-us/excel/HP052015361033.aspx?pid=CH010036991033) and reference it using VLOOKUP(A2, MyDataTable, 2) ``` Person Age Spot #1 =VLOOKUP(A2, Sheet1!A1:B4, 2) ```
155465
I'm trying to get data from a fusion table. I write, as it is written in the [example](https://github.com/dart-google-apis/dart_fusiontables_v1_api_client) ``` import "package:google_fusiontables_v1_api/fusiontables_v1_api_browser.dart"; import "package:google_oauth2_client/google_oauth2_browser.dart"; class CFusionTable { static const _tableName = '*mytablename*'; static const _clientID = "*myclientid*"; GoogleOAuth2 _gauth; CFusionTable() { _gauth = new GoogleOAuth2(_clientID, [Fusiontables.FUSIONTABLES_SCOPE]); var fusiontables = new Fusiontables(_gauth); fusiontables.query.sql('select ID, Name, Latitude, Longitude, Country, Territory, City, Photo, ROWID from '+_tableName, hdrs: false) .then(_loadData); } void _loadData(data) { print (data.toString()); } } ``` But the authentication does not work: > > Failed to load resource: the server responded with a status of 403 > (Forbidden) > > As">https://www.googleapis.com/fusiontables/v1/query?hdrs=false&sql=select%20ID%2C%20Name%2C%20Latitude%2C%20Longitude%2C%20Country%2C%20Territory%2C%20City%2C%20Photo%2C%20ROWID%20from%201bSQ16GyMgRuleMBdn1aF4Xfu0E3HRv\_As > Uncaught Error: APIRequestException: 403 Daily Limit for > Unauthenticated Use Exceeded. Continued use requires signup. > Exception: APIRequestException: 403 Daily Limit for Unauthenticated > Use Exceeded. Continued use requires signup. undefined > (undefined:0:0) > > > Tell me please, what am I doing wrong?
You need to authenticate first before you can execute methods on the fusion tables. In the example code below, call the `login` method to invoke the authentication and the fusion tables when authentication was successful. ``` import "package:google_fusiontables_v1_api/fusiontables_v1_api_browser.dart"; import "package:google_oauth2_client/google_oauth2_browser.dart"; class CFusionTable { static const _tableName = '*mytablename*'; static const _clientID = "*myclientid*"; GoogleOAuth2 _gauth; CFusionTable() { _gauth = new GoogleOAuth2(_clientID, [Fusiontables.FUSIONTABLES_SCOPE]); } void login() { _gauth.login().then(_gauth_tokenLoadedHandler); } void _gauth_tokenLoadedHandler(Token token) { var fusiontables = new Fusiontables(_gauth); fusiontables.query.sql('select ID, Name, Latitude, Longitude, Country, Territory, City, Photo, ROWID from '+_tableName,hdrs: false) .then(_loadData); } void _loadData(data) { print (data.toString()); } } ```
155566
On my Kubernetes Setup, i have 2 Services - A and B. Service B is dependent on Service A being fully started through. I would now like to set a TCP Readiness-Probe in Pods of Service B, so they test if any Pod of Service A is fully operating. the ReadinessProbe section of the deployment in Service B looks like: ``` readinessProbe: tcpSocket: host: serviceA.mynamespace.svc.cluster.local port: 1101 # same port of Service A Readiness Check ``` I can apply these changes, but the Readiness Probe fails with: ``` Readiness probe failed: dial tcp: lookup serviceB.mynamespace.svc.cluster.local: no such host ``` I use the same hostname on other places (e.g. i pass it as ENV to the container) and it works and gets resolved. Does anyone have an idea to get the readiness working for another service or to do some other kind of dependency-checking between services? Thanks :)
Due to the fact that Readiness and Liveness [probes](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/) are fully managed by `kubelet` node agent and [kubelet](https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/) inherits DNS discovery service from the particular Node configuration, you are not able to resolve K8s internal nameserver [DNS](https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/) records: > > For a probe, the kubelet makes the probe connection at the **node**, not > in the **pod**, which means that you can not use a service name in the > host parameter since the kubelet is unable to resolve it. > > > You can consider scenario when your source **Pod A** consumes Node IP Address by propagating `hostNetwork: true` parameter, thus `kubelet` can reach and success Readiness probe from within **Pod B**, as described in the official k8s [documentation](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/#configure-probes): ``` tcpSocket: host: Node Hostname or IP address where Pod A residing port: 1101 ``` However, I've found Stack [thread](https://stackoverflow.com/questions/51079849/kubernetes-wait-for-other-pod-to-be-ready), where you can get more efficient solution how to achieve the same result through [Init Containers](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/#what-can-init-containers-be-used-for).
155595
How i can do for open a main frame, please look at my code, and correct, or tell me where i have a misstake. This is a code for authorization window, and i want see the main frame when i click at the button "login". Please,help me. I don`t know how to do this. I sitting at this program more than 5 days. ``` public static void authorizationWindow(){ JButton createAcc = new JButton("Створити новий аккаунт"); JButton loginIntoMy = new JButton("Ввійти в існуючий"); loginIntoMy.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JPanel jPanelCreateAcc = new JPanel(); JLabel nameLabel = new JLabel("Введіть ваш email:"); JLabel passLabel = new JLabel("Введіть пароль :"); JTextField name = new JTextField(10); JPasswordField pass =new JPasswordField(10); jPanelCreateAcc.add(nameLabel); jPanelCreateAcc.add(name); jPanelCreateAcc.add(passLabel); jPanelCreateAcc.add(pass); JButton login = new JButton("Ввійти"); JButton cancel = new JButton("Вийти"); login.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String text = name.getText(); char[] password = pass.getPassword(); System.out.println(" "+ text + ""+new String(password)); } }); // Кнопка вийти має виходити повністю з програми cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); JOptionPane.showOptionDialog(createAcc,jPanelCreateAcc,"Вхід", JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE,null,new Object[]{login,cancel},null); } }); int n =JOptionPane.showOptionDialog(null, "", "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{createAcc,loginIntoMy}, null); } ``` This is a main frame code: ``` private static Component createWindow(int width, int height, String title ) throws IOException { window.setVisible(true); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setResizable(false); window.setLocationRelativeTo(null); window.pack(); window.setTitle(title); window.setSize(width, height); JPanel jPanel = new JPanel(); window.add(jPanel); screenButton.setLocation(25, 59); // jtb.setFont(new Font("Times New Roman",1,14)); jPanel.setBackground(Color.lightGray); jPanel.add(screenButton); jPanel.add(saveTextButton); jtb.setBackground(Color.green); JScrollPane jsp = new JScrollPane(jtb); jsp.setPreferredSize(new Dimension(900, 247)); jpm.add(copy); jtb.setComponentPopupMenu(jpm); jPanel.add(jsp); jtb2.setBackground(Color.orange); JScrollPane jsp2 = new JScrollPane(jtb2); jsp2.setPreferredSize(new Dimension(900, 247)); jtb2.setComponentPopupMenu(jpm); jtb3.setBackground(Color.white); JScrollPane jsp3 = new JScrollPane(jtb3); jsp3.setPreferredSize(new Dimension(300, 247)); jtb3.setComponentPopupMenu(jpm); jPanel.add(time()); jPanel.add(jsp2); jPanel.add(jsp3); window.setJMenuBar(jMenuBar); jMenuBar.add(jMenu); jMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(jMenuItem, ""); } }); // GridBagLayout gbl = new GridBagLayout(); // // jPanel.setLayout(gbl); // GridBagConstraints gbc = new GridBagConstraints(); // // gbc.gridx = 0; // gbc.gridy = 0; // // gbc.weightx = 0.0 ; // gbc.weighty = 0.9; // // gbc.insets =new Insets(10,3,4,5); // gbc.anchor = GridBagConstraints.WEST; return jMenu.add(jMenuItem); } ``` And this is a thread: ``` javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { try { authorizationWindow(); createWindow(1280, 720, ""); } ```
You can't do this with a `textarea` element: they support plaintext only, and not HTML. You will have to use a different element with `contenteditable="true"`. I prefer `div`, but others work as well.
155606
My thesis (Canadian Research Based, Computer Science), collects three separate research projects (with a tenuous connecting thread). While collating these projects into a single document, I have looked into other theses coming out of my university and others in my field, and have realized that it's looking like my thesis is going to be very large. Probably twice the average length of others in my field. Which makes me wonder: Did I do **too much** work for a thesis? Should I have pushed my supervisor, cancelled the final proposed project (#3) and graduated on the strength of the first two? I'll be graduating 6 months after my target deadline, with multiple publications, and so burnt out that my initial plan to pursue a PhD has collapsed. Can't change the past, so I'm asking here mostly out of curiosity, and for other future students.
It is not clear how to judge the "size" of a thesis (page length or word count is probably not very good), but one can clearly do too much research for a Masters or Doctorate. That said a factor of two difference is not really that big since there is always going to be a healthy overlap between the "largest" Master thesis and the "smallest" PhD thesis. If your Masters thesis is larger than the average PhD thesis and larger than the vast majority of Masters theses, then it is possibly too large. As a student you need to be asking yourself why you are getting the qualification. Most students put in much more work than that which is required to simply graduate. You should make sure you push your supervisor to help you achieve your goals.
155645
Background: Around 600 years ago, the whole world was in conflict. Outside of Ser, the world was a chaotic and dangerous place. Ser was the only neutral country in a world filled with violence and devastation. There were at least 8 wars going on and nobody had any alliances. All trade was cut off. The country Ser, led by an aging Empress Ana, said the following: > > Let them fight, die, or whatever it is that barbarians do with one another. There is no need to intervene, so long as they do not cross our borders. > > > Upon her death, her son gained the throne and had a much different stance on the matter. In fact, he declared war upon the *entire world:* > > As of this moment, the Ser Empire will begin to liberate the people in the world burdened by their oppressive governments, who forfeited their right to yield power when they abused it. We will extend our hand in leadership towards these victims and one by one, we will unite all of mankind. This will be the last war. > > > In a nutshell, they were able to actually conquer the entire world due to their brilliant military strategist. I won't go into detail. --- In response to being conquered, about 50 years later a superhuman organization intent on overthrowing the Ser government was created called Res. They almost succeeded. A new secret organization of superhumans called Rova was created, secretly sponsored by the Ser government to defeat Res. Res was defeated and disbanded, only to keep resurfacing every once in a while. --- **500 years later**, in a world very similar to modern Earth, Rova continues to protect the world from the chaos of Res. I'm having a hard time figuring out just how big secret organizations such as Res and Rova would be. **How big would Res be, considering that its leaders and key figures have been defeated time and time again? How big would Rova be, with the support and finances of the Ser government?** The way the Rova organization works currently in my story: They have a shell organization or organizations that are legitimate on the outside, but most of its members are all part of something bigger. For example, the Rova headquarters is located in the capital city of Ser, in a building that leases office space to some other large organizations. --- Specifically, I'm trying to figure out how buildings each organization might own, or how many employees I should decide each organization has. Or how they might get away with staying in the shadows for hundreds of years and yet maintain influence on an international scale. --- EDIT Clarification 1: Superhumans are born, not made. They can been seen as similar to mutants from the X-Men/Marvel universe. However, there is also some genetics involved: Normal people tend to produce normal children, and superhumans tend to make superhuman children. But it is also not out of the ordinary for normal people to produce superhumans, or vice versa. EDIT Clarification 2: Although it is true that rebellions thrive on publicity, Res is keeping themselves secret because they aren't strong enough to take on the entire world by themselves. They need to slowly gain enough members secretly until they believe they can take on the entire world's armies. Their political views simply do not have enough public support to justify coming to the surface - especially with their history of violence.
My answer is: pretty small. I'd personally go with something like 1000-3000 humans in the whole world. That is to cover the entire planet. Here is a couple of points to justify the number. * Consider how much influence google, facebook, and amazon are for example. Each can be run by a couple of people. Gone are the days of dragging the rebel to the town square and beheading him. It's enough to simply omit them from the internet. * Lobbies, interest groups, and all the actual dirty politics of the modern world. Oh boy. Are we talking. Imagine how much those groups actually effect the country and even world. Why are we letting them get away? Simple. They control the elected officials. Now there are levels of this. But in truth if your group is big enough and strong enough, which is is because magic, you can be even more powerful. And you just need a handful of people to control it. * Money. If you control the money you control the world. Honestly it's that simple. Especially in the context of magic and planning for centuries for advance. Your group of people can have the entire world in debt and still have them borrow more. Think of Crassus in the Roman Republic. So have a bunch of venture capitalist and bankers in there. * Big companies. Like really big companies. Think GE. Pretty simple. One figure head for that company. * Science and research. Yep. They can be bought and sold. I don't want to get into too much real world politics. But you would be surprised how much the actual scientific community is... Well. A community. A group of humans with all that brings. So again with enough money you can easily control the whole thing. Also science is not an abstract meditation thing. Scientists need money. And if you control the money... * The military. If you control enough of the high ranking generals you effectively control the military. Pretty simple. * The media. If they are not corrupt they are just plain wrong and stupid. And if you super duper smart journalist can't find a sing newspaper or channel to run their story, then they don't have a story. If the idea the games causes violence or that metalhead are satanists then I'm pretty sure they won't mind getting paid to still cover lies. I mean if they gonna suck anyway, might as well get paid. * Art. You finances the next movie, game, play, and other stuff? Yeah. They decide what is on screen and what people can see. Think how big Netflix, Sony, and Disney are. Just imagine. OH you just made a masterpiece with a crew of 2 and a budget of a grilled cheese sandwich and some change? OK. But where will it air? How can people see it? If you are into cinema you will be surprised at how much they even screw up the non political parts of it. And all that with the supreme goal of mere money making. However if your group don't care then it won't even matter if the movies make money or not. * Friendly head of states in third world countries. Is a thing. And it sucks. Want to mine Phlebotinum but can't find it anywhere but in this hellhole that is in a constant state or civil war like an NPC in a loop? Just a couple of millions in peaceful aid. Just your run of the mill artillery, tanks, automatic rifles, and kevlar The stuff children need to survive. And now you have your very own government. Ask that dictator for the hearts of a 100 child monthly and they will oblige. I read about literal cannibal dictators in Africa. So. Yep. * Little global conflicts. Because you already own most of the world as it is. You still let people have their fun and problem. But you don't have to worry about actual opposition. * The Godfather's model. The idea is that you do people favors of all types and sorts and then they owe you. And you should not be stupid enough to ask them something they won't like doing. So how can you actually control a several million people army? You approach the up and coming officers. You don't break their door and drop a bag of gold on their beds while putting a gun to their child's head. You gradually introduce them into you world with whatever vices or method is more appropriate. With time they come to depend on their "godfather" more and more. You insure they rise to the top or whatever position you want. By that point, we are talking years, they already view that person as a good guy. If he says they should support that war against that country then it's not like a stranger or a blackmailer. It's the guy that have been looking out for them since day one. Then you already have the entire cabinet in your pocket. You also have the media. They open the TV and it's about the necessity for war against country X. They speak to the elected people and again it's war. Their fellow officers want war. If you control enough people then the rest will follow. Same with every single aspect of society. Buy the head of university, but the think tank, buy people the head of the local fast food store for all it matters. You can afford it. You also don't ask the upstanding vegan doctor who volunteers all the time and uses a bicycle and is really child, to go butcher a nosy journalist. You ask the corrupt cop, you ask the button man. In fact the ruling class/elite/group...etc is so removed for the request of murder that they are never aware about the day to day affairs. All this is with as little magic as possible. You superhumans can change it further. So just having the resources, focus, and time to do it is enough. They can do it with a 100. But I gave a more generous number to comfortably cover the world. So that there is no stress of worrying.
155954
I want to create a layout for my android application using inheritance i.e. every screen will have the same background and header. The layout with that background and header is specified like this: ``` <?xml version="1.0" encoding="utf-8"?> <merge xmlns:android="http://schemas.android.com/apk/res/android"> <LinearLayout android:layout_width="match_parent" android:layout_height="25dp" android:background="@drawable/background" android:orientation="vertical" > <TextView android:id="@+id/headerLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="2dp" android:text="@string/app_name" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@string/ColorLabel" /> </LinearLayout> </merge> ``` While a specific screen, the login screen, looks like this: ``` <?xml version="1.0" encoding="utf-8"?> <merge xmlns:android="http://schemas.android.com/apk/res/android"> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <include android:layout_width="wrap_content" android:layout_height="wrap_content" layout="@layout/background" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="50dp" android:orientation="vertical" > <TextView android:id="@+id/username_label" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:text="@string/Username" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/username_box" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:ems="10" android:inputType="text" > <requestFocus /> </EditText> <TextView android:id="@+id/password_label" android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginTop="10dp" android:layout_weight="1" android:text="@string/Password" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/password_box" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:ems="10" android:inputType="textPassword" /> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_gravity="fill" android:layout_marginTop="10dp" android:layout_weight="1" android:gravity="center_vertical" android:weightSum="2" > <Button android:id="@+id/login_button" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_gravity="center|left" android:layout_marginRight="20dp" android:background="@drawable/background" android:text="@string/Login" android:textColor="@string/ColorLabel" /> <Button android:id="@+id/register_button" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_gravity="right" android:background="@drawable/background" android:text="@string/Register" android:textColor="@string/ColorLabel" /> </LinearLayout> </LinearLayout> </LinearLayout> </merge> ``` When I want to run this code, it causes an error: ``` 10-05 17:10:11.620: D/AndroidRuntime(25222): Shutting down VM 10-05 17:10:11.623: W/dalvikvm(25222): threadid=1: thread exiting with uncaught exception (group=0x40015578) 10-05 17:10:11.635: E/AndroidRuntime(25222): FATAL EXCEPTION: main 10-05 17:10:11.635: E/AndroidRuntime(25222): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.shopassistent/com.shopassistent.Login_Activity}: android.view.InflateException: Binary XML file line #9: Error inflating class <unknown> 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.os.Handler.dispatchMessage(Handler.java:99) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.os.Looper.loop(Looper.java:123) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.app.ActivityThread.main(ActivityThread.java:3687) 10-05 17:10:11.635: E/AndroidRuntime(25222): at java.lang.reflect.Method.invokeNative(Native Method) 10-05 17:10:11.635: E/AndroidRuntime(25222): at java.lang.reflect.Method.invoke(Method.java:507) 10-05 17:10:11.635: E/AndroidRuntime(25222): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842) 10-05 17:10:11.635: E/AndroidRuntime(25222): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 10-05 17:10:11.635: E/AndroidRuntime(25222): at dalvik.system.NativeStart.main(Native Method) 10-05 17:10:11.635: E/AndroidRuntime(25222): Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class <unknown> 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.createView(LayoutInflater.java:518) 10-05 17:10:11.635: E/AndroidRuntime(25222): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:682) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.rInflate(LayoutInflater.java:619) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.inflate(LayoutInflater.java:383) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 10-05 17:10:11.635: E/AndroidRuntime(25222): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:209) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.app.Activity.setContentView(Activity.java:1657) 10-05 17:10:11.635: E/AndroidRuntime(25222): at com.shopassistent.Login_Activity.onCreate(Login_Activity.java:12) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615) 10-05 17:10:11.635: E/AndroidRuntime(25222): ... 11 more 10-05 17:10:11.635: E/AndroidRuntime(25222): Caused by: java.lang.reflect.InvocationTargetException 10-05 17:10:11.635: E/AndroidRuntime(25222): at java.lang.reflect.Constructor.constructNative(Native Method) 10-05 17:10:11.635: E/AndroidRuntime(25222): at java.lang.reflect.Constructor.newInstance(Constructor.java:415) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.view.LayoutInflater.createView(LayoutInflater.java:505) 10-05 17:10:11.635: E/AndroidRuntime(25222): ... 26 more 10-05 17:10:11.635: E/AndroidRuntime(25222): Caused by: android.content.res.Resources$NotFoundException: File #ffffff from drawable resource ID #0x7f040009: .xml extension required 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.content.res.Resources.loadColorStateList(Resources.java:1824) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.content.res.TypedArray.getColorStateList(TypedArray.java:342) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.widget.TextView.<init>(TextView.java:677) 10-05 17:10:11.635: E/AndroidRuntime(25222): at android.widget.TextView.<init>(TextView.java:369) 10-05 17:10:11.635: E/AndroidRuntime(25222): ... 29 more ``` Can anybody see where this error comes from?
Do you have background.xml? ``` Caused by: android.content.res.Resources$NotFoundException: File #ffffff from drawable resource ID #0x7f040009: .xml extension required ```
155963
I am attempting to optimize a Convolutional Neural Network using a grid search but am encountering an issue when I try to determine how many Dense and Convolutional layers should be used when doing a grid search. Ideally it would add the Convolutional Layers first (depending on the trial) and then add the Dense layers afterwards. ``` ### ~~~CREATING MODEL~~~ dense_layers = [0, 1, 2] conv_layers = [1, 2, 3] layer_sizes = [16, 32, 64, 128] layer_sizec1 = [16, 32, 64, 128] layer_sizec2 = [16, 32, 64, 128] layer_sizec3 = [16, 32, 64, 128] layer_size1d = [16, 32, 64, 128] layer_size2d = [16, 32, 64, 128] for dense_layer in dense_layers: for layer_sizec1 in layer_sizec1: for layer_sizec2 in layer_sizec2: for layer_sizec3 in layer_sizec3: for layer_size1d in layer_size1d: for layer_size2d in layer_size2d: for conv_layer in conv_layers: NAME = "{}-conv-{}-nodes-{}-dense-{}".format(conv_layer, layer_size, dense_layer, int(time.time())) print(NAME) model = Sequential() model.add(Conv2D(layer_size, (3, 3), input_shape = input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) if conv_layer == '1': model.add(Conv2D(layer_sizec1, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) if conv_layer == '2': model.add(Conv2D(layer_sizec1, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(layer_sizec2, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) if conv_layer == '3': model.add(Conv2D(layer_sizec1, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(layer_sizec2, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(layer_sizec3, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) if dense_layer == '0': if dense_layer == '1': model.add(Dense(layer_size1d)) model.add(Activation('relu')) if dense_layer == '2': model.add(Dense(layer_size1d)) model.add(Activation('relu')) model.add(Dense(layer_size2d)) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('sigmoid')) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam',metrics=['accuracy']) model.fit(X_train, Y_train, batch_size = 128, nb_epoch = 10, validation_data=(X_val, Y_val), callbacks = [tensorboard]) ``` It displays the following generic message after running. ``` Error Message: File "<ipython-input-33-f7d41bf08db6>", line 53 if dense_layer == '0': ^ IndentationError: unexpected indent ```
It works when you use the `x <- rlang::enquo(x)` and `name <- rlang::quo_name(x)` before the `if`-statement: ```r date_from_text <- function(df, x){ x <- rlang::enquo(x) name <- rlang::quo_name(x) if(!inherits(df[[name]], c("POSIXct", "POSIXt"))) { out <- dplyr::mutate(df, !!name := lubridate::ymd_hms(!!x)) } else { stop("Seems that column is in the right format already") } } ``` I changed the requirement in the `if`-statement to `!inherits(df[[name]], c("POSIXct", "POSIXt"))`. In your original code only the first element of the class vector would be checked, whereas inherits checks if any of the specified classes is inherited. ```r my.df <- tibble::tibble(time_text = as.character(as.POSIXct("2018-02-03 08:00:00", tz = "UTC") + rnorm(100, 0, 60*60*60))) my.df2 <- date_from_text(my.df, time_text) my.df2 # A tibble: 100 x 1 # time_text # <dttm> # 1 2018-02-06 18:38:46 # 2 2018-01-31 16:16:15 # 3 2018-02-04 05:52:32 # 4 2018-02-05 23:31:50 # 5 2018-02-06 13:00:34 # 6 2018-02-01 16:16:24 # 7 2018-02-05 15:09:45 # 8 2018-02-04 04:23:00 # 9 2018-02-03 06:55:18 # 10 2018-01-29 01:06:26 # ... with 90 more rows date_from_text(my.df2, time_text) ``` > > Error in date\_from\_text(my.df2, time\_text) : > Seems that column is in the right format already > > > Thanks to @KonradRudolph for improving this answer with his comments.
155997
Im creating a JOptionPane dialog box to take input from user to choose the type of cake they want to buy, but i only want to take in an integer value. I am very new to java programming and need some help using try, catch to only get an integer value. I have created "Cakes[]" array to store and retrieve the flavor of cake, price of cake and the number of cakes left. ``` do { do { String userinput = JOptionPane.showInputDialog(null, "Enter your choice of cake:" + "\n" + "1." + Cakes[0].getflavorofcake() + "(" + Cakes[0].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[0].getnofcaksleft() + "\n" + "2." + Cakes[1].getflavorofcake() + "(" + Cakes[1].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[1].getnofcaksleft() + "\n" + "3." + Cakes[2].getflavorofcake() + "(" + Cakes[2].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[2].getnofcaksleft() + "\n" + "4." + Cakes[3].getflavorofcake() + "(" + Cakes[3].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[3].getnofcaksleft() + "\n" + "5." + Cakes[4].getflavorofcake() + "(" + Cakes[4].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[4].getnofcaksleft(), "mini cake shop", JOptionPane.QUESTION_MESSAGE); choiceofcake = Integer.parseInt(userinput); showthatthereisnocakesleft(choiceofcake);//Method called to show user that the choiceofcake chosen is no longer available } while (Cakes[choiceofcake - 1].getnofcaksleft() < 1); if (choiceofcake > 5 || choiceofcake < 1) { JOptionPane.showMessageDialog(null, "Invalid input! Please enter in the range from 1 to 5", "Error", JOptionPane.ERROR_MESSAGE); } } while (choiceofcake > 5 || choiceofcake < 1); ```
wrap the ``` choiceofcake = Integer.parseInt(userinput); ``` with a try-catch ``` try { choiceofcake = Integer.parseInt(userinput); if (choiceofcake > 5 || choiceofcake < 1) { break; } } catch (NumberFormatException ee) { ee.printStatckTrace (); continue; } ```
156092
I'm trying to restore an old Angular project. After an `npm-install` and then `ng-serve` I get the following error > > Could not find API compiler-cli, function \_\_NGTOOLS\_PRIVATE\_API\_2 > > > The error is coming from the @ngtools package located at `..node_modules\@ngtools\webpack\src\ngtools_api.js:8:11)` my dependencies look as followed ``` "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/core": "2.0.0", "@angular/forms": "2.0.0", "@angular/http": "2.0.0", "@angular/platform-browser": "2.0.0", "@angular/platform-browser-dynamic": "2.0.0", "@angular/router": "3.0.0", "angular2-moment": "1.0.0-beta.5", "core-js": "^2.4.1", "ng2-bootstrap": "^1.1.16", "ng2-toastr": "^1.3.0", "rxjs": "5.0.1", "ts-helpers": "^1.1.1", "zone.js": "^0.6.23", "moment": "2.15.2", "karma-phantomjs-launcher": "^1.0.2" }, "devDependencies": { "@types/jasmine": "^2.2.30", "angular-cli": "1.0.0-beta.16", "bootstrap-sass": "^3.3.7", "codelyzer": "~0.0.26", "jasmine-core": "2.4.1", "jasmine-spec-reporter": "2.5.0", "karma": "1.2.0", "karma-chrome-launcher": "^2.0.0", "karma-cli": "^1.0.1", "karma-jasmine": "^1.0.2", "karma-remap-istanbul": "^0.2.1", "node-sass": "^3.10.1", "protractor": "4.0.14", "ts-node": "1.2.1", "tslint": "3.13.0", "typescript": "2.0.2", } ``` If I delete the nodes module folder I can get the Angluar version from `ng -v` ``` angular-cli: 1.0.0-beta.14 node: 9.11.1 os: win32 x64 ``` What would be the best course of action to get this project working again?
The problem basically is that your inner array is illegal. Swift arrays must consist of elements of a single type. You have two types of element, String and Array Of String. Swift tries to compensate but the result is that double indexing can’t work, not least because there is no way to know whether a particular element will have a String or an Array in it. The solution is to rearchitect completely. If your array entries all consist of the same pattern String plus String plus Array of String, then the pattern tells you what to do; that should be a custom struct, not an array at all.
156113
[Project Euler #11](http://projecteuler.net/problem=11) asks to find the largest product of four numbers of a grid, where the four numbers occur consecutive to each other vertically, horizontally, or diagonally. Here is my solution in Python. In addition to the usual code review, I have 2 extra questions (actually confessions of my laziness): 1. Would it be better if I compared products as in traditional way instead of using max(list)? Like: ``` if (current > max_product): max_product = current ``` 2. Would it be better if I used proper `for` loops instead of relying on `try`? Because in certain cases it gives `KeyError`. Because of these two shortcuts, I feel like I have cheated. Shall I worry about them or just ignore them? ``` yy = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48""" rows = yy.splitlines() d = {} x = 0 for row in rows: row_cels = row.split() y = 0 d[x] = {} for cell in row_cels: d[x].update({y: int(cell)}) y+=1 x+=1 def product(a, b, al="hori", r=4): try: res = 1 for xx in xrange(r): if al == "hori": # - res *= d[a][b+xx] elif al == "verti": # | res *= d[b+xx][a] elif al == "dia": # \ res *= d[a+xx][b+xx] elif al == "diarev": # / res *= d[a+xx][19-(b+xx)] return res except: return 0 hori = [] verti = [] dia = [] diarev = [] for x in xrange(0, 20): for y in xrange(0, 20): hori.append(product(x,y)) verti.append(product(x, y, "verti")) dia.append(product(x, y, "dia")) diarev.append(product(x, y, "diarev")) print max(max(hori), max(verti), max(dia), max(diarev)) ```
1. It's OK to use `max()`, reimplementing it yourself won't save time, especially since the Python version is possibly faster if it's written in C. It's possible to be more concise and clearer though: `max(hori + verti + dia + diarev)`. 2. You should use a list of list to represent a matrix, not a list of dictionaries. As `cat_baxter` points out, `d = [map(int, row.split()) for row in open('20x20.txt').read().splitlines()]` is enough to populate `d`. However if you're not familiar with list comprehensions and map, it's OK to use normal loops. 3. Python doesn't really have constants, but a convention is to do `VERTI = "verti"` and then use `VERTI` everywher, denoting that it is a constant ("verti" is not a good name, by the way, "vertical" is better. Use code completion.) 4. `try: ... except: ...` is bad practice, you need to catch specific exceptions (`KeyError` in this case). And you need to understand why those errors are thrown! This could be a bug in your code.
156713
I am using google analytics but when I debug with adb show me these messages. ``` 05-11 14:57:48.911 1681-1912/? W/GAv4-SVC: Network compressed POST connection error: java.net.ConnectException: failed to connect to ssl.google-analytics.com/127.0.0.1 (port 443) after 60000ms: isConnected failed: ECONNREFUSED (Connection refused) 05-11 14:58:43.591 7281-7281/? I/GAv4: Google Analytics 8.2.98 is starting up. To enable debug logging on a device run: adb shell setprop log.tag.GAv4 DEBUG adb logcat -s GAv4 05-11 14:58:43.631 7281-7281/? W/GAv4: AnalyticsReceiver is not registered or is disabled. Register the receiver for reliable dispatching on non-Google Play devices. See some url for instructions. 05-11 14:58:43.681 7281-7281/? D/GAv4: setLocalDispatchPeriod (sec): 60 05-11 14:58:43.681 7281-7330/? W/GAv4: AnalyticsService not registered in the app manifest. Hits might not be delivered reliably. See some url for instructions. 05-11 14:58:48.131 7237-7268/? I/GAV3: Thread[GAThread,5,main]: No campaign data found. 05-11 14:59:23.171 7761-7785/? I/GAv4: Google Analytics 8.1.15 is starting up. To enable debug logging on a device run: adb shell setprop log.tag.GAv4 DEBUG adb logcat -s GAv4 05-11 14:59:23.181 7761-7785/? W/GAv4: AnalyticsReceiver is not registered or is disabled. Register the receiver for reliable dispatching on non-Google Play devices. See some url for instructions. 05-11 14:59:23.191 7761-7785/? W/GAv4: CampaignTrackingReceiver is not registered, not exported or is disabled. Installation campaign tracking is not possible. See some url for instructions. 05-11 14:59:23.191 7761-7791/? W/GAv4: AnalyticsService not registered in the app manifest. Hits might not be delivered reliably. See some url for instructions. 05-11 14:59:23.591 7817-7817/com.example.admin.helloanalytics I/GAv4: Google Analytics 8.4.87 is starting up. To enable debug logging on a device run: adb shell setprop log.tag.GAv4 DEBUG adb logcat -s GAv4 05-11 14:59:23.591 7817-7817/com.example.admin.helloanalytics D/GAv4: XML config - app name: XXXXX 05-11 14:59:23.591 7817-7817/com.example.admin.helloanalytics D/GAv4: XML config - app version: 1.0 05-11 14:59:23.591 7817-7817/com.example.admin.helloanalytics D/GAv4: XML config - dispatch period (sec): 1800 05-11 14:59:23.591 7817-7817/com.example.admin.helloanalytics D/GAv4: XML config - dry run: false 05-11 14:59:23.601 7817-7817/com.example.admin.helloanalytics D/GAv4: setLocalDispatchPeriod (sec): 1800 05-11 14:59:23.881 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit delivery requested: ht=1462962563740, _s=50, _v=ma8.4.87, a=2122668187, adid=7d85460d-4d41-4d41-8225-b1499b154b44, aid=com.example.admin.helloanalytics, an=XXXXX, ate=1, av=1.0, cd=com.example.admin.helloanalytics.MainActivity, cid=577d2178-6c7e-431d-a258-cea382dd9263, sr=540x960, t=screenview, tid=UA-77544180-1, ul=en-us, v=1 05-11 14:59:23.921 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit delivery requested: ht=1462962563740, _s=51, _v=ma8.4.87, a=2122668188, adid=7d85460d-4d41-4d41-8225-b1499b154b44, aid=com.example.admin.helloanalytics, an=XXXXX, ate=1, av=1.0, cd=com.example.admin.helloanalytics.MainActivity, cid=577d2178-6c7e-431d-a258-cea382dd9263, sc=start, sr=540x960, t=screenview, tid=UA-77544180-1, ul=en-us, v=1 05-11 14:59:23.991 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit sent to the device AnalyticsService for delivery 05-11 14:59:24.531 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit sent to the device AnalyticsService for delivery 05-11 14:59:24.801 7915-7915/? W/GAV2: Thread[main,5,main]: Need to call initialize() and be in fallback mode to start dispatch. 05-11 14:59:25.151 7964-7964/? I/GAv4: Google Analytics 8.2.98 is starting up. To enable debug logging on a device run: adb shell setprop log.tag.GAv4 DEBUG adb logcat -s GAv4 05-11 14:59:25.161 7964-7964/? W/GAv4: AnalyticsReceiver is not registered or is disabled. Register the receiver for reliable dispatching on non-Google Play devices. See some url for instructions. 05-11 14:59:25.191 7964-7964/? D/GAv4: setLocalDispatchPeriod (sec): 60 05-11 14:59:25.191 7964-8007/? W/GAv4: AnalyticsService not registered in the app manifest. Hits might not be delivered reliably. See some url for instructions. 05-11 14:59:29.771 7915-7955/? I/GAV2: Thread[GAThread,5,main]: No campaign data found. 05-11 14:59:49.111 1681-1912/? W/GAv4-SVC: Network compressed POST connection error: java.net.ConnectException: failed to connect to ssl.google-analytics.com/127.0.0.1 (port 443) after 60000ms: isConnected failed: ECONNREFUSED (Connection refused) 05-11 15:00:12.531 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit delivery requested: ht=1462962612433, _s=52, _v=ma8.4.87, a=2122668189, adid=7d85460d-4d41-4d41-8225-b1499b154b44, aid=com.example.admin.helloanalytics, an=XXXXX, ate=1, av=1.0, cd=com.example.admin.helloanalytics.MainActivity, cid=577d2178-6c7e-431d-a258-cea382dd9263, ea=Share, ec=Action, sr=540x960, t=event, tid=UA-77544180-1, ul=en-us, v=1 05-11 15:00:12.621 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit sent to the device AnalyticsService for delivery 05-11 15:00:12.671 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit delivery requested: ht=1462962612569, _s=53, _v=ma8.4.87, a=2122668189, adid=7d85460d-4d41-4d41-8225-b1499b154b44, aid=com.example.admin.helloanalytics, an=XXXXX, ate=1, av=1.0, cd=com.example.admin.helloanalytics.Second, cid=577d2178-6c7e-431d-a258-cea382dd9263, sr=540x960, t=screenview, tid=UA-77544180-1, ul=en-us, v=1 05-11 15:00:12.691 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit delivery requested: ht=1462962612569, _s=54, _v=ma8.4.87, a=2122668190, adid=7d85460d-4d41-4d41-8225-b1499b154b44, aid=com.example.admin.helloanalytics, an=XXXXX, ate=1, av=1.0, cd=com.example.admin.helloanalytics.Second, cid=577d2178-6c7e-431d-a258-cea382dd9263, sr=540x960, t=screenview, tid=UA-77544180-1, ul=en-us, v=1 05-11 15:00:12.751 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit sent to the device AnalyticsService for delivery 05-11 15:00:12.791 7817-7872/com.example.admin.helloanalytics D/GAv4: Hit sent to the device AnalyticsService for delivery ``` Is my google analytics connect or is it true ? Here is my MainActivity : ``` import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; public class MainActivity extends AppCompatActivity { private Tracker mTracker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button BTN = (Button) findViewById(R.id.BTN); BTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mTracker.send(new HitBuilders.EventBuilder() .setCategory("Action") .setAction("Share") .build()); Intent intent = new Intent(MainActivity.this,Second.class); startActivity(intent); } }); MobikulApplication mMobikulApplication = (MobikulApplication) getApplication(); mTracker = mMobikulApplication.getDefaultTracker(); String name = this.getClass().getName(); mTracker.setScreenName("" + name); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); } } ``` And here is my analytics\_global\_config.xml : ``` <?xml version="1.0" encoding="utf-8" ?> <resources> <!-- The application name. Defaults to name specified for the application label --> <string name="ga_appName">XXXXX</string> <!-- The application version. Defaults to android:versionName specified in the AndroidManifest.xml --> <string name="ga_appVersion">1.0</string> <!-- The dispatching period in seconds when Google Play services is unavailable. The default period is 1800 seconds or 30 minutes --> <integer name="ga_dispatchPeriod">1800</integer> <!-- Enable dry run mode. Default is false --> <bool name="ga_dryRun">false</bool> </resources> ``` And I add json in my app project. If need to see all project I can show it. Thanks
> > Make sure you have **AnalyticService** enable in `Manifest` > > > ``` <service android:name="com.google.android.gms.analytics.AnalyticsService" android:enabled="true" android:exported="false"/> ``` And you haven't specify the **GA\_PROPERTY\_ID**(Tracking ID) in `analytics_global_config.xml` you can't track without an ID Edit: Sample sharing **EventLogUtil.class** ``` public class EventLogUtil { private static final String TAG = EventLogUtil.class.getSimpleName(); private FirebaseAnalytics firebaseAnalytics; private static EventLogUtil eventLogUtil; /** * Param names can be up to 40 characters long, may only contain alphanumeric characters and * underscores ("_"), and must start with an alphabetic character. Param values can be up to * 100 characters long. The "firebase_", "google_" and "ga_" prefixes are reserved and should * not be used. * https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Param */ private static final int FIRE_BASE_MAX_KEY_EVENT_LENGTH = 40; private static final int FIRE_BASE_MAX_VALUE_EVENT_LENGTH = 100; private static final int FIRE_BASE_MAX_USER_PROPERTY_LENGTH = 36; private EventLogUtil() { } private EventLogUtil(Context context) { if (firebaseAnalytics == null) { firebaseAnalytics = FirebaseAnalytics.getInstance(context); } } public static EventLogUtil getInstance(Context context) { if (eventLogUtil == null) { eventLogUtil = new EventLogUtil(context); } return eventLogUtil; } public void logEvent(String eventName, Map<String, String> eventParams) { CustomEvent customEvent = new CustomEvent(eventName); Bundle params = new Bundle(); if (eventParams != null && !eventParams.isEmpty()) { eventParams.put("time_stamp", getCurrentUTCTime("MM/dd/yyyy h:mm:ss a")); for (Map.Entry<String, String> entry : eventParams.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); key = removeExceedingCharacters(key, FIRE_BASE_MAX_KEY_EVENT_LENGTH); value = removeExceedingCharacters(value, FIRE_BASE_MAX_VALUE_EVENT_LENGTH); customEvent.putCustomAttribute(key, value); params.putString(key, value); } } firebaseAnalytics.logEvent(eventName, params); Answers.getInstance().logCustom(customEvent); } public void setUserProperties(User user) { try { String baseJid = "anyID"; firebaseAnalytics.setUserId(baseJid); firebaseAnalytics.setUserProperty("UserJid", removeExceedingCharacters(baseJid, FIRE_BASE_MAX_USER_PROPERTY_LENGTH)); firebaseAnalytics.setUserProperty("UserName", removeExceedingCharacters(user.getFullName(), FIRE_BASE_MAX_USER_PROPERTY_LENGTH)); } catch (Exception e) { LogUtils.d(TAG, e.getMessage()); } } public void setAnalyticsCollectionStatus(boolean status) { firebaseAnalytics.setAnalyticsCollectionEnabled(status); } public void trackCurrentScreen(Activity activity, String screenName) { firebaseAnalytics.setCurrentScreen(activity, screenName, null); Answers.getInstance().logContentView(new ContentViewEvent() .putContentName(screenName) .putContentType("Screen View") .putContentId("screen-activity")); } public void trackException(Exception e) { FirebaseCrash.report(e); } public static String getCurrentUTCTime(String dateFormat) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return simpleDateFormat.format(new Date()); } public static String removeExceedingCharacters(final String string, final int maxLength) { try { if (string != null && !string.isEmpty() && string.length() > maxLength) { return string.substring(0, maxLength); } } catch (Exception e) { LogUtils.d(TAG, e.getMessage()); } return string; } } ``` And for including fabric [**see this**](https://stackoverflow.com/a/45177733/3496570) call it like ``` HashMap<String, String> hashForAnalytics = new HashMap<>(); hashForAnalytics.put(SOAP_SERVICE_EVENT_FAILURE, FALSE_RESPONSE + " " + serviceName); EventLogUtil.getInstance(context).logEvent(SOAP_SERVICE_EVENT, hashForAnalytics); ```