qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
19,711,349
Welcome) have a little trouble, help solve them, please. Here's the code: ``` import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JComponent; import javax.swing.JFrame; class MyCanvas extends JComponent { public void paint(Graphics g) { Image img1 = Toolkit.getDefaultToolkit().getImage("yourFile.gif"); int width = img1.getWidth(this); int height = img1.getHeight(this); int scale = 2; int w = scale * width; int h = scale * height; // explicitly specify width (w) and height (h) g.drawImage(img1, 10, 10, (int) w, (int) h, this); } } public class Graphics2DDrawScaleImage { public static void main(String[] a) { JFrame window = new JFrame(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setBounds(30, 30, 300, 300); window.getContentPane().add(new MyCanvas()); window.setVisible(true); } } ``` If we run the code, we have displayed a picture.But my task is to bring many of the same image but in different places. How to do it?) If you do so: ``` for(int i = 0; i < 500 ; i+=100){ g.drawImage(img1, 10+i, 10, (int) w, (int) h, this); } ``` Then the images are displayed in a row. And I would like more randoml
2013/10/31
[ "https://Stackoverflow.com/questions/19711349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2839008/" ]
> > And I would like more random > > > Use the `Random` class to generate an integer within your specified range. You would want to use `getWidth()` and `getHeight()` to get the bounds of your component so you can specify a realistic range. Then you can randomize the x, y values. ``` Random random = new Random(); int x = random(getWidth()); int y = random(getHeight(); ``` You might also want to consider the width/height of your images to make sure they are fully contained in the panel. Also, custom painting is done by overriding the `paintComponent(...)` method not the paint() method.
You are indeed correct that you can draw the same image multiple times by calling ``` g.drawImage(img1, x, y, (int) w, (int) h, this); ``` multiple times for different values of x and y. So, basically what you need to do is randomizing the coordinates. That can be done by using the handy `Random` class in Java: ``` Random random = new Random(); int x = random.nextInt(300); int y = random.nextInt(300); ``` This will generate random coordinates between (0, 0) and (299, 299).
10,843
If I have road tires that have a recommended pressure of 110 PSI and maximum of 120 PSI can I safely pump my tires up to that level or does the inner tube effect the maximum? I currently have the tires pumped up to 90 PSI however the question [What Pressure Should I Run My Road Bike Tyres At](https://bicycles.stackexchange.com/questions/2744/what-pressure-should-i-run-my-road-bike-tyres-at) seems to indicate I should go for the full 110. It feels when I'm pumping that it would be very hard to pump above the 90 mark and I am wondering if the quality of the inner tube (or a inner tube max PSI) could be the reason. Should I just go for it and try to pump it up to 110 PSI or am I best off leaving my tires at 90 PSI?
2012/08/16
[ "https://bicycles.stackexchange.com/questions/10843", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/4731/" ]
The inner tube has no significant effect on max pressure. The valve stem area is the only area sensitive to pressure, and in general the valve can withstand 200 PSI or better. (And if you exceed whatever limit there is the result is "catastrophic" failure, not simply the inability to pump in more air.) What it sounds like you're noticing is the geometry of the pump. A piston pump has a compression ratio, just like a cylinder in an engine, and the max pressure that the pump can generate is that compression ratio multiplied times the 14 PSI of atmospheric pressure. In general, pumps are designed either to move a lot of air at low compression ratio to fill low pressure tires quickly, or to move less air at a higher compression ratio to be able to fill high pressure tires at all (though more slowly). Good quality pumps will be advertised with a stated maximum pressure, and you can fill tires reasonably fast to 80-90% of that max pressure, after which progress will slow to a crawl. So when you shop for a pump you need to pay attention to that number.
In addition to the tire limiting PSI, rim tape is also a factor. Cheap rim tape can prevent higher pressures since they, and the tube, will dimple into the spoke holes of the wheel. Over time, this can cause the tube to fail.
1,484,739
I'm new to C++, and I'm confused about arrays and pointers. Could someone tell me how I can properly delete a pointer. Like for example, ``` int *foo; foo = new int[10]; delete foo; ``` or ``` delete [] foo; ``` Thanks.
2009/09/27
[ "https://Stackoverflow.com/questions/1484739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/130278/" ]
If you allocate an array of objects using the `new []` operator then you must use the `delete []` operator and therefore the non-array `new` can only be used with the non-array `delete`. ``` int *a = new int[10]; int *b = new int; delete [] a; delete b; ```
You walked in the front door and left it open. Then you walked through to the back door and tried to close it but you smashed it because it was already closed. ``` foo = new int [10]; // so when you open the front door delete [] foo; // please remember to close the front door. foo = new int; // and when you open the back door delete foo; // please remember to close the back door. ``` Don't mix them up!
20,941,935
I know my JSON is valid, I'm wanting to pull all the KEY's out of the array and put them in an object. However it seems I can either access ONE objects Key or Value, the entire array, or one key value pair. I have not figured out how to parse out all the keys, or all the values in the array. Here is what I've tried: print\_r($json\_obj) yields: ``` Array ( [0] => Array ( [0] => uploads/featured/doublewm-4097.jpg [1] => featured ) [1] => Array ( [0] => uploads/featured/moon-5469.jpg [1] => featured ) ) ``` print\_r($json\_obj[0][1]) yields: ``` featured ``` print\_r($json\_obj[1][0]) yields: ``` uploads/featured/moon-5469.jpg ``` print\_r($json\_obj[1][1]) yeilds: ``` featured ``` print\_r($json\_obj[0][0]) yields: ``` uploads/featured/doublewm-4097.jpg ``` PHP Code: ``` <?php $resultSet = '[["uploads/featured/doublewm-4097.jpg","featured"], ["uploads/featured/moon-5469.jpg","featured"]]'; $json_obj = json_decode($resultSet); // print_r($json_obj); print_r($json_obj[0][1]); ?> ``` The JSON validates per JSONLint ``` [ [ "uploads/featured/doublewm-4097.jpg", "featured" ], [ "uploads/featured/moon-5469.jpg", "featured" ] ] ``` I would like to end up with a object with all the keys in the json\_obj... ie: ``` json_obj = array( 'uploads/featured/moon-5469.jpg', 'uploads/featured/doublewm-4097.jpg' ); ```
2014/01/06
[ "https://Stackoverflow.com/questions/20941935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3161804/" ]
If your input is always in the same format, you can handle it like this ``` $tmp = json_decode($resultSet); $json_obj = array(); foreach ($tmp as $values) { array_push($json_obj, $values[0]); } ``` This will give you `$json_obj` in the desired format with a hardcoded `$resultSet` like the one you provided.
maybe this is what you are looking for: json encode server-side like: ``` echo json_encode($html); ``` json parse clientside like ``` var str = JSON.parse(data); alert (JSON.stringify(str)) ```
645,038
No matter how many tabs I have, Firefox only shows one item on the taskbar. I'm **not** talking about the previews when you hover over the *item on the taskbar*, that works fine. It only displays 2 or more items on the taskbar if I have 2 or more windows open. Is there a way to do this for each tab? Or even **more preferably** for each tab group? ![enter image description here](https://i.stack.imgur.com/MTKlK.png)
2013/09/13
[ "https://superuser.com/questions/645038", "https://superuser.com", "https://superuser.com/users/127809/" ]
You can `echo` a bell - `\a` in the remote terminal: `./long_process ; echo -e '\a'` Some terminal emulators will play some sort of sound and might show a notifications. iTerm2, in particular, will show a notification and play a sound, if process' tab is not focused. Also, notice that I used `;` to separate commands. This way you will be notify even when command returns non-zero status while `&&` will only run if command succeeds.
There's a really easy way to cause iTerm2 to bounce in the dock until you switch over to it. It's great. To use it, you just need to use iTerm2 and be able to install software on the host you're ssh'd into. Here's how you do it, 1. SSH into the host. 2. Install Shell Integration for iTerm2. On the Mac version of iTerm2 you do this by selecting iTerm2->Install Shell Integration. More info about how to install [here](https://iterm2.com/documentation-utilities.html) if you need it. 3. Execute your command ``` ./long_process && it2attention start ``` 4. You can also try ``` ./long_process && it2attention fireworks ```
43,718
Suppose I was hired as a Junior Manager from 2010 to 2012, then was promoted to Senior Manager from 2012 to 2014. On a resume/CV is it appropriate to list my title as Senior Manager (2010-2014)? Often on resumes/CVs on LinkedIn I see people who list the highest position they were promoted to along with the entire duration of their employment at the company, even when they were in more junior roles. Is this normal/reasonable practice?
2015/04/06
[ "https://workplace.stackexchange.com/questions/43718", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/33828/" ]
I do my CV like this as it shows to the recruiter / employer that i have worked at a company a preset period of time and during that period i was promoted several times. If you only list the final job title then it looks odd when there is a gap in your employment (Pre 2008 in below eg) period or if listed as 'Senior Developer 2000 - 2010' it looks like you held that role for 10 years when you really held it for 2 years. Employer: ABC Software Co (2000 - 2010) * Senior Developer (2008 - 2010) + Large description of role * Developer (2004 - 2008) + 1 line description of role (Unless job is still very relevant) * Junior Developer (2000 - 2004) + 1 line description of role or omit description if no longer relevant
> > On a resume/CV is it appropriate to list my title as Senior Manager > (2010-2014)? > > > **Yes,** But specify year as 2012-2014. Or I would list as "Currently working as Senior Manager". You can use your current profile as a Heading of Resume, LinkedIn profile and on your business cards (with or without duration). However you should list other positions with correct duration in "Work Experience" section of resume.
39,695,293
After upgrading to Mac OSX Sierra from El Capitan as soon as I run php it denies to run any php project which was previously installed on my system. That after exploring this issues on internet I came with these options... After running the below commands: ``` cd /etc/apache2/ sudo mv httpd.conf httpd.conf.sierra sudo mv httpd.conf~previous httpd.conf cd .. sudo cp php.ini-previous php.ini sudo apachectl restart ``` I made my php project work like a charm. But now I ran into an another issue. That is php mcrypt extension error. As I run php project (laravel 4.2 project) the project doesn't work and shows me the error - "PHP mcrypt extension required!" Please help me out with this.. My php.ini file's mcrypt line looks like this ``` ; Directory in which the loadable extensions (modules) reside. ; http://php.net/extension-dir ; extension_dir = "./" extension_dir = "/usr/lib/php/extensions/no-debug-non-zts-20121212/" ; extension_dl = On extension=mcrypt.so ; On windows: ; extension_dir = "ext" ``` Can you tell me what is wrong with my system.
2016/09/26
[ "https://Stackoverflow.com/questions/39695293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1563528/" ]
I fixed my problem... To make mcrypt extension work (if you get an error after upgrading) Then follow [this guide](https://coolestguidesontheplanet.com/install-mcrypt-for-php-on-mac-osx-10-10-yosemite-for-a-development-server/) from scratch... Please use the updated version of libmcrypt and php (php 5.6 - comes with OSX Sierra) from the mentioned guide (above). And if your mysql stops working after folowing the above process (as it happened to me :( ), then just remove all the .err files from directory **/usr/local/mysql/data** and **restart your mysql** again for more info - [see this](https://coolestguidesontheplanet.com/mysql-error-server-quit-without-updating-pid-file/) **To Restart MySQL use this command** ``` sudo /usr/local/mysql/support-files/mysql.server restart ``` Hope it helps you to upgrade your Mac OSX without any problems and saves your precious hours..!! :D
``` brew install homebrew/php/php70-mcrypt ```
67,930,508
I have two sorted lists and I need to find the odd ones out in each list. Currently I am using two list comprehensions with `not in`: ``` > if foo != bar: in_foo = [i for i in foo if i not in bar] in_bar = [i for i in bar if i not in foo] ``` However, this method doesn't take advantage of the sorted structure of the list. I can use an alternative method with a counter variable and recursion, but is there a more pythonic way of doing this? edit: sorted output is preferred. Thanks.
2021/06/11
[ "https://Stackoverflow.com/questions/67930508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14830842/" ]
Here is a comparison of three methods. The `with_intersection` method allows for repeated values within each list, the other two do not. The test considers two sorted lists, each with one million distinct integers. The `using_sorted` method takes advantage of the fact that both lists are sorted and does not use sets. At the same time, it is the slowest, most verbose and error-prone. ``` import numpy as np # only for data generation lst1 = np.random.randint(1, 20, 10**6).cumsum().tolist() lst2 = np.random.randint(1, 20, 10**6).cumsum().tolist() def with_intersection(lst1, lst2): common = set(lst1).intersection(lst2) res1 = [x for x in lst1 if x not in common] res2 = [x for x in lst2 if x not in common] return res1, res2 def set_then_sort(foo, bar): _foo = set(foo) _bar = set(bar) in_foo = _foo - _bar in_bar = _bar - _foo return sorted(in_foo), sorted(in_bar) def using_sorted(lst1, lst2): res1 = list() res2 = list() n1 = len(lst1) n2 = len(lst2) i = j = 0 while True: while i < n1 and j < n2 and lst1[i] < lst2[j]: res1.append(lst1[i]) i += 1 while j < n2 and i < n1 and lst1[i] > lst2[j]: res2.append(lst2[j]) j += 1 while i < n1 and j < n2 and lst1[i] == lst2[j]: i += 1 j += 1 if i == n1: res2.extend(lst2[j:]) break elif j == n2: res1.extend(lst1[i:]) break return res1, res2 assert with_intersection(lst1, lst2) == set_then_sort(lst1, lst2) == using_sorted(lst1, lst2) # %timeit with_intersection(lst1, lst2) # 306 ms # %timeit set_then_sort(lst1, lst2) # 491 ms # %timeit using_sorted(lst1, lst2) # 870 ms ```
By putting a None trailer at the end of each list, we can use iterators and focus on recording the differences. This algorithm is O(n+m): ``` foo = [1, 3, 4, 5] bar = [2, 4, 5, 6] i_foo = iter(foo + [None]) i_bar = iter(bar + [None]) n_foo = next(i_foo) n_bar = next(i_bar) in_foo = [] in_bar = [] while True: if n_foo is None: if n_bar is None: break in_bar.append(n_bar) n_bar = next(i_bar) continue if n_bar is None: in_foo.append(n_foo) n_foo = next(i_foo) if n_foo == n_bar: n_foo = next(i_foo) n_bar = next(i_bar) continue if n_foo < n_bar: in_foo.append(n_foo) n_foo = next(i_foo) else: in_bar.append(n_bar) n_bar = next(i_bar) print(in_foo, in_bar) # [1, 3] [2, 6] ```
39,661,184
I am doing an exercise. This is my interface. Now I want a mouse effect for two banners on the left: [![before](https://i.stack.imgur.com/vTHI9.png)](https://i.stack.imgur.com/vTHI9.png) When we move mouse on **each banner**, **that banner** will be replaced by a text box with same size, green background (without affecting the other banner) as following. [![after](https://i.stack.imgur.com/8jNSL.png)](https://i.stack.imgur.com/8jNSL.png) I know we can do this effect somehow with javascript, but since i am learning html, javascript is not easy for me, could you guys please help me as an example? This is my code: ```css #parent { overflow: hidden; margin:0px; } .right { border-left: 2px solid; border-color: rgb(215,217,216); padding-left: 20px; float: right; width: 270px; } .left { margin: 0px; overflow: hidden; height: 100%; } body { margin:0px; font-family: Calibri; } header20 { font-size: 16pt; } #inner { margin-left: 10px; width:730px; margin: 0 auto; } .row { display: flex; /* equal height of the children */ } ``` ```html <div id="parent" class="row"> <div class="right"> <br> <img src="http://dbclipart.com/wp-content/uploads/2016/03/Red-banner-clipart-image-1.png" style='width:250px;height:50px'> <br><br> <img src="http://images.clipartpanda.com/banner-20clipart-normal_1283818525.jpg" style='width:250px;height:50px'> <br><br> <table style='width:250px;background-color:rgb(211,238,208)'> <tr> <td> <header20><span style='color:rgb(17,56,96)'><b>This is the first table</b></span></header20> <ul style='padding-left:25px;margin-top:0px;magrin-bottom:0px'> <li>First point</li> <li>Second point</li> <li>Third point</li> </ul> </td> </tr> </table> <br> <table style='width:250px;background-color:rgb(211,238,208)'> <tr> <td> <header20><span style='color:rgb(17,56,96)'><b>This is the second table</b></span></header20> <ul style='padding-left:25px;margin-top:0px;magrin-bottom:0px'> <li>First point</li> <li>Second point</li> <li>Third point</li> </ul> </td> </tr> </table> <br> </div> <div class="left"> <div id="inner"> <br> <img src="smallpic.png" style='float:left;margin:0.1cm;width:85px;height:85px'> <p style='margin-left:2cm;font-size:22.0pt;margin-top:6pt;color:rgb(0,56,96)'><b>This is the title of the page - bla bla bla <br>Timetable for the next month</b></p> <p style='margin-left:1cm'> The first line of the content</p> <p style='margin-left:1cm'> The second line of the content</p> <p style='margin-left:1cm'> The third line of the content</p> <br> </div> <table align='center'> <tr> <td style='padding-right:25px'><img src="pic1.png" style='width:140px;height:115px'/></td> <td style ='padding-left:25px;padding-right:25px'><img src="pic2.png" style='width:140px;height:115px'/></td> <td style ='padding-left:25px'><img src="pic3.png" style='width:140px;height:115px'/></td> </tr> </table> </div> </div> ```
2016/09/23
[ "https://Stackoverflow.com/questions/39661184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196709/" ]
The java bean and spring-managed beans are different things. Java bean is indeed some object with particular naming convention where spring bean is different. What spring refers to as (spring managed) bean is simply instance of a class which lifecycle is managed by Spring framework. It doesn't have to follow the Java bean naming conventions etc. The most straight-forward usage of a bean is dependency injection. You can inject such spring-manged object (bean) into other beans - like controllers for example. You have several ways how to create a bean. [It's nicely described in the doc](http://docs.spring.io/spring-javaconfig/docs/1.0.0.m3/reference/html/creating-bean-definitions.html). Note that from spring standpoint even a the controller is just another bean which happen to have some extra features. To get started I would go with some spring-boot sample application. It saves you a lot of configuration and it's generally good starting point.
To save time for those who would like to know the answer to this question, on the Spring official site there is a nice explanation of [Spring Beans](http://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/html/beans.html#beans-introduction) and [high-level view of how Spring works](http://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/html/beans.html#beans-basics). The links refer to version 4.3.9 (the latest on time being), more updated info should be available [here](http://docs.spring.io/spring/docs/). The documentation says: > > In Spring, **the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans**. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, **a bean is simply one of many objects in your application**. > > > ... > > > The following diagram is a high-level view of how Spring works. [![enter image description here](https://i.stack.imgur.com/ikH9Q.png)](https://i.stack.imgur.com/ikH9Q.png) > > >
20,308,870
I have a Login table in MySql database . . In table there is a column by cname and one of the value is 'Raghu'. My question is when i write the query as ``` Select *from Login where cname='raghu'; ``` Then it is retrieving the record which contains 'Raghu' . I want it to retrieve according to case . How can I retrieve with case sensitively, values in the data of tables.
2013/12/01
[ "https://Stackoverflow.com/questions/20308870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007137/" ]
Use: [10.1.7.7. The BINARY Operator](http://dev.mysql.com/doc/refman/5.0/en/charset-binary-op.html) > > The BINARY operator casts the string following it to a binary string. This is an easy way to force a comparison to be done byte by byte rather than character by character. > > > ``` Select * from Login where binary cname='raghu'; ```
Can you try this, you can use `LOWER` FUNCTION in either column name `LOWER('cname')` or in value `LOWER('raghu')`; ``` Select *from Login where LOWER(`cname`) = 'raghu'; ```
408,719
I wonder "which quantity" is conserved in relation to a specific symmetry. I guess it is in some meaning simply the generator (in the context of Lie theory) of the symmetry, as it is true for angular momentum (conserved) being generator of rotation (symmetry). I want clear formulation of idea but I can't complete it: Let $M$ be configuration manifold of a classical system. $L(q,\dot q,t)$ it's Lagrangian, $h^s: M\rightarrow M$ a one-parameter group of diffeomorphisms of $M$ which preserves $L$. then $$I(q,\dot q)= \frac{\partial L}{\partial \dot q}\frac{d h^s(q)}{ds}|\_{s=0}$$ is a conserved quantity along trajectory $q$. on the other hand $h^s$ produce a flow on manifold and we may denote its vector field by $\frac{\partial}{\partial s}$ which we may call generator of diffeomorphism. *so in particular the generator of diffeomorphism along a trajectory $q$ is a vector field along it not a scalar field to could be discussed a conserved quantity or not* (for example conserved quantity in relation to rotation be its generator namely angular momentum) you may say by formula of $I$ just act $\frac{\partial L}{\partial \dot q}$ on this vector field to get a scalar field! but why?!! (I mean by which principle?). and then in what meaning $I$ is genarator of $h^s$?
2018/05/28
[ "https://physics.stackexchange.com/questions/408719", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/118357/" ]
Forget that velocity is a vector $\vec{v}$ for the moment, and just let $v:=\vec{v}$ denote the speed (i.e. modulus of the velocity vector). This is just a non-negative real random variable, and you're asking why $\langle v^2\rangle\ne\langle v\rangle^2$. But famously, the difference between these two expressions is just the variance of $v$.
One is defined as $$ \langle |v|\rangle=\frac{\int |v|f(v)\mathrm{d}v}{\int f(v)\mathrm{d}v} $$ while the other $$ \langle v^2\rangle=\frac{\int v^2f(v)\mathrm{d}v}{\int f(v)\mathrm{d}v}. $$ It is clear that $\langle |v|\rangle^2\neq\langle v^2\rangle$.
144,714
I've been working on a fitness journal app and have been trying to come up with a design to show your sets in a summary view. [![summary screenshot](https://i.stack.imgur.com/gHKUG.jpg)](https://i.stack.imgur.com/gHKUG.jpg) The sets are displayed in chronological order. A super set is when you alternate between 2 or more exercises. In this case, 1 set for triceps followed by a set for biceps and repeat. The best solution I was able to come up with is what you see. If you press on the slightly opaque exercise name, it switches and highlight that exercise and it's sets. However I feel like this seems cluttered and disorganized. I'm not really sure what to even search for to get some inspiration. Looking up alternating lists and such didn't seem to help. Does anyone have any suggestions to point me in the right direction for how I should go about this? Just FYI I'm not a designer, I'm a developer so please excuse the rough design
2022/10/20
[ "https://ux.stackexchange.com/questions/144714", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/162621/" ]
I'm wondering if you could try being specific. Instead of 'superset' (or in addition to), you could trying saying what they actually do, which is alternate the exercise. You also have a lot of repetitive elements overall. The mental model most of us have for weight training is: **Weight** (times) **Reps** Instead of listing those 2 elements (plus bullet points on each line), try using table headers, and test with users if they can grasp the information as quickly (one disadvantage might be scrolling, if the table headers are temporarily out of the viewport). #### Expressing the alternating sequence v1: try a label system them separate from the exercise names v2: another thought is to condense each exercise to take the first letters of each word and build a shorthand element you can alternate: [![enter image description here](https://i.stack.imgur.com/zotsV.jpg)](https://i.stack.imgur.com/zotsV.jpg) Some caveats: The key needs to unique, in that you would need to make sure any 2 exercises do not share the same one or two first letters, but there might be a way here to indicate the alternating between the two exercises.
Gym Dashboard ------------- These types of designs are called **Dashboards**, specifically, the one referred to in the question, **Gym Dashboard**, **Fitness Dashboard** or **Training Dashboard**. If what you need are design alternatives, you can find several solutions in [Dribbble](https://dribbble.com/search/gym-dashboard) where you will find quite resolved application interfaces [![enter image description here](https://i.stack.imgur.com/zIhGF.png)](https://i.stack.imgur.com/zIhGF.png) Regarding the attached image, I would think about: * Accompany relevant texts with icons: weight, exercise, repetitions * Replace repeated texts with a single one, for example, the reps column should not have the word *rep* in each case * Bulleted lists are fine for text, but they are unclear on screen graphics, I would replace them with frames or graphics
66,093
I did try using the plugin Front End Users but this clashes with something as it prevents access to some front end pages. So I need to manually just set it so that anyone who isn't one of two usernames (or roles) can't access wp-admin.
2012/09/24
[ "https://wordpress.stackexchange.com/questions/66093", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14739/" ]
Just revisited that answer as it wasn't updated in a long time. Year is 2021. The accepted answer is checking whether the current page is a `wp-login.php` page **OR** an admin page **WHILE** using an `admin_init` hook, this is nonsense. [`admin_init`](https://developer.wordpress.org/reference/hooks/admin_init/) fires as an admin screen or script is being initialized. It does **NOT** just run on user-facing admin screens. It runs on `admin-ajax.php` and `admin-post.php` as well. In no cases whatsoever will it fire on a `wp-login.php` as it is **NOT** an admin screen. Tho it will indeed fire upon an ajax request, therefore that case should be handle. [`wp_doing_ajax()`](https://developer.wordpress.org/reference/functions/wp_doing_ajax/) determines whether the current request is a WordPress Ajax request. In the following example I'm using the `delete_posts` user capability to allow `admin`, `editor` and `author` access to the Wordpress backend. Refer to the [Capability vs. Role Table](https://wordpress.org/support/article/roles-and-capabilities/#capability-vs-role-table) for a more restrictive approach. As a reminder here are the default Wordpress roles ([Summary of Roles](https://wordpress.org/support/article/roles-and-capabilities/#summary-of-roles)): > > super admin `→` admin `→` editor `→` author `→` contributor `→` subscriber. > > > With a single site WordPress installation, Administrators are, in effect, Super Admins. I've chosen to use [`wp_die()`](https://developer.wordpress.org/reference/functions/wp_die/) instead of blindly redirecting users. `wp_die()` offer some kind of user onboarding as it kills Wordpress execution and displays an HTML page with an error message. The same approach could be done with redirecting users to a 404 page. Anything that explain the situation is better than a blind home page redirect. ``` add_action( 'admin_init', 'restrict_wpadmin_access' ); if ( ! function_exists( 'restrict_wpadmin_access' ) ) { function restrict_wpadmin_access() { if ( wp_doing_ajax() || current_user_can( 'delete_posts' ) ) { return; } else { header( 'Refresh: 2; ' . esc_url( home_url() ) ); $args = array( 'back_link' => true, ); wp_die( 'Restricted access.', 'Error', $args ); }; }; }; ``` To prevent the default redirection to the `wp-admin.php` upon login I'm using the [`login_redirect`](https://developer.wordpress.org/reference/hooks/login_redirect/) hook filter which Filters the login redirect URL. I'm redirecting them to their own profile page using [`get_author_posts_url()`](https://developer.wordpress.org/reference/functions/get_author_posts_url/), but you can easily redirect to whatever page you would like. You could also conditionally redirect based on the user role (eg: admin to the admin page, rest to profile), everything is explained on the CODEX page example section. ``` add_filter( 'login_redirect', 'redirect_user_to_profile_on_login', 10, 3 ); if ( ! function_exists( 'redirect_user_to_profile_on_login' ) ) { function redirect_user_to_profile_on_login( $redirect_to, $requested_redirect_to, $user ) { if ( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) { $redirect_to = esc_url( get_author_posts_url( $user->ID ) ); }; return $redirect_to; }; }; ```
Based on the answer provided by @kaiser (thank you btw), this is my working code, just in any case someone needs it. It is placed in `functions.php` file. The condition used is, if the user **can't** `manage_options` or `edit_posts`. ``` function wpse66093_no_admin_access() { $redirect = home_url( '/' ); if ( ! ( current_user_can( 'manage_options' ) || current_user_can( 'edit_posts' ) ) ) exit( wp_redirect( $redirect ) ); } add_action( 'admin_init', 'wpse66093_no_admin_access', 100 ); ```
21,749,798
I occasionally have react components that are conceptually stateful which I want to reset. The ideal behavior would be equivalent to removing the old component and readding a new, pristine component. React provides a method `setState` which allows setting the components own explicit state, but that excludes implicit state such as browser focus and form state, and it also excludes the state of its children. Catching all that indirect state can be a tricky task, and I'd prefer to solve it rigorously and completely rather that playing whack-a-mole with every new bit of surprising state. Is there an API or pattern to do this? **Edit:** I made a trivial example demonstrating the `this.replaceState(this.getInitialState())` approach and contrasting it with the `this.setState(this.getInitialState())` approach: [jsfiddle](https://jsfiddle.net/emn13/kdrzk6gh/) - `replaceState` is more robust.
2014/02/13
[ "https://Stackoverflow.com/questions/21749798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42921/" ]
You should actually avoid `replaceState` and use `setState` instead. The docs say that `replaceState` "may be removed entirely in a future version of React." I think it will most definitely be removed because `replaceState` doesn't really jive with the philosophy of React. It facilitates making a React component begin to feel kinda swiss knife-y. This grates against the natural growth of a React component of becoming smaller, and more purpose-made. In React, if you have to err on generalization or specialization: aim for specialization. As a corollary, the state tree for your component should have a certain parsimony (it's fine to tastefully break this rule if you're scaffolding out a brand-spanking new product though). Anyway this is how you do it. Similar to Ben's (accepted) answer above, but like this: ``` this.setState(this.getInitialState()); ``` Also (like Ben also said) in order to reset the "browser state" you need to remove that DOM node. Harness the power of the vdom and use a new `key` prop for that component. The new render will replace that component wholesale. Reference: <https://facebook.github.io/react/docs/component-api.html#replacestate>
Example code (reset the `MyFormComponent` and it's state after submitted successfully): ``` function render() { const [formkey, setFormkey] = useState( Date.now() ) return <> <MyFormComponent key={formkey} handleSubmitted={()=>{ setFormkey( Date.now() ) }}/> </> } ```
3,733,234
I am interested to know the difference between `this` and `base` object in C#. What is the best practice when using them?
2010/09/17
[ "https://Stackoverflow.com/questions/3733234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167689/" ]
Darin is right on. An example may also help. (There wasn't an example when I initially posted. Now there is.) ``` class Base { protected virtual void SayHi() { Console.WriteLine("Base says hi!"); } } class Derived : Base { protected override void SayHi() { Console.WriteLine("Derived says hi!"); } public void DoIt() { base.SayHi(); this.SayHi(); } } ``` The above prints "Base says hi!" followed by "Derived says hi!"
`this` refers to the current class instance. `base` refers to the base class of the current instance, that is, the class from which it is derived. If the current class is not explicitly derived from anything `base` will refer to the `System.Object` class (I think).
14,136,636
I want to connect a `MySql` DB with my android application. However, I **DON'T** want to/**CAN'T** use `PHP` for doing this. Almost all solution for `MySql` connection with android on internet uses `PHP`. I read somewhere that, If one don't want to use `PHP` then `web service` should be used. But I'm not able to find any tutorial/sample example for the same. Any help appreciated.
2013/01/03
[ "https://Stackoverflow.com/questions/14136636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061728/" ]
It seems you're mixing up some things. A web service is simply some code on the internet (web) which allows you to receive and send information to a server, where it is saved per example in a database. PHP is just a language, in which you can write a web service. You can use a vast array of languages to create a web service ( read: expose your database) to other devices. Among others, you can easily do this in Java, .NET, Python ... If you're looking for a way to connect to an external database without any web service / API in between, i'll have to disappoint you with the news that this is not supported by Android. Most examples of a simple web service / a bunch of scripts contain PHP since this is probably the easiest and can be used on pretty much any server.
A webservice, is as it's called, a service, meaning that you have one side consuming it (the android client). if all you want is a persistent storage, you could use SQLite which is an SQL compliant solution which exists within android. If it's possible to SSH to a server via Android, you could use that to connect to mysql, because the only other solution involves having mysql binaries installed locally on your android machine, and that's not possible AS FAR AS I KNOW, on Android.
2,385,617
I have numbers in javascript from 01(int) to 09(int) and I want add 1(int) to each one. For example: ``` 01 + 1 = 2 02 + 1 = 3 ``` But ``` 08 + 1 = 1 09 + 1 = 1 ``` I know the solution. I've defined them as float type. **But I want to learn, what is the reason for this result?** Thank you.
2010/03/05
[ "https://Stackoverflow.com/questions/2385617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286975/" ]
Javascript, like other languages, may treat numbers beginning with `0` as octal. That means only the digits 0 through 7 would be valid. What seems to be happening is that `08` and `09` are being treated as octal but, because they have invalid characters, those characters are being silently ignored. So what you're actually calculating is `0 + 1`. Alternatively, it may be that the entire `08` is being ignored and having `0` substituted for it. The best way would be to try `028 + 1` and see if you get `3` or `1` (or possibly even `30` if the interpretation is *really* weird).
Since you haven't specified the radix it is treated as octal numbers. `08` and `09` are not valid octal numbers. ``` parseInt(08,10) + 1; ``` will give you the correct result. See **[parseInt](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Functions/ParseInt)**
14,743,530
I am looking at production code in hadoop framework which does not make sense. Why are we using transient and why can't I make the utility method a static method (was told by the lead not to make isThinger a static method)? I looked up the transient keyword and it is related to serialization. Is serialization really used here? ``` //extending from MapReduceBase is a requirement of hadoop public static class MyMapper extends MapReduceBase { // why the use of transient keyword here? transient Utility utility; public void configure(JobConf job) { String test = job.get("key"); // seems silly that we have to create Utility instance. // can't we use a static method instead? utility = new Utility(); boolean res = utility.isThinger(test); foo (res); } void foo (boolean a) { } } public class Utility { final String stringToSearchFor = "ineverchange"; // it seems we could make this static. Why can't we? public boolean isThinger(String word) { boolean val = false; if (word.indexOf(stringToSearchFor) > 0) { val = true; } return val; } } ```
2013/02/07
[ "https://Stackoverflow.com/questions/14743530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62539/" ]
The problem in your code is the difference between the local mode (dev&testcases using it usually) and the distributed mode. In the local mode everything will be inside a single JVM, so you can safely assume that if you change a static variable (or a static method that shares some state, in your case `stringToSearchFor`) the change will be visible for the computation of every chunk of input. In distributed mode, every chunk is processed in its own JVM. So if you change the state (e.G. in `stringToSearchFor`) this won't be visible for every other process that runs on other hosts/jvms/tasks. This is an inconsistency that leads to the following design principles when writing map/reduce functions: 1. Be as stateless as possible. 2. If you need state (mutable classes for example), **never** declare references in the map/reduce classes `static` (otherwise it will behave different when testing/develop than in production) 3. Immutable constants (for example configuration keys as `String`) should be defined `static` and `final`. `transient` in Hadoop is pretty much useless, Hadoop is not serializing anything in the usercode (Mapper/Reducer) class/object. Only if **you** do something with the Java serialization which we don't know of, this will be an issue. *For your case*, if the `Utility` is really a utility and `stringToSearchFor` is an immutable constant (thus not be changed ever), you can safely declare `isThinger` as `static`. And please remove that `transient`, if you don't do any Java serialization with your `MapReduceBase`.
Unless there is something not shown here, then I suspect that the matter of making `Utility` a `static` method largely comes down to style. In particular, if you are not injecting the `Utility` instance rather than instantiating it on demand within, then it is rather pointless. As it is written, it cannot be overridden nor can it be more easily tested than `static` method. As for `transient`, you are right that it is unnecessary. I wouldn't be surprised if the original developer was using Serialization somewhere in the inheritance or implementation chain, and that they were avoiding a compiler warning by marking the non-serializable instance variable as `transient`.
2,147
What are really helpful math resources out there on the web? Please don't only post a link but a short description of what it does and why it is helpful. Please only one resource per answer and let the votes decide which are the best!
2009/10/23
[ "https://mathoverflow.net/questions/2147", "https://mathoverflow.net", "https://mathoverflow.net/users/1047/" ]
For enumerative combinatorics, it's hard to beat Sloane's [Online Encyclopedia of Integer Sequences](https://oeis.org/). It is what it says on the tin. A huge list of integer sequences, with references, links, formulas, and comments.
For knot theorists, there are two really cool databases: * [knotinfo](http://www.indiana.edu/~knotinfo) and its cousin [linkinfo](http://www.indiana.edu/~linkinfo), both maintained by Cha and Livingston. * [knotatlas](http://katlas.math.toronto.edu/wiki/Main_Page), maintained by Bar-Natan.
798,359
Can a 64bit Citrix server running a 32bit app through WoW64 handle just as many instances/users as the 32bit Citrix server equivalent? And if so if I up the memory in the 64bit server will the number of instances/users scale too? Or are there some strange memory considerations with a 64bit server running a 32bit app?
2009/04/28
[ "https://Stackoverflow.com/questions/798359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/97150/" ]
> > I'm replacing a submit button with an > anchor link. Since calling > form.submit() does not activate > onsubmit's, I'm finding it, and > eval()ing it myself. But I'd like to > check if the function exists before > just eval()ing what's there. – gms8994 > > > ``` <script type="text/javascript"> function onsubmitHandler() { alert('running onsubmit handler'); return true; } function testOnsubmitAndSubmit(f) { if (typeof f.onsubmit === 'function') { // onsubmit is executable, test the return value if (f.onsubmit()) { // onsubmit returns true, submit the form f.submit(); } } } </script> <form name="theForm" onsubmit="return onsubmitHandler();"> <a href="#" onclick=" testOnsubmitAndSubmit(document.forms['theForm']); return false; "></a> </form> ``` EDIT : missing parameter f in function testOnsubmitAndSubmit The above should work regardless of whether you assign the `onsubmit` HTML attribute or assign it in JavaScript: ``` document.forms['theForm'].onsubmit = onsubmitHandler; ```
using a string based variable as example and making use `instanceof Function` You register the function..assign the variable...check the variable is the name of function...do pre-process... assign the function to new var...then call the function. ``` function callMe(){ alert('You rang?'); } var value = 'callMe'; if (window[value] instanceof Function) { // do pre-process stuff // FYI the function has not actually been called yet console.log('callable function'); //now call function var fn = window[value]; fn(); } ```
417,118
Here we have a problem that seems very intuitive, but is hard to define mathematically. In Tic Tac Toe, we can find an equivalent of the game in any number of dimensions, it seems. The trick is to realize the the game is defined by *lines on which the characters can be placed* not how the board is drawn. 1D tic tac toe, for example, would be a single column of boxes. 2D tic tac toe, is the classic childrens game. 3D tic tac toe looks like this: ![enter image description here](https://i.stack.imgur.com/H34cW.gif) (Thanks to PrintActivities.com for the image, which I've shrunk.) Now, here is the pattern I've noticed: 1-dimensional: * up/down 2-dimensional * up/down * left/right * diagonal 3-dimensional * up/down * left/right * diagonal * vertical up down * vertical diagonal The number of possible winning combinations seem to be $2n-1$! Now... how would I express this for the *fourth* spatial dimension? What ways can this be projected so some one with a worse short-term memory than Leonhard Euler can actually play it ? This sounds fun (if challanging) to analyze myself, but the question is complicated enough I am interested in the insights of others! Also, this question is to help assemble a computer game (I'm a programmer) but I intend to link back at least to this page from the game itself, credit where credit's due.
2013/06/11
[ "https://math.stackexchange.com/questions/417118", "https://math.stackexchange.com", "https://math.stackexchange.com/users/64746/" ]
It sounds like you're asking about the different *types* of lines that have to be looked at, for instance all the possible lines through the center of the board. If this is so, then you left out two distinct classes in the 3d case. For convenience, I'm going to use coordinates that go from $0$ to $2$ in each direction, so the center of the board is at $(1,1,1)$. Now, the five different classes of line you mentioned in the 3d case are: * up-down (which would go through $(1, 0, 1)$, $(1, 1, 1)$ and $(1, 2, 1)$) * left-right (which would go through $(0, 1, 1)$, $(1, 1, 1)$ and $(2,1,1)$) * 'flat diagonal' through $(0, 0, 1)$, $(1, 1, 1)$ and $(2, 2, 1)$ * vertical up-down through $(1, 1, 0)$, $(1, 1, 1)$ and $(1, 1, 2)$ * and now, you list 'vertical diagonal', but that's not quite informative enough. In fact, there are two different types of vertical diagonal: + one that goes left-right and vertical — or in other words, through $(0, 1, 0)$, $(1, 1, 1)$ and $(2, 1, 2)$... + ...and one that goes north-south and vertical — or in other words one that goes through $(1, 0, 0)$, $(1, 1, 1)$ and $(1, 2, 2)$ What's more, there's also another 'long diagonal' that you missed: it goes through $(0, 0, 0)$, $(1, 1, 1)$ and $(2,2,2)$. This gives a total of 7 different 'line classes' in the 3d case. More generally, in $n$ dimensions there are $2^n-1$ different 'classes' of line by your counting. These correspond perfectly to all the vectors in $\{0,1\}^n$ that aren't the zero vector; each vector of the form $(v\_0, v\_1, \ldots, v\_n)$ corresponds to a line that goes through $(1-v\_0, 1-v\_1, \ldots, 1-v\_n)$, $(1, 1, \ldots, 1)$ and $(1+v\_0, 1+v\_1, \ldots, 1+v\_n)$. This scheme doesn't really work out well for enumerating all of the lines to be checked, though, because it misses things like the distinction between 'diagonals up' and 'diagonals down' - the two different diagonals of the original square, for instance, or the four distinct long diagonals of the cube, etc. A better count would be the total number of lines; this is eight for the 3x3 game (three horizontal, three vertical, and four diagonals), whereas for the 3x3x3 game it's forty-nine distinct lines (nine horizontal, nine vertical, nine up/down; eighteen 'short diagonal' lines; and four 'long diagonal' lines).
I play tic-tac-toe frequently. 4D is the most frequently played game for my group, but 6D's a close second. Here is 2D: ``` _|_|_ _|_|_ | | ``` Here is 3D: ``` _|_|_|_ _|_|_|_ _|_|_|_ | | | _|_|_|_ _|_|_|_ _|_|_|_ | | | _|_|_|_ _|_|_|_ _|_|_|_ | | | _|_|_|_ _|_|_|_ _|_|_|_ | | | ``` Here is 4D. Be aware even the provided 3D board is a first player win (but a very difficult one). The provided 4D board thus is obviously an even stronger first player win. In practice it works as a fun game. Because of the addition of the middle square, 5X5X5X5 boards actually feel *less* strategic (sense so much value is caught up in that middle space). ``` _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ | | | | | | | | | | | | _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ | | | | | | | | | | | | _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ | | | | | | | | | | | | _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ _|_|_|_ | | | | | | | | | | | | ``` If you go to 5D add two spaces in each direction, that should tide you over through 6D. And your 2n-1 is wrong. In 2 dimensions you have 3 kinds of lines that can be formed, yes. But in 3 dimensions you have 7 kinds of lines, not 5. If left/right, top/bottom, and front/back are different kinds, then each combination of these kinds should be considered to form a unique kind of diagonal. In general the number of kinds of line is (possible combinations of 1 element of N)+(possible combinations of 2 elements of N)+(possible combinations of 3 elements of N)+...(possible combinations of N elements of N). So that's N!/(1!(N-1)!)+N!/(2!(N-2)!)+N!/(3!(N-3)!)...+N!/(N!(N-N)!) or $2^N-1$ For 3 dimensions, though, this clearly yields 3+3+1=7 kinds of line.
17,424,254
I have ejabberd setup to be the xmpp server between mobile apps, ie. custom iPhone and Android app. But I've seemingly run into a limitation of the way ejabberd handles online status's. Scenario: * User A is messaging User B via their mobiles. * User B loses all connectivity, so client can't disconnect from server. * ejabberd still lists User B as online. * Since ejabberd assumes User B is still online, any message from User A gets passed on to the dead connection. * So user B won't get the message, nor does it get saved as an offline message, as ejabberd assumes the user is online. * Message lost. * Until ejabberd realises that the connection is stale, it treats it as an online user. And throw in data connection changes (wifi to 3G to 4G to...) and you'll find this happening quite a lot. mod\_ping: I tried to implement mod\_ping on a 10 second interval. <https://www.process-one.net/docs/ejabberd/guide_en.html#modping> But as the documentation states, the ping will wait 32 seconds for a response before disconnecting the user. This means there will be a 42 second window where the user can lose their messages. Ideal Solution: Even if the ping wait time could be reduce, it's still not a perfect solution. Is there a way that ejabberd can wait for a 200 response from the client before discarding the message? If no response then save it offline. Is it possible to write a hook to solve this problem? Or is there a simple setting I've missed somewhere? FYI: I am not using BOSH.
2013/07/02
[ "https://Stackoverflow.com/questions/17424254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1177855/" ]
ejabberd supports stream management as default in latest version. It is implemented in most mobile libraries like Smack for Android and XMPPFramework for iOS. This is the state of the art in XMPP specification at the moment.
Implementing XEP-198 on ejabberd is quite involved. Erlang Solutions (I work for them) has an XEP-184 module for ejabberd, with enhanced functionality, that solves this problem. It does the buffering and validation on the server side. As long as client sends messages carrying receipt request and when it is delivered the receipt goes back to sender. The module validates receipts to see if message has been received. If it hasn't within timeout, it gets saved as an offline message.
178,338
I know these pads are at least 4 summers old, but not sure how old exactly. As I was shutting the swamp cooler down for the winter, I saw that they seemed really dirty. The white material flakes of really easy. I don't know if I need to clean them or actually replace them? [![enter image description here](https://i.stack.imgur.com/hnDUz.jpg)](https://i.stack.imgur.com/hnDUz.jpg)
2019/11/14
[ "https://diy.stackexchange.com/questions/178338", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/44218/" ]
No one would ever do that. They would get a programmable thermostat. It is trivial to set up programs that do exactly what you want to do. Further, many thermostats have mechanical gating so the up and down (temperature) buttons are readily accessible and changeable right now, but will reset at the next program time. Access to program is gated by a special door. You can then put a cage over top of it so they can access the buttons, but not the door. They typically allow 4 program changes per day. This is a $50 solution, and you can't homebrew a thing like that for so little.
I've seen something like you're asking used in hotels before. They would have a regular thermostat that allowed the guest to adjust the temperature to their liking, but there was also a keycard reader tied in. In order for the A/C to operate, the guest would have to insert their room key into this device and leave it in. After removing the key (which tends to be a requirement when you leave a hotel room, as you can't get back in without it), the A/C would shut off. An example I found by Googling would be [here](https://illumra.com/application/application-notes/sample-applications/hotel-room-hvac-controls/) [This](https://www.evolvecontrols.com/climate-control/) is a similar system, but it uses occupancy sensors instead of the keycard.
3,536,604
sleep() is a static method of class Thread. How does it work when called from multiple threads. and how does it figure out the current thread of execution. ? or may be a more generic Question would be How are static methods called from different threads ? Won't there be any concurrency problems ?
2010/08/21
[ "https://Stackoverflow.com/questions/3536604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408215/" ]
> > how does it figure out the current > thread of execution? > > > It doesn't have to. It just calls the operating system, which always sleeps the thread that called it.
`Thread.sleep(long)` is implemented natively in the `java.lang.Thread` class. Here's a part of its API doc: ``` Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors. ``` The sleep method sleeps the thread that called it.(Based on EJP's comments) determines the currently executing thread (which called it and cause it to sleep). Java methods can determine which thread is executing it by calling `Thread.currentThread()` Methods (static or non static) can be called from any number of threads simultaneously. Threre will not be any concurrency problems as long as your methods are [thread safe](http://searchcio-midmarket.techtarget.com/sDefinition/0,,sid183_gci331590,00.html). You will have problems only when multiple Threads are modifying internal state of class or instance without proper synchronization.
10,294,122
Can somebody explain how works MySQL function LAST\_INSERT\_ID(). I'm trying to get id of last inserted row in database, but every time get 1. I use mybatis. Example query is : ``` <insert id="insertInto" parameterType="Something" timeout="0"> INSERT INTO something (something) VALUES (#{something}) <selectKey resultType="int"> SELECT LAST_INSERT_ID() </selectKey> </insert> ``` Code: ``` System.out.println("Id : " + id) ``` Output: ``` Id : 1 ```
2012/04/24
[ "https://Stackoverflow.com/questions/10294122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1345122/" ]
`LAST_INSERT_ID` returns the last value **implicitly** inserted into an `AUTO_INCREMENT` column in the current session. ``` CREATE TABLE mytable (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, value INT NOT NULL); ``` To make the column autoincrement, you should omit it from the `INSERT` list: ``` INSERT INTO mytable (value) VALUES (1) ``` or provide it with a `NULL` value: ``` INSERT INTO mytable (id, value) VALUES (NULL, 1) ``` After that, ``` SELECT LAST_INSERT_ID() ``` will return you the value `AUTO_INCREMENT` has inserted into the `id` column. This will not work if: 1. You provide the explicit value for the `AUTO_INCREMENT` column 2. You call `LAST_INSERT_ID` in another session 3. You insert more than one row in the same statement (`LAST_INSERT_ID()` will return the value of the first row inserted, not the last one).
I have two solutions, after implements much complicated i find out about second one... I will tell you second which is better one ... It's pretty simple... just in query insert this `keyProperty="id"` Like this : `<insert id="insertInto" parameterType="Something" keyProperty="id" timeout="0"> INSERT INTO something (something) VALUES (#{something}) </insert>` Query returns id of inserted row Thanks!
26,071,627
Im trying to do a java script that can convert hex to binary. What the script does, is that it prompts the user for a hex input and comes up with the binary equivalent output. Im having issues as i dont know how to set the parameters for the scanner input, as a hex can both be an Int and Char. I know what i've done here is wrong.. can you by any chance tell me how to do this correct? i just stripped out the part in question of my script. :-) ``` char hex; Scanner in = new Scanner(System.in); System.out.print("Enter a hex digit: "); hex = in.next().charAt(0); ```
2014/09/27
[ "https://Stackoverflow.com/questions/26071627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3582547/" ]
``` char hex; Scanner in = new Scanner(System.in); System.out.print("Enter a hex digit: "); hex = in.next().charAt(0); System.out.println("binary is "+new BigInteger(hex+"", 16).toString(2)); ```
what you need. Use string then convert it. ``` BigInteger.toString(radix) static String hexToBin(String s) { return new BigInteger(s, 16).toString(2); } ```
10,978
I'm wondering if there is any benefit behind double-clicking when using a mechanical torque wrench. Could it be that some folks do it to compensate for slack in the ratcheting mechanism? In other words, would I lose anything if I torqued down with just a single click? This [YouTube video](http://youtu.be/9UXftuZcEO4?t=12m30s) demonstrates what I mean.
2014/06/09
[ "https://mechanics.stackexchange.com/questions/10978", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/675/" ]
I spent 25 years as a Helicopter technician, and from year one i was Ordered NEVER EVER to double click a torque wrench. This double clicking that i see mechanics do drives me nuts. You are "overtorquing" if you do it twice.
It depends on what you're torquing and the requirements that need to be met for the item your are torquing. In the aviation industry everything is very fine tolerances and small torque ranges. A double click is over-torquing. In the general automotive industry where things are not as precise as aviation a double click isn't going to hurt anything.
57,458,998
I want to hide a certain paragraph from the SINGLE POST in WordPress via PHP content filter. I developed this filtering script, which works like a sunshine: ``` function hideDaStuff( $content ) { $paragraphs = explode( '</p>', $content ); foreach ($paragraphs as $index => $paragraph) { if(6 == $index){ $paragraphs[$index] = '<p>Hidden for you ma friend.</p>'; }else{ $paragraphs[$index] .= '</p>'; } } return implode( '', $paragraphs ); } add_filter( 'the_content', 'hideDaStuffForDaStranger' ); function hideDaStuffForDaStranger( $content ) { if ( is_single() && ! is_user_logged_in() ) { $content = hideDaStuff( $content ); } return $content; } ``` The problem is that WP cache caches the page whatever happens. So if a logged in user visits the page, then the content will show for everybody, and viceversa. How can I make this specific part cache-independent, while keeping an efficient cache? Using latest WP version and WP cache. Thank you.
2019/08/12
[ "https://Stackoverflow.com/questions/57458998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11751224/" ]
This theory is untested but I suspect you could throw a [`.select_for_update()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-for-update) on your view's queryset attribute. `.get_object()` calls `.get_queryset()` and since your code executes in an atomic block the row should be locked until the transaction is completed. ``` class Bet(UpdateView): queryset = Bet.objects.all().select_for_update() def put(self, request, *args, **kwargs): with transaction.atomic(): instance = self.get_object() ... ```
As your connection is slow and you are updating data via `REST API` being consumed by the client(ex. Android or IOS App maybe), there is no solution to carry out such thing. What you can do is, store the data in the client's local storage and `sync` it with your API once the connection speed is fast enough. You can check the `ServiceWorker` in web browser to understand the whole concept. basically, you will need something that works as a service worker for your API client/consumer app. Also, try to perform an `atomic` transaction with your database.
31,215,768
To test if my code is throwing expected exception I use the following syntax: ``` an [IllegalArgumentException] should be thrownBy(Algorithms.create(degree)) ``` is there any way to test if thrown exception contains expected message like: ``` an [IllegalArgumentException(expectedMessage)] should be thrownBy(Algorithms.create(degree)) -- what doesn't compile ``` ?
2015/07/04
[ "https://Stackoverflow.com/questions/31215768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1298028/" ]
[Documentation](http://www.scalatest.org/user_guide/using_matchers): ``` the [ArithmeticException] thrownBy 1 / 0 should have message "/ by zero" ``` and using that example: ``` the [IllegalArgumentException] thrownBy(Algorithms.create(degree)) should have message expectedMessage ```
Your syntax for checking the message is wrong. As an alternative to what bjfletcher suggested, you can also use the following, as per the documentation: 1. Capture the exception and assign it to a val `val thrown = the [IllegalArgumentException] thrownBy Algorithms.create(degree)` 2. Use the val to inspect its contents. E.g.: `thrown.getMessage should equal ("<whatever the message is")` I personally like the first alternative introduced by bjfletcher more, since it is more compact. But capturing the exception itself, gives you more possibilities to inspect its contents.
24,534,226
Although I am a beginner in java, I am trying to plot some data I have using JMathPlot. Every thing went well, but the script didn't terminate after I closed the window of the plot. Could any body tells me how to force the script to terminate when I close the window of the plot. I use a debian machine(32-bit), IDE = eclipse, java-version = 1,6 and here is the code I'm using for plotting: ``` Plot2DPanel plot = new Plot2DPanel(); plot.addLinePlot("test", x, y); JFrame frame = new JFrame("A test panel"); frame.setContentPane(plot); frame.setVisible(true); ``` Thank you in advance
2014/07/02
[ "https://Stackoverflow.com/questions/24534226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2804070/" ]
You termainate the process when closing the frame, not the panel. This this: `frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);` Also see [JFrame Exit on close Java](https://stackoverflow.com/questions/7799940/jframe-exit-on-close-java)
Sure! ``` frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0) } }); ``` What that does is, waits until the close button is pressed, then runs System.exit(0) which simply terminates your program. Note: I wrote this on iPhone, so watch for syntax errors :)
69,981
The Harmonium hails from Germany and it is not an Indian instrument. Also, it is an equal tempered instrument. But the harmonium is a very common accompanying instrument in Hindustani Classical (North-Indian tradition) and Bhajan. Whilst the harmonium is not used for South Indian Carnatic Music, violin is commonly used. The violin was also adopted from western world. Why did Hindustani music pick harmonium and Carnatic Music pick violin? Why did we adopt Western instruments even though we have a lot of Indian instruments?
2018/04/16
[ "https://music.stackexchange.com/questions/69981", "https://music.stackexchange.com", "https://music.stackexchange.com/users/49365/" ]
I had always assumed that the harmonium entered Indian culture via Western missionaries. But, according to this source: [Harmonium Indian Culture](https://indianculture.gov.in/musical-instruments/sushir-vadya/harmonium#:%7E:text=Harmonium%20is%20a%20stringed%20instrument,for%20both%20music%20and%20dance.) the table-top version with hand bellows was created by one Dwarkanath Ghose of Calcutta in 1875. Though I don't suppose he thought of the piano-style keyboard and method of sound production ALL by himself :-) Fun fact: in 1995 I got a call to go down to Garsington Manor near Oxford where the movie 'Carrington' was being shot. They required someone to play a tune on harmonium for an outdoor party scene. The instrument that appeared on screen was a full console instrument, but what they gave me to record the track was a half-size 'ship's harmonium'. I wonder if this is the sort of instrument Dwarkanath Ghose saw? The production company had wasted some time looking for professional harmonium players in the Musicians' Union directory, and finding only Indian classical musicians. Then they realised that a keyboard was a keyboard, and what they really needed was a hooligan who could busk something based on a WW1 era song. That fitted me just fine. Nice little gig.
The harmonium is not specifically a German instrument. As "pump organ" you can also find it in England and the US. It was popular has a home replacement of a church organ, which is why you would often find it in religious households for singing hymns. Thus it is not unlikely that missionaries took it with them, including to India, where they re-engineered it to have a hand bellows. Note 1: searching around I find no definite history to this effect. Note 2: the hand bellows is actually part of the medieval / renaissance "portatif" pipe organ. However, given the multi-century gap between that instrument's use and the rise of the harmonium in India I doubt there is a connection. Note 3: why so popular? I guess a combination of the gentle tone that does not interfere with the soloist, the fact that it can be played sitting on the floor, and that it's not fatiguing.
43,066,350
I've come up with some code that prints the address and postalcode of my location. This is done in the didupdatelocation function. The only problem that I occur, is that every second this address get's updated by the "didupdatelocation" function. Because this is very battery ineffecient, I was looking for ways to use an interval but I couldn't find ways (also not on Google en stackoverflow) on how to do this. Can anybody give me tips how I can do this in Swift?
2017/03/28
[ "https://Stackoverflow.com/questions/43066350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4671017/" ]
The answers of Rajeshkumar and Basir doesn't change much for the battery power, their delegate method is still called the same number of times per minute. If you want to have a more efficient behavior, try to change the values of distanceFilter, desiredAccuracy, and activityType (You can find all you need [here](https://developer.apple.com/reference/corelocation/cllocationmanager)) ``` manager.distanceFilter = 50 // distance changes you want to be informed about (in meters) manager.desiredAccuracy = 10 // biggest approximation you tolerate (in meters) manager.activityType = .automotiveNavigation // .automotiveNavigation will stop the updates when the device is not moving ``` Also if you only need the location of the user when it changes significantly, you can monitor significantLocationChanges, can also work when your app is killed.
Swift 3 version of this [answer](https://stackoverflow.com/a/22292872/7250862) ``` func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var newLocation = locations.last! var locationAge = -newLocation.timestamp.timeIntervalSinceNow if locationAge > 5.0 { return } if newLocation.horizontalAccuracy < 0 { return } // Needed to filter cached and too old locations var loc1 = CLLocation(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude) var loc2 = CLLocation(latitude: newLocation.coordinate.latitude, longitude: newLocation.coordinate.longitude) var distance: Double = loc1.distanceFromLocation(loc2) self.currentLocation = newLocation if distance > 20 { //significant location update } //location updated } ```
272,635
I'm doing some shennanigans with jQuery to put little plus/minus icons next to my expanders. Its similar to the windows file trees, or firebugs code expanders. It works, but its not specific enough. Hopefully this makes sense... ``` $('div.toggle').hide();//hide all divs that are part of the expand/collapse $('ul.product-info li a').toggle(function(event){ event.preventDefault(); $(this).next('div').slideToggle(200);//find the next div and sliiiide it $('img.expander').attr('src','img/content/info-close.gif');//this is the part thats not specific enough!!! },function(event) { // opposite here event.preventDefault(); $(this).next('div').slideToggle(200); $('img.expander').attr('src','img/content/info-open.gif'); }); <ul class="product-info"> <li> <a class="img-link" href="#"><img class="expander" src="img/content/info-open.gif" alt="Click to exand this section" /> <span>How it compares to the other options</span> </a> <div class="toggle"><p>Content viewable when expanded!</p></div> </li> </ul> ``` There are loads of `$('img.expander')` tags on the page, but I need to be specific. I've tried the next() functionality ( like I've used to find the next div), but it says that its undefined. How can I locate my specific img.expander tag? Thanks. EDIT, updated code as per Douglas' solution: ``` $('div.toggle').hide(); $('ul.product-info li a').toggle(function(event){ //$('#faq-copy .answer').hide(); event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-close.gif'); //alert('on'); },function(event) { // same here event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-open.gif'); }); ```
2008/11/07
[ "https://Stackoverflow.com/questions/272635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
``` $(this).contents('img.expander') ``` This is what you want. It will select all of the nodes that are children of your list. In your case, all of your images are nested inside of the list element, so this will filter out only what you want.
How about making your click event toggle a CSS class on a parent item (in your case, perhaps the ul.product-info). Then you can use CSS background properties to change the background image for a <span> instead of using a literal <img> and trying to fiddle with the src. You would also be able to accomplish a showing and hiding on your div.toggle's. ``` ul.product-info.open span.toggler { background-image: url( "open-toggler.png" ); } ul.product-info.closed span.toggler { background-image: url( "closed-toggler.png" ); } ul.product-info.open div.toggle { display: block; } ul.product-info.closed div.toggle { display: hidden; } ``` Using jQuery navigation/spidering functions can be slow when the DOM has many items and deep nesting. With CSS, your browser will render and change things more quickly.
3,259,530
I'm trying to prove that two definitions of the ordinal sum are equivalent. In the present question I want to prove that given $$\tag{1} \alpha+\beta:=\operatorname{ord}(\{0\}\times \alpha\cup \{1\}\times \beta) $$ it follows that $$ \alpha+ \operatorname{S}(\beta)=\operatorname{S}(\alpha+\beta) \text{, where }\operatorname{S}(A):=A\cup\{A\}. $$ Here is my start: \begin{align} \alpha+ \operatorname{S}(\beta)&=\alpha+ (\beta\cup \{\beta\})\\ &=\operatorname{ord}\big(\left(\{0\}\times \alpha\right)\cup \left(\{1\}\times (\beta\cup \{\beta\})\right)\big)\\ &=\operatorname{ord}\big(\left(\{0\}\times \alpha\right)\cup \left(\{1\}\times \beta\right)\cup \left(\{1\}\times \{\beta\}\right)\big)\\ &=\cdots\tag{\*}\\ &=\operatorname{ord}\big(\left(\{0\}\times \alpha\right)\cup \left(\{1\}\times \beta\right)\big)\cup \left\{\operatorname{ord}\big(\left(\{0\}\times \alpha\right)\cup \left(\{1\}\times \beta\right)\big)\right\}\\ &=(\alpha+\beta)\cup\{\alpha+\beta\}=\operatorname{S}(\alpha+\beta) \end{align} I proved the result $$ \operatorname{ord}(A\cup B)=\operatorname{ord} A+\operatorname{ord} B, $$ but $A,B$ have to be woset and disjoint, additionally $A\cup B$ has to be woset. > > How do I fill the gap? Are there already error? > Perhaps there are easier ways (transfinite induction?), but I would like to know if there is some technical trick to fill (\*). > > > **EDIT** I changed my mind... any hint to any type of proof showing the equivalence of (1) with the following definition (2) is welcomed (incl. ref duplicate / ref. textbook): 1. $\alpha+0=\alpha$ 2. $\alpha+ \operatorname{S}(\beta)=\operatorname{S}(\alpha+\beta)$ 3. if $\beta$ is a limit ordinal then $\alpha+\beta$ is the limit of the $\alpha+\delta$ for all $\delta<\beta$.
2019/06/12
[ "https://math.stackexchange.com/questions/3259530", "https://math.stackexchange.com", "https://math.stackexchange.com/users/680792/" ]
We want to prove the following > > **Theorem**: For each ordinal $\alpha$, the following equalities characterize the operation $\xi\longmapsto\alpha+\xi$: > > > $$\begin{cases} > \alpha+0=\alpha\\ > \alpha+S(\beta)=S(\alpha+\beta)\\ > \alpha+\gamma=\text{sup}\{\alpha+\delta\;|\;\delta<\gamma\}\quad\text{if }\gamma\text{ is a limit ordinal} > \end{cases}$$ > > > But first, let's prove the following: > > **Lemma**: For any ordinals $\alpha,\beta$ and $\gamma$: > > > (a) $\alpha+0=0+\alpha=\alpha$ > > > (b) $\alpha+1=S(\alpha)$ > > > (c) $\alpha+(\beta+\gamma)=(\alpha+\beta)+\gamma$ (associativity) > > > (d) $\alpha+S(\beta)=S(\alpha+\beta)$ > > > **Demonstration**: (a) Let $\langle A,<\_R\rangle$ be a well ordered set of ordinal $\alpha$. The only well ordered set of ordinal $0$ is the empty set $\varnothing$, so the ordered sum has as base set $A\cup\varnothing=A$ and its well-order is simply the well-order $<\_R$ of $A$, so its ordinal is $\alpha$ and $\alpha+0=\alpha$. Similarly, we can obtain $0+\alpha=\alpha$. (b) Let $\langle A,<\_R\rangle$ be a well ordered set of ordinal $\alpha$ and let $\langle\{b\},<\_S\rangle$ be a well ordered set of ordinal $1$ such that $b\not\in A$. The ordinal $\alpha+1$ of the ordered sum $\langle A\cup\{b\},<\_{R\oplus S}\rangle$ is $S(\alpha)$, because $$\langle A\cup\{b\},<\_{R\oplus S}\rangle\cong\langle S(\alpha),\in\_{S(\alpha)}\rangle$$ Via the isomorphism $f:A\cup\{b\}\longrightarrow S(\alpha)$ defined by: for each $a\in A\cup\{b\}$ $$f(a)=\begin{cases} g(a)\quad\text{if }a\in A\\ \alpha\qquad\,\text{if }a=b \end{cases}$$ Where $g$ is the isomorphism between the well ordered set $\langle A,<\_R\rangle$ and $\alpha$. (c) Let $\langle A,<\_R\rangle,\;\langle B,<\_S\rangle$ and $\langle C,<\_T\rangle$ be well ordered sets of ordinals $\alpha,\beta$ and $\gamma$ respectively, such that $A,B$ and $C$ are pairwise disjoint. The ordinal $\alpha+(\beta+\gamma)$ is the ordinal of the well ordered set $\langle A\cup(B\cup C),<\_{R\oplus(S\oplus T)}\rangle$, and the ordinal $(\alpha+\beta)+\gamma$ is the ordinal of the well ordered set $\langle(A\cup B)\cup C,<\_{(R\oplus S)\oplus T}\rangle$. This well ordered set are not only isomorphic but identical, because $A\cup(B\cup C)=(A\cup B)\cup C$ and $<\_{R\oplus(S\oplus T)}=<\_{(R\oplus S)\oplus T}$, so their respective ordinals are equal, i.e. $\alpha+(\beta+\gamma)=(\alpha+\beta)+\gamma$ (d) $\alpha+S(\beta)=\alpha+(\beta+1)=(\alpha+\beta)+1=S(\alpha+\beta)$ For the last part of the theorem, we just have to prove the following: > > **Lemma**: For any ordinals $\alpha$ and $\gamma$, if $\gamma$ is a limit ordinal, then > > > $$\alpha+\gamma=\text{sup}\{\alpha+\delta\;|\;\delta<\gamma\}$$ > > > **Demonstration**: We must prove the two corresponding inequalities. First, for each $\delta<\gamma$, we have that $\alpha+\delta<\alpha+\gamma$ (cf. Hrbacek & Jech *Introduction to Set Theory*, page 120, lemma 5.4 (a)), so $$\text{sup}\{\alpha+\delta\;|\;\delta<\gamma\}\leq\alpha+\gamma$$ On the other hand, let $\eta<\alpha+\gamma$. We shall prove that there exists some $\delta<\gamma$ such that $\eta\leq\alpha+\delta$. We have that $\eta<\alpha$ or $\alpha\leq\eta$. In the first case, we simply take $\delta=0$. In the second case, we know there exists some $\beta$ such that $\eta=\alpha+\beta$ (cf. Hrbacek & Jech *Introduction to Set Theory*, page 121, lemma 5.5), and since $\eta<\alpha+\gamma$, it results that $\beta<\gamma$. So taking $\delta=\beta$, we have that $\eta\leq\alpha+\delta$, and $$\alpha+\gamma\leq\text{sup}\{\alpha+\delta\;|\;\delta<\gamma\}$$ For the other part of the equivalence, that is, supposing that we **define** the sum of ordinals recursively, and we want to prove that the sum of ordinals is the ordinal of the ordered sum of two well ordered disjoint sets, just take a look again at the book of Hrbacek & Jech, page 120, theorem 5.3, where this fact is proved in full detail.
For short let $X=(\{0\}\times \alpha)\cup (\{1\}\times \beta).$ From the 3rd line of your "start" we have $$\alpha + S(\beta)=$$ $$=ord \,(X\cup (\{1\}\times \{\beta\})\,)$$ $$==ord \,(\, (\{0\}\times X)\cup (\{1\}\times \{\beta\})\,)=$$ $$=ord\,(\,(\{0\}\times X)\cup (\{1\}\times \{\alpha+\beta\})\,)=$$ $$=ord\,(\,(\{0\}\times (\alpha+\beta)\,)\cup (\{1\}\times(\{\alpha+\beta\}) \,)=$$ $$=S(\alpha+\beta).$$
61,897,076
I've encountered strange behavior when trying to construct a tuple of references from a mix of tuples and integral values. Given the following: ``` struct A { int v = 1; }; struct B { int v = 2; }; struct C { int v = 3; }; A a; std::tuple<B,C> tpl; ``` I'm trying to create a third tuple which holds references to all instances, so that each instance's `v` will be assignable and readable through it. Seems simple enough using templates ``` template <class Tuple, size_t... Is> constexpr auto as_ref_impl(Tuple t, std::index_sequence<Is...>) { return std::tuple_cat(std::tie(std::get<Is>(t))...); // or // return std::make_tuple(std::ref(std::get<Is>(t))...); } template <class...Args> constexpr auto as_ref(std::tuple<Args...>& t) { return as_ref_impl(t, std::index_sequence_for<Args...>{}); } ``` and then ``` auto ref_tpl = std::tuple_cat(std::tie(a), as_ref(tpl)); ``` which builds fine (in both versions). Unfortunately only the parts of the reference tuple (`ref_tpl`), which originate from integral values, can be assigned or read from successfully. I'm using `C++14` and `gcc 9.3.0`. Any ideas, or insight why this does not work, are very welcome! **Minimal working example:** ``` #include <iostream> #include <tuple> #include <type_traits> #include <utility> #include <functional> struct A { int v = 1; }; struct B { int v = 2; }; struct C { int v = 3; }; A a; std::tuple<B,C> tpl; template <class Tuple, size_t... Is> constexpr auto as_ref_impl(Tuple t, std::index_sequence<Is...>) { //return std::tuple_cat(std::tie(std::get<Is>(t))...); return std::make_tuple(std::ref(std::get<Is>(t))...); } template <class...Args> constexpr auto as_ref(std::tuple<Args...>& t) { return as_ref_impl(t, std::index_sequence_for<Args...>{}); } int main() { using std::cout; auto ref_tpl = std::tuple_cat(std::tie(a), as_ref(tpl)); // prints 1 2 3, as expected. cout << a.v << std::get<0>(tpl).v << std::get<1>(tpl).v << std::endl; std::get<0>(ref_tpl).v = 8; // works std::get<1>(ref_tpl).v = 9; // does not work std::get<2>(ref_tpl).v = 10; // does not work // should output 8 9 10 instead outputs 8 2 3 cout << a.v << std::get<0>(tpl).v << std::get<1>(tpl).v << std::endl; // should output 8 9 10, instead outputs garbage. cout << std::get<0>(ref_tpl).v << std::get<1>(ref_tpl).v << std::get<2>(ref_tpl).v << std::endl; return 0; } ```
2020/05/19
[ "https://Stackoverflow.com/questions/61897076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2065991/" ]
You can try this: ``` df['rate_number'] = df['rate_number'].replace('\(|[a-zA-Z]+', '', regex=True) ``` Better answer: ``` df['rate_number_2'] = df['rate_number'].str.extract('([0-9][,.]*[0-9]*)') ``` **Output:** ``` rate_number rate_number_2 0 92 92 1 33 33 2 9.25 9.25 3 4,396 4,396 4 2,620 2,620 ```
There is a small error with the asterisk's position: ``` df['rate_number_2'] = df['rate_number'].str.extract('([0-9]*[,.][0-9]*)') ```
55,073
I recently updated my server's database system from MySQL to MariaDB. After update, everything works well. But, when I went to phpMyAdmin, the default charset and types are changed: ![MySQL chareset and type info](https://i.stack.imgur.com/KjVhg.png) At the end of this image, the default type was set to 'InnoDB' and charset was set to 'latin1\_swedish\_ci'. They were 'MyISAM' and 'utf8\_general\_ci' before. How can I revert my character set and type settings back, and how can I customize settings when I make new database? When I looked at /etc/my.cnf and /etc/my.cnf.rpmnew, I couldn't find any settings related to DB type/charset.
2013/12/16
[ "https://dba.stackexchange.com/questions/55073", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/31738/" ]
*"How can I revert my character set" :* ``` ALTER TABLE myTable CONVERT TO CHARACTER SET "utf8"; ``` *"How can I revert my type": (MySQL Engine):* ``` ALTER TABLE myTbale ENGINE=MyISAM; ``` *"how can I customize settings when I make new database?"* **In your my.cnf** ``` default-storage-engine=MyISAM ``` Best Regards. Max.
* You can change server's **charset** and **collation** by editing `my.cnf` file and restart MySQL server to have effect <http://dev.mysql.com/doc/refman/5.6/en/charset-server.html> * Now all your tables are of Engine type as **InnoDB**, if you are using MariaDB 5.6+ then it can support Fulltext search with InnoDB which is primary reason before v5.6 to use MyISAM table. Now, you can get rid of MyISAM tables You can have a look at this blog post <http://www.mysqlperformanceblog.com/2013/07/31/innodb-full-text-search-in-mysql-5-6-part-3/> (You can refer part-1 and part-2) as well for better understaning why we should use InnoDB rather than MyISAM in v5.6 * You can specify **charset** and **collation** as you would like while creating a database, a session level setting always overrides global level settings. <http://dev.mysql.com/doc/refman/5.6/en/create-database.html>
1,352,522
I need to write a DLL (using Delphi) which is dynamically loaded into delphi applications and makes RTTI queries (typical operation is to obtain string values for control properties). The classic problem is that passing strings (and objects) between application and DLL is problematic due to different memory managers used in both (this might lead to memory issues, e.g. DLL's memory manager would try to free the memory allocated by Application's memory manager). Is there a way to set DLL's memory manager to application's memory manager in a way that would not depend on delphi version? Any thoughts? **October 2010 edit:** Since interest to this topic is almost lost - I'll describe the (quite poor) solution which I ended up with so that others would understand why I didn't accept any of the proposed answers. So a *hacky* way to perform something like this would be to find `RVA` of `MemoryManager` structure (refer to implementation part of System.pas) and hardcode in the DLL. This way, DLL would be able to set its private memory manager to be the same as that of the application it is being loaded into. It works with some limitations and issues; anyway - it is very Delphi compiler & linker options dependent. Though it is not an answer I was searching for - I do not expect anything better than this.
2009/08/29
[ "https://Stackoverflow.com/questions/1352522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106688/" ]
Use the same memory manager for your application and your DLLs. For recent version of Delphi that includes the new FastMM memory manager, use SimpleShareMem as the 1st unit in both your application and the DLL projects. Or download the [full FastMM4 from SourceForge](http://sourceforge.net/projects/fastmm/), set the Flags in FastMM4Options.Inc (ShareMM, ShareMMIfLibrary, AttemptToUseSharedMM) and put FastMM4 as the 1st unit in both the application and the DLLs projects.
Here's a nice article that has some recommendations: <http://www.codexterity.com/memmgr.htm> I also found this: <http://sourceforge.net/projects/fastmm/> I haven't tried either of the libraries they recommend. It might get you version independence, it might not. If you're wanting to distribute the DLL and support different Delphi versions, that might be problematic. One option would be to compile a version for several of the major releases. Note: It's unclear when FastSharemem was last updated; it may be obsolete.
1,002,327
Are there any site that show good examples of web application styles? Form designs and layout styles?
2009/06/16
[ "https://Stackoverflow.com/questions/1002327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104849/" ]
Besides the many tutorials and examples on <http://www.w3schools.com/> ? There is always <http://www.csszengarden.com/> that shows how you can manipulate the content of your web page just by altering the style sheet. You can find a large list of examples of form designs at: <http://www.smashingmagazine.com/2008/04/17/web-form-design-modern-solutions-and-creative-ideas/>
Smashing Magazine has some useful links ... a few have been mentioned in previous responses, so I will add the one that I have found useful ... [40 Helpful Resources On User Interface Design Patterns](http://www.smashingmagazine.com/2009/06/15/40-helpful-resources-on-user-interface-design-patterns/)
6,203,090
I have been using `TForm`'s `OnActivate` event to give me the opportunity to show a dialog box as soon as my app has started. I want the main form to already be loaded & visible. What's a good way to do this? I have found that `OnActivate` works fine unless the forms `WindowState` is `wsMaximized`. in the past I've accomplished what I want in various ways but I expect there is a better way. Here's what worked for me: ``` procedure TForm1.FormCreate(Sender: TObject); begin Application.OnIdle:=OnIdle; end; procedure TForm1.OnIdle(Sender: TObject; var Done: Boolean); begin Application.OnIdle:=nil; form2:=TForm2.Create(Application); form2.ShowModal; end; ``` Is there a better way?
2011/06/01
[ "https://Stackoverflow.com/questions/6203090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14031/" ]
In the form's OnCreate event handler post a user message and show the dialog in the handler of the message: ``` unit Unit1; interface const UM_DLG = WM_USER + $100; type TForm1 = class(TForm) ... procedure UMDlg(var Msg: TMessage); message UM_DLG; ... implementation procedure TForm1.FormCreate(Sender: TObject); begin PostMessage(Handle, UM_DLG, 0, 0); end; procedure TForm1.UMDlg(var Msg: TMessage); begin form2 := TForm2.Create(Application); form2.ShowModal; end; ``` Although I found timer approach even better: just drop a timer component on the form, set Interval to 100 (ms) and implement OnTimer event: ``` procedure Timer1Timer(Sender: TObject); begin Timer1.Enabled := False; // stop the timer - should be executed only once form2 := TForm2.Create(Application); form2.ShowModal; end; ``` --- The difference between the two approaches is: When user message is posted either from OnCreate or OnShow handler, the message is dispatched with normal priority which means that other window initialization messages might get posted and handled after it. For essence, WM\_PAINT messages would be handled after UM\_DLG message. If UM\_DLG message is taking long time to process without pumping the message queue (for example, opening db connection), then form would be shown blank without client area painted. WM\_TIMER message is a low-priority message and than means that form initialization messages would be handled first and only then WM\_TIMER message would be processed, even if WM\_TIMER message is posted before the form creation completes.
Well, I do not know if it is the best pratice, but I do like this: In the PROGRAM file (.dpr - I use Delphi 7) I add this lines: ``` begin Application.Initialize; Application.CreateForm(TForm1, Form1); Form1.Show; // Show Main Form Form1.Button1.Click; // Call event/function Application.Run; end. ``` Please, someone correct me if it is not the best pratice! Hope to be helpfull for you!
3,984
I am running a logistic model. The actual model dataset has more than 100 variables but I am choosing a test data set in which there are around 25 variables. Before that I also made a dataset which had 8-9 variables. I am being told that AIC and SC values can be used to compare the model. I observed that the model had higher SC values even when the variable had low p values ( ex. 0053) . To my intuition a model which has variables having good significance level should result in low SC and AIC values. But that isn't happening. Can someone please clarify this. In short I want to ask the following questions: 1. Does the number of variable have anything to do with SC AIC ? 2. Should I concentrate on p values or low SC AIC values ? 3. What are the typical ways of reducing SC AIC values ?
2010/10/26
[ "https://stats.stackexchange.com/questions/3984", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/1763/" ]
It is quite difficult to answer your question in a precise manner, but it seems to me you are comparing two criteria (information criteria and p-value) that don't give the same information. For all information criteria (AIC, or Schwarz criterion), the smaller they are the better the fit of your model is (from a statistical perspective) as they reflect a trade-off between the lack of fit and the number of parameters in the model; for example, the Akaike criterion reads $-2\log(\ell)+2k$, where $k$ is the number of parameters. However, unlike AIC, SC is consistent: the probability of choosing incorrectly a bigger model converges to 0 as the sample size increases. They are used for comparing models, but you can well observe a model with significant predictors that provide poor fit (large residual deviance). If you can achieve a different model with a lower AIC, this is suggestive of a poor model. And, if your sample size is large, $p$-values can still be low which doesn't give much information about model fit. At least, look if the AIC shows a significant decrease when comparing the model with an intercept only and the model with covariates. However, if your interest lies in finding the best subset of predictors, you definitively have to look at methods for variable selection. I would suggest to look at *penalized regression*, which allows to perform variable selection to avoid overfitting issues. This is discussed in Frank Harrell's Regression Modeling Strategies (p. 207 ff.), or Moons et al., [Penalized maximum likelihood estimation to directly adjust diagnostic and prognostic prediction models for overoptimism: a clinical example](http://www.jclinepi.com/article/S0895-4356%2804%2900171-4/abstract), J Clin Epid (2004) 57(12). See also the [Design](http://cran.r-project.org/web/packages/Design/index.html) (`lrm`) and [stepPlr](http://cran.r-project.org/web/packages/stepPlr/index.html) (`step.plr`) R packages, or the [penalized](http://cran.r-project.org/web/packages/penalized/index.html) package. You may browse related questions on *variable selection* on this SE.
Grouping SC and AIC together **IS WRONG**. They are very different things, even though people heavily misuse them. AIC is meaningful when you are predicting things, using SC in this scenario can lead (not all the times) to wrong results. Similarly, if you are interested in doing model selection with the principle of parsimony (Occam's Razor) SC is better. I don't want to go into the theoretical details, but in a nutshell: SC -- good for parsimonious models when you want something equivalent to simplest possible model to explain your data, AIC -- When you want to predict. AIC doesn't assume that your true model lies in the model space where as SC does. Secondly, using p-values and information criteria together can be also misleading as explained by **chl**.
9,330,882
I'm working on a java android project. this project requires to use specific commands. these commands are all developed in c++/c but I've been given two files (.jar and .so) that are supposed to "turn them into" java, so I can use them in my java android project. The thing is, what am I supposed to do with these 2 files?? I've read a lot of stuff (mostly about creating the .jar and .so, but I don't care about this step, for I already have the 2 files) I tried to import the .jar (import external lib), I tried to add the .so via the static loading : //static { // System.loadLibrary("MySoFile"); // } All I get is a stack overflow error or a problem with the DEX file... Has anybody ever tried to do this?? I don't seem to get the point here...all I want to do is being able to use the commands in the .jar file.... :// thanks in advance!!
2012/02/17
[ "https://Stackoverflow.com/questions/9330882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1216018/" ]
Take a look at [this answer](https://stackoverflow.com/questions/9283040/eclipse-android-project-how-to-reference-library-within-workspace/9283084#9283084) about adding `jar` files. '.so' files can usually just be drag and dropped to the project.
All you need to do is make sure the jar is in your classpath and you can then access the classes within this jar. A jar is just an archive of classes, you don't need to load the library into memory or something similar. You may want to read the answer to the question here [How to use classes from .jar files?](https://stackoverflow.com/questions/460364/how-to-use-classes-from-jar-files)
5,103,884
Hi I have a jsp page in which following lines ``` if(Exception err) { out.println (err.getMessage() + "<br/><br/>"); } ``` may get XSS attacks i want to it just display the above things without any XSS attacks Any thought ?
2011/02/24
[ "https://Stackoverflow.com/questions/5103884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632197/" ]
use [`c:out`](http://download.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/c/out.html) tag. **Also See** * [java-best-practices-to-prevent-cross-site-scripting](https://stackoverflow.com/questions/1159729/java-best-practices-to-prevent-cross-site-scripting)
Apache Commons provides StringEscapeUtils, see the [escapeHtml()](http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringEscapeUtils.html#escapeHtml%28java.io.Writer,%20java.lang.String%29) method
2,058,339
I have a text file with lots of lines and with this structure: ``` [('name_1a', 'name_1b', value_1), ('name_2a', 'name_2b', value_2), ..... ..... ('name_XXXa', 'name_XXXb', value_XXX)] ``` I would like to convert it to: ``` name_1a, name_1b, value_1 name_2a, name_2b, value_2 ...... name_XXXa, name_XXXb, value_XXX ``` I wonder what would be the best way, whether awk, python or bash. Thanks Jose
2010/01/13
[ "https://Stackoverflow.com/questions/2058339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209514/" ]
Oh boy, here is a job for `ast.literal_eval`: (`literal_eval` is safer than `eval`, since it restricts the input string to literals such as strings, numbers, tuples, lists, dicts, booleans and None: ``` import ast filename='in' with open(filename,'r') as f: contents=f.read() data=ast.literal_eval(contents) for elt in data: print(', '.join(map(str,elt))) ```
Asking what's the best language for doing a given task is a very different question to say, asking: 'what's the best way of doing a given task in a particular language'. The first, what you're asking, is in most cases entirely subjective. Since this is a fairly simple task, I would suggest going with what you know (unless you're doing this for learning purposes, which I doubt). If you know any of the languages you suggested, go ahead and solve this in a matter of minutes. If you know none of them, now enters the subjective part, I would suggest learning Python, since it's so much more fun than the other 2 ;)
6,036,127
I just started with Zend Framework 2.0 and wanted to load my own resources. My own library PWS resides in the library folder. To override the FrontController resource I have the following file PWS/Application/Resource/FrontController.php ``` <?php namespace PWS\Application\Resource; class FrontController extends \Zend\Application\Resource\FrontController { public function init() { return parent::init() } } ``` In my application.ini I have the following relevant lines: ``` autoLoaderNamespaces.PWS = APPLICATION_PATH "/../library/PWS" pluginPaths.PWS\Application\Resource\ = APPLICATION_PATH "/../library/PWS/Application/Resource" ``` The project uses modules but I don't think this should affect the problem. When I debugged a class ResourceLoader (which contains hardcoded paths to the resources) was used to load the FrontController instead of my own resource. It isn't urgent but annoying :)
2011/05/17
[ "https://Stackoverflow.com/questions/6036127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730277/" ]
Suppose you have a task to perform. Let's say you're a math teacher and you have twenty papers to grade. It takes you two minutes to grade a paper, so it's going to take you about forty minutes. Now let's suppose that you decide to hire some assistants to help you grade papers. It takes you an hour to locate four assistants. You each take four papers and you are all done in eight minutes. You've traded 40 minutes of work for 68 total minutes of work including the extra hour to find the assistants, so this isn't a savings. The overhead of finding the assistants is larger than the cost of doing the work yourself. Now suppose you have twenty thousand papers to grade, so it is going to take you about 40000 minutes. Now if you spend an hour finding assistants, that's a win. You each take 4000 papers and are done in a total of 8060 minutes instead of 40000 minutes, a savings of almost a factor of 5. The overhead of finding the assistants is basically irrelevant. Parallelization is *not free*. **The cost of splitting up work amongst different threads needs to be tiny compared to the amount of work done per thread.** Further reading: [Amdahl's law](https://en.wikipedia.org/wiki/Amdahl%27s_law) > > Gives the theoretical speedup in latency of the execution of a task at fixed workload, that can be expected of a system whose resources are improved. > > > [Gustafson's law](https://en.wikipedia.org/wiki/Gustafson%27s_law) > > Gives the theoretical speedup in latency of the execution of a task at fixed execution time, that can be expected of a system whose resources are improved. > > >
As previous writer has said there are some overhead associated with `Parallel.ForEach`, but that is not why you can't see your performance improvement. `Console.WriteLine` is a synchronous operation, so only one thread is working at a time. Try changing the body to something non-blocking and you will see the performance increase (as long as the amount of work in the body is big enough to outweight the overhead).
13,269,183
Hi can you guys help me with this, I have try several things. I need to search between two IEnumerables, here is the code. ``` IEnumerable<Project> Projects = new[] { new Project {id = "1", lan = "test1"}, new Project {id = "2", lan = "test1"}} IEnumerable<string> lan = new [] { "test1", "test2"}; IEnumerable<string> indexFiltered = ?; ``` I need to do a linq query that return the Project.id thats have any Project.lan in lan. Any idea?
2012/11/07
[ "https://Stackoverflow.com/questions/13269183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1083647/" ]
I'd use a `HashSet` rather than an array, as it allows check-if-contains as an O(1), rather than O(n), operation: ``` HashSet<string> lan = new HashSet<string> { "test1", "test2" }; IEnumerable<string> indexFiltered = projects .Where(p => lan.Contains(p.lan)) .Select(p => p.id); ```
Another efficient approach is using [`Enumerable.Join`](http://msdn.microsoft.com/en-us/library/bb344797.aspx) since it's implemented as a hash table: ``` IEnumerable<string> indexFiltered = from p in Projects join l in lan on p.lan equals l select p.id; ``` [Why is LINQ JOIN so much faster than linking with WHERE?](https://stackoverflow.com/questions/5551264/why-is-linq-join-so-much-faster-than-linking-with-where) The Join operator takes the rows from the first tables, then takes only the rows with a matching key from the second table, then only the rows with a matching key from the third table.
54,750,231
I have the below code. I wish to place a table in the body of an HTML email where I want negative values to be color-coded in red, positive values in green and unchanged values to display a dash. I can make it work for a single cell reference, however I can't figure out how to incorporate a For Each...Next command so that the code runs through an entire column and color codes all values accordingly. Any help is greatly appreciated. ``` Sub Test() Dim oApp As Object Dim oEmail As Object Set oApp = CreateObject("Outlook.Application") Set oEmail = oApp.CreateItem(0) rng = Range("A1") If Range("A1") < 0 Then rng = "<font color=""red"">" & "<b>" & rng & "</font>" & "</b>" ElseIf Range("A1") > 0 Then rng = "<font color=""green"">" & "<b>" & rng & "</font>" & "</b>" Else: rng = "<b>" & "-" & "</b>" End If Set oApp = CreateObject("Outlook.Application") Set oEmail = oApp.CreateItem(olMailItem) oEmail.Close olSave oEmail.Save oEmail.BCC = "" oEmail.Subject = "Test" oEmail.SentOnBehalfOfName = """Hello"" <xxx@xxx>" oEmail.HTMLBody = rng oEmail.Display Set oEmail = Nothing Set oApp = Nothing Set colAttach = Nothing Set oAttach = Nothing cleanup: Set oApp = Nothing End Sub ```
2019/02/18
[ "https://Stackoverflow.com/questions/54750231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4299209/" ]
You were pretty correct till *public static ExpectedCondition visibilityOf(WebElement element): An expectation for checking that an element, known to be present on the DOM of a page, is visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. This existing method above, checks that the element is visible and also present in the DOM but not only present in the DOM*. For simplicity I would rephrase this ExpectedCondition as *the expectation to check for the element known to be present within the DOM of a page, is visible*. Of-coarse the two expectations `presenceOfElementLocated()` and `visibilityOf()` have a lot of differences between them. --- Coming back to your main question, *to wait for a specific WebElement to be present* using *WebElement* as an argument is **not possible** . The reason is simple as the *WebElement* is yet to be identified in the DOM, which will be identified only after the expectation of `presenceOfElementLocated` or `findElement()` succeeds. This concept is abruptly supported by the list of [ExpectedCondition](https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html)s in the *JavaDocs* related to *presence of element(s)* which are as follows: * [`presenceOfAllElementsLocatedBy(By locator)`](https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#presenceOfAllElementsLocatedBy-org.openqa.selenium.By-) * [`presenceOfElementLocated(By locator)`](https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#presenceOfElementLocated-org.openqa.selenium.By-) * [`presenceOfNestedElementLocatedBy(By locator, By childLocator)`](https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#presenceOfNestedElementLocatedBy-org.openqa.selenium.By-org.openqa.selenium.By-) * [`presenceOfNestedElementLocatedBy(WebElement element, By childLocator)`](https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#presenceOfNestedElementLocatedBy-org.openqa.selenium.WebElement-org.openqa.selenium.By-) * [`presenceOfNestedElementsLocatedBy(By parent, By childLocator)`](https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#presenceOfNestedElementsLocatedBy-org.openqa.selenium.By-org.openqa.selenium.By-) --- To conclude, you can't pass a *WebElement* as an argument as an expectation as `presenceOfElementLocated()` as the *WebElement* is yet to be identified. But once the element is identified through `findElement()` or `presenceOfElementLocated()` this *WebElement* can be passed an an argument. To summarize: * [`presenceOfElementLocated(By locator)`](https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#presenceOfElementLocated-org.openqa.selenium.By-): This expectation is for checking that an element is **present** in the DOM of a page. This does not necessarily mean that the element is **visible**. * [`visibilityOf(WebElement element)`](https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#visibilityOf-org.openqa.selenium.WebElement-): This expectation is for checking that an element, known to be present on the DOM of a page, is visible. Visibility means that the element is not only **displayed** but also has a **height** and **width** that is **greater than 0**.
How to check presence with `WebElement` as a parameter. ``` public boolean isElementPresent(WebElement element) { if (element != null) { try { //this line checks the visibility but it's not returned. //It's to perform any operation on the WebElement element.isDisplayed(); return true; } catch (NoSuchElementException e) { return false; } } else return false; } ```
116,322
I got this on an interview question and I still don't know the answer. > > What output will have a nonlinear device if we will give two random frequencies \$f\_1\$ and \$f\_2\$? > > > I answered that it will have two carriers but I really unsure about my answer.
2014/06/23
[ "https://electronics.stackexchange.com/questions/116322", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/46115/" ]
The correct answer is that you don't know without more information about this non-linear device. Non-linear only rules out linear, but can otherwise mean anything else, including putting out a fixed signal regardless of the inputs. To show that you understand the concept, you should explain that a linear device can produce at most *only* the frequencies put into it. It can change the amplitude and phase angle of the input frequencies, but it can't create new ones. It could, for example, attenuate either or both frequencies well past the noise floor, so even for a linear device, the answer is none, one, or both of the input frequencies. What they were probably after with this question is for you to say that the non-linear device can produce additional frequencies beyond those you put in. If the non-linear device happens to include a product term, as Leon is apparently assuming, then you will get the sum and difference of the two frequencies included in the output.
In general, you will get: * the two original frequencies f1,f2 * The sum and difference of the two frequencies f1 + f2, f1 - f2 (aka intermodulation products) * The harmonics of each of the two frequencies (f1\*2, f1\*3, f1\*n, f2\*2, f2\*3, f2\*n, ...) * Harmonics of the intermodulation products * Intermodulation products between any of the above and any other component TL/DR : a mess. In practice while you can get all of these, the amplitudes of many of them may be negligibly low or actually zero, depending on the form of the nonlinearity. One special case is a perfect multiplier or balanced mixer with one carrier on each input. This produces the sum and difference on the output, and nothing else. Another special case is a device with a square law or quadratic transfer function (vacuum tube triodes and some FET amplifiers can approximate this) - you will get the original frequencies, the sum and difference, and almost purely second harmonics only. Makes for a good guitar amp or an overpriced "audiophile" hi-fi system... And so on.
476,165
I have this function $f(\mathrm{X})$ where $\mathrm{X=A+B+C}$ where $\mathrm{A}$ is a diagonal element with variable $a$ on its diagonal. $\mathrm{B}$ is another diagonal matrix with variable $b$ on its diagonal. $\mathrm{C}$ is a positive definite matrix with variable $c\_{ij}$. Now I want to optimize this function over these variables. I was wondering to keep $\mathrm{A}$ and $\mathrm{B}$ constant first optimize over $\mathrm{C}$ using Newton's method. Then I will keep $\mathrm{C}$ constant and optimize over $a$ and $b$ using gradient descent. I am not sure if this is applicable or will work. Suggestions guys?
2013/08/26
[ "https://math.stackexchange.com/questions/476165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/34790/" ]
I'm dropping that $\tfrac{1}{2}$ for simplicity; it can be buried in the $y$ vector. Assuming the function is $$\begin{aligned} f(X) &= y^T X y + z^T X^{-1} z - \log\det(X) \\ &= \langle yy^T, X \rangle + \langle zz^T, X^{-1} \rangle - \log\det(X) \end{aligned}$$ then the gradient is $$\nabla f(X) = yy^T - X^{-1} zz^T X^{-1} - X^{-1}$$ I'd consider just doing a gradient descent with a backtracking line search to start. Because our variable is a matrix instead of a vector, it takes a bit of care to get the computations right, but it's not too bad. There are plenty of good explanations of gradient descent with backtracking line search available with a simple Google search. In short: 1. Compute $V=-\nabla f(X)$. 2. Find $t>0$ such that $f(X+tV)=f(X)-\tfrac{1}{2}t \|V\|\_F^2$ 3. Update $X\leftarrow X + tV$ and repeat To find $t$, one typically just starts with $t=t\_\max$ (say, 1) and cuts in half until the condition is satisfied. Again, Google is your friend.
Here's some sample Matlab code that uses CVX to solve a problem similar to yours. However, I don't yet know how to handle the $r^T X^{-1} r$ term. ``` N = 30; y = randn(N,1); cvx_begin sdp variable X hermitian minimize(.5*y'*X*y - log_det(X)) subject to X >= 0 cvx_end ```
12,851,791
How can I remove digits from a string?
2012/10/12
[ "https://Stackoverflow.com/questions/12851791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1739954/" ]
And, just to throw it in the mix, is the oft-forgotten `str.translate` which will work a lot faster than looping/regular expressions: For Python 2: ``` from string import digits s = 'abc123def456ghi789zero0' res = s.translate(None, digits) # 'abcdefghizero' ``` For Python 3: ``` from string import digits s = 'abc123def456ghi789zero0' remove_digits = str.maketrans('', '', digits) res = s.translate(remove_digits) # 'abcdefghizero' ```
I'd love to use regex to accomplish this, but since you can only use lists, loops, functions, etc.. here's what I came up with: ``` stringWithNumbers="I have 10 bananas for my 5 monkeys!" stringWithoutNumbers=''.join(c if c not in map(str,range(0,10)) else "" for c in stringWithNumbers) print(stringWithoutNumbers) #I have bananas for my monkeys! ```
171,311
I try to understand using of 'to' at the end of this sentence. I understand the meaning but grammar is confusing me. Can someone explain it to me please? I hope I could express myself. I googled but couldn't find anyting. 'songs to dance ***to***', 'songs to make up ***to***' etc, have same construction. Is it about the verbs '***dance***' ,' ***make up***','***have***' or something else that? For me in ***to***'s at the end of construction is necessary but obviously I'm wrong but why? Thanks in advance.
2018/06/28
[ "https://ell.stackexchange.com/questions/171311", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
To "to" at the end of this sentence is a dangling preposition. If you were pedantic, the sentence would be rewritten as: > > Movies **to** which one (can) have a good cry > > > The "to" functions as a preposition indicating what you are crying for (or, in this case, to). In the second example you provided, it would be "Songs to which you can dance," i.e, songs that are good for dancing. The first "to" is for the infinitive of the verb phrase "to have a good cry." The headline as you present it though is very colloquial and *du jour*, and one could likewise say "Tear-jerking Films" "Sentimental Movies" or "Heartbreaking Titles," etc., etc.
> > *movies [(for you) to have a good cry to \_\_ ]* > > > The bracketed "to have a good cry to" is an infinitival relative clause modifying "movies", in which the relativised element is complement of the preposition "to" (represented by the gap notation '\_\_'). It has a modal meaning similar to that expressed in "movies that one can have a good cry to". Note than a subject can be optionally added, as shown in parentheses.
19,784,025
I keep getting the following error while trying to install phonegap 3.0 using cli Can you please help me figure out where I am going wrong? I am using a Macbook Pro ``` ~ developer$ sudo npm install g- phonegap npm http GET https: //registry.npmjs.org/g- npm http GET https: //registry.npmjs.org/phonegap npm http GET https: //registry.npmjs.org/g- npm http GET https: //registry.npmjs.org/phonegap npm http GET https: //registry.npmjs.org/g- npm http GET https: //registry.npmjs.org/phonegap npm ERR! network tunneling socket could not be established, cause=connect ECONNREFUSED npm ERR! network This is most likely not a problem with npm itself npm ERR! network and is related to network connectivity. npm ERR! network In most cases you are behind a proxy or have bad network settings. npm ERR! network npm ERR! network If you are behind a proxy, please make sure that the npm ERR! network 'proxy' config is set properly. See: 'npm help config' npm ERR! System Darwin 13.0.0 npm ERR! command "node" "/usr/local/bin/npm" "install" "g-" "phonegap" npm ERR! cwd /Users/developer npm ERR! node -v v0.10.21 npm ERR! npm -v 1.3.11 npm ERR! code ECONNRESET npm ERR! npm ERR! Additional logging details can be found in: npm ERR! /Users/developer/npm-debug.log npm ERR! not ok code 0 ```
2013/11/05
[ "https://Stackoverflow.com/questions/19784025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2955365/" ]
*edit* - Updated Fiddle I had a similar problem. I got my solution by setting a scroll attribute for background. Also be sure to set the parent container to 100% height and width. AdrianS has the right point for aiming at html to set 100% height and 100% width. In the following code, I have a `header` class for the background image. Adapt it as you need. Check out a fiddle at <http://jsfiddle.net/Bavc_Am/7L3gD/5/> Upvote if helpful please, I'm new here. ``` html, body { height: 100%; width: 100%; } /* Full Page Image Header Area */ .header { display: table; height: 100%; width: 100%; position: relative; background: url(http://placehold.it/800x800.png) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } /* Responsive */ @media (max-width: 768px) { .header { background: url(http://placehold.it/800x800.png) no-repeat center center scroll; } } ```
The solution I will provide can be seen [here](http://css-tricks.com/perfect-full-page-background-image/). But with a minor change. This method is tested many times and for IE it has IE8+ support. You can see the full browser support in the link that I provided. ``` html { width: 100%; height: 100%; } body { background: #Fallback-color; background: url(../images/image.jpg) center top no-repeat; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/image.jpg',sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/image.jpg', sizingMethod='scale')"; height: 100%; } ```
18,565,313
I have the Text box .That text Box ID is **text\_1\_\_val**. I need **1** from that Id.How to Get the Particular part of the textbox ID in jquery which means i need the between \_ and \_\_ from that textbox ID?
2013/09/02
[ "https://Stackoverflow.com/questions/18565313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103259/" ]
If the only requirement is that the character / characters appear between a single and double underscore, try this regular expression match ``` var rx = /_(.+?)__/; var part = rx.test(idValue) && rx.exec(idValue)[1]; ``` This assumes that you're only after the first of any occurrences in your ID value string. If the string fails to match, `part` will be `false`.
The `split()` method is used to split a string into an array of substrings, and returns the new array. ``` $(your_textbox).attr("id").split("_")[1] //Syntax string.split(separator,limit) ``` Function Reference: <http://www.w3schools.com/jsref/jsref_split.asp>
9,115,273
I want 'This Is A 101 Test' to be 'This Is A Test', but I can't get the syntax right. ```ruby src = 'This Is A 101 Test' puts "A) " + src # base => "This Is A 101 Test" puts "B) " + src[/([a-z]+)/] # only does first word => "his" puts "C) " + src.gsub!(/\D/, "") # Does digits, I want alphabetic => "101" puts "D) " + src.gsub!(/\W///g) # Nothing. => "" puts "E) " + src.gsub(/(\W|\d)/, "") # Nothing. => "" ```
2012/02/02
[ "https://Stackoverflow.com/questions/9115273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631619/" ]
No regexp: ``` src = 'This Is A 101 Test' src.delete('^a-zA-Z ') #the ^ negates everything ```
Do you want to cut ' 101' from the string? Here's your regex ``` src = 'This Is A 101 Test' puts src.gsub /\ \d+/, '' # => This Is A Test ``` Also I don't understand why you are using bang version of `gsub`. `gsub!` modifies the original string, `gsub` copies it and modifies the copy.
50,001,851
Will appreciate if someone can please guide or provide me pointers to debug the backup issues with Artifactory. Whenever backups are performed - there is always an error message of 401 on /api/v1/system/backup/export in the artifactory.log The backups exist on backup location but with an error message in the log. Not sure how can debug and implications of this error in the logs. I can see in the stack the rest call is failing, have tried setting a password to unsupported and multiple other things but the error persists. Also checked the Jira on Artifactory to no avail. Any pointers will be greatly appreciated **More details** ``` artifactory.version=5.9.3 artifactory.timestamp=1521564024289 artifactory.revision=50903900 artifactory.buildNumber=820 ``` The backups are failing with following the info in the log. `2018-04-24 11:59:24,620 [ajp-apr-8009-exec-9] [ERROR] (o.a.s.a.AccessServiceImpl:1070) - Error during access server backup org.jfrog.access.client.AccessClientHttpException: HTTP response status 401:Failed on executing /api/v1/system/backup/export, with response: {"errors":[{"code":"UNAUTHORIZED","detail":"Bad credentials","message":"HTTP 401 Unauthorized"}]} at org.jfrog.access.client.http.AccessHttpClient.createRestResponse(AccessHttpClient.java:154) at org.jfrog.access.client.http.AccessHttpClient.restCall(AccessHttpClient.java:113) ...` Following is the full stack as displayed in artifactory.log `2018-04-24 11:59:24,620 [ajp-apr-8009-exec-9] [ERROR] (o.a.s.a.AccessServiceImpl:1070) - Error during access server backup org.jfrog.access.client.AccessClientHttpException: HTTP response status 401:Failed on executing /api/v1/system/backup/export, with response: {"errors":[{"code":"UNAUTHORIZED","detail":"Bad credentials","message":"HTTP 401 Unauthorized"}]} at org.jfrog.access.client.http.AccessHttpClient.createRestResponse(AccessHttpClient.java:154) at org.jfrog.access.client.http.AccessHttpClient.restCall(AccessHttpClient.java:113) at org.jfrog.access.client.system.SystemClientImpl.exportAccessServer(SystemClientImpl.java:21) at org.artifactory.security.access.AccessServiceImpl.exportTo(AccessServiceImpl.java:1060) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:201) at com.sun.proxy.$Proxy144.exportTo(Unknown Source) at org.artifactory.spring.ArtifactoryApplicationContext.exportTo(ArtifactoryApplicationContext.java:662) at org.artifactory.ui.rest.service.admin.importexport.exportdata.ExportSystemService.execute(ExportSystemService.java:67) at org.artifactory.rest.common.service.ServiceExecutor.process(ServiceExecutor.java:38) at org.artifactory.rest.common.resource.BaseResource.runService(BaseResource.java:92) at org.artifactory.ui.rest.resource.admin.importexport.ExportArtifactResource.exportSystem(ExportArtifactResource.java:65) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60) at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205) at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75) at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302) at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108) at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84) at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542) at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473) at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419) at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409) at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409) at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558) at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.artifactory.webapp.servlet.RepoFilter.execute(RepoFilter.java:184) at org.artifactory.webapp.servlet.RepoFilter.doFilter(RepoFilter.java:93) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.artifactory.webapp.servlet.AccessFilter.useAuthentication(AccessFilter.java:403) at org.artifactory.webapp.servlet.AccessFilter.doFilterInternal(AccessFilter.java:212) at org.artifactory.webapp.servlet.AccessFilter.doFilter(AccessFilter.java:166) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.artifactory.webapp.servlet.RequestFilter.doFilter(RequestFilter.java:67) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:164) at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80) at org.artifactory.webapp.servlet.SessionFilter.doFilter(SessionFilter.java:62) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.artifactory.webapp.servlet.ArtifactoryFilter.doFilter(ArtifactoryFilter.java:128) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502) at org.apache.coyote.ajp.AbstractAjpProcessor.process(AbstractAjpProcessor.java:877) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2527) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2516) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) 2018-04-24 11:59:24,660 [ajp-apr-8009-exec-9] [INFO ] (o.a.s.ArtifactoryApplicationContext:819) - Note: the etc exported folder has excessive permissions. Be careful with the files.`
2018/04/24
[ "https://Stackoverflow.com/questions/50001851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9523860/" ]
Since Artifactory version 5.4 there is a separate service in Artifactory named "Access", which manages permissions and security related configurations. Artifactory authenticates with Access using an access token that is configured in the "[Config Descriptor](https://www.jfrog.com/confluence/display/RTF/Configuration+Files#ConfigurationFiles-GlobalConfigurationDescriptor)". It is possible that this issue will be resolved by a simple restart, so that's what i would have started with. If this doesn't work, or what i suspect will happen is Artifactory won't be able to start, please do (while Artifactory is shut down): 1. Remove the `<adminToken>` tag from the `$ARTIFACTORY_HOME/etc/artifactory.config.latest.xml` 2. `$ cp artifactory.config.latest.xml artifactory.config.import.xml` 3. Restart Artifactory.
Added `bootstrap.creds` ``` tomcat@XXXXXXXX:/home/bitnami/apps/artifactory/artifactory_home/etc$ ls -ltrh total 136K -rw-r--r-- 1 tomcat tomcat 5.5K Mar 20 16:41 mimetypes.xml -rw-r--r-- 1 tomcat tomcat 12K Mar 20 16:41 logback.xml -rw-r--r-- 1 tomcat tomcat 13K Mar 20 16:41 artifactory.system.properties -rw-r--r-- 1 tomcat tomcat 11K Mar 20 16:41 artifactory.config.bootstrap.xml -rw-rw-r-- 1 tomcat tomcat 145 Mar 21 13:36 db.properties drwxrwxr-x 2 tomcat tomcat 4.0K Mar 21 13:37 ui drwxrwxr-x 2 tomcat tomcat 4.0K Mar 21 13:37 plugins drwx------ 3 tomcat tomcat 4.0K Mar 21 13:37 security -rw-rw-r-- 1 tomcat tomcat 13K Mar 21 13:37 artifactory.config.latest.1521639475000.xml -rw-r--r-- 1 tomcat tomcat 199 Apr 24 18:50 binarystore.xml -rw-rw-r-- 1 tomcat tomcat 13K Apr 24 18:57 artifactory.config.latest.xml_bkp -rw-rw-r-- 1 tomcat tomcat 12K Apr 24 18:58 artifactory.config.latest.1524596291000.xml -rw-rw-r-- 1 tomcat tomcat 14K Apr 25 14:39 artifactory.config.latest.xml -rw------- 1 tomcat tomcat 24 Apr 25 15:09 bootstrap.creds -rw-rw-r-- 1 tomcat tomcat 864 Apr 25 15:12 artifactory.properties ``` Contents of bootstrap.creds are `access-admin@*=password` AND restarted the arttifactory BUT still seeing the same error message `2018-04-25 15:14:29,607 [art-exec-1] [ERROR] (o.a.s.a.AccessServiceImpl:1070) - Error during access server backup: HTTP response status 401:Failed on executing /api/v1/system/backup/export, with response: {"errors":[{"code":"UNAUTHORIZED","detail":"Bad credentials","message":"HTTP 401 Unauthorized"}]}` I tried the backup using access-admin as well as user from gui with same error (both are admin users). Following are from the access log when artifactory restarted `2018-04-25 15:10:54,396 [localhost-startStop-1] [INFO ] (o.j.a.c.AccessApplicationContextInitializer:46) - Using JFrog Access home at '/opt/bitnami/apps/artifactory/artifactory_home/access' 2018-04-25 15:10:54,413 [localhost-startStop-1] [INFO ] (o.j.a.AccessApplication:48) - Starting AccessApplication v3.2.2 on ip-10-51-35-238 with PID 16169 (/opt/bitnami/apache-tomcat/webapps/access/WEB-INF/lib/access-application-3.2.2.jar started by tomcat in /opt/bitnami/apache-tomcat/bin) 2018-04-25 15:10:54,414 [localhost-startStop-1] [INFO ] (o.j.a.AccessApplication:597) - The following profiles are active: production,grpc 2018-04-25 15:11:11,402 [localhost-startStop-1] [INFO ] (o.j.a.s.d.u.AccessJdbcHelperImpl:129) - Database: Apache Derby 10.11.1.1 - (1616546). Driver: Apache Derby Embedded JDBC Driver 10.11.1.1 - (1616546) 2018-04-25 15:11:11,410 [localhost-startStop-1] [INFO ] (o.j.a.s.d.u.AccessJdbcHelperImpl:132) - Connection URL: jdbc:derby:/opt/bitnami/apps/artifactory/artifactory_home/data/derby 2018-04-25 15:11:16,127 [localhost-startStop-1] [INFO ] (o.j.a.s.s.c.InternalConfigurationServiceImpl:94) - Loading configuration from db finished successfully 2018-04-25 15:11:18,035 [localhost-startStop-1] [INFO ] (o.j.a.s.s.AccessStartupServiceImpl:79) - Found master.key file at /opt/bitnami/apps/artifactory/artifactory_home/etc/security/master.key, using it as master.key 2018-04-25 15:11:19,486 [localhost-startStop-1] [INFO ] (o.j.a.s.s.t.TokenServiceImpl:100) - Scheduling task for revoking expired tokens using cron expression: 0 0 0/1 * * ? 2018-04-25 15:11:19,651 [localhost-startStop-1] [INFO ] (o.j.a.s.r.c.RpcServiceInvoker:86) - Added service: sync 2018-04-25 15:11:20,764 [localhost-startStop-1] [INFO ] (o.j.a.s.AccessServerBootstrapImpl:93) - [ACCESS BOOTSTRAP] Starting JFrog Access bootstrap... 2018-04-25 15:11:23,381 [localhost-startStop-1] [INFO ] (o.j.a.s.AccessServerBootstrapImpl:146) - [ACCESS BOOTSTRAP] Updating server '509b68e8-48e5-4bba-8ea7-6564c65d5b37' private key finger print to: 63c2f42824ead3169fc13eab66d3d254d25c659ceef5cdeed21c3110f47ee0d3 2018-04-25 15:11:24,164 [localhost-startStop-1] [INFO ] (o.j.a.s.AccessServerBootstrapImpl:108) - [ACCESS BOOTSTRAP] JFrog Access bootstrap finished. 2018-04-25 15:11:30,624 [localhost-startStop-1] [INFO ] (o.j.a.s.s.s.RefreshableScheduledJob:56) - Scheduling heartbeat task to run every 5 seconds 2018-04-25 15:11:43,339 [localhost-startStop-1] [INFO ] (o.j.a.AccessApplication:57) - Started AccessApplication in 53.93 seconds (JVM running for 93.388) 2018-04-25 15:11:47,756 [localhost-startStop-1] [WARN ] (o.a.t.u.s.StandardJarScanner:311) - Failed to scan [file:/opt/bitnami/apache-tomcat/lib/derbyLocale_cs.jar] from classloader hierarchy enter code here` Additionaly I enabled trace on the logs. Following is what I am seeing in /home/bitnami/apps/artifactory/artifactory\_home/access/logs/request.log. Seems the ones with backup call are tagged as coming from anonymous vs |jfrt@01c94cf2cpdmx60xvtsf8j1jy4 for other calls. ``` 2018-04-25T15:49:03.906+0000|127.0.0.1|jfrt@01c94cf2cpdmx60xvtsf8j1jy4|GET|http://127.0.0.1/access/api/v1/groups/|200|0|198|JFrog Access Java Client/3.2.2 2018-04-25T15:50:17.553+0000|127.0.0.1|anonymous|POST|http://127.0.0.1/access/api/v1/system/backup/export|401|0|188|JFrog Access Java Client/3.2.2 2018-04-25T15:50:18.657+0000|127.0.0.1|jfrt@01c94cf2cpdmx60xvtsf8j1jy4|GET|http://127.0.0.1/access/api/v1/users/|200|0|84|JFrog Access Java Client/3.2.2 2018-04-25T15:50:18.733+0000|127.0.0.1|jfrt@01c94cf2cpdmx60xvtsf8j1jy4|GET|http://127.0.0.1/access/api/v1/groups/|200|0|73|JFrog Access Java Client/3.2.2 2018-04-25T15:50:42.823+0000|127.0.0.1|anonymous|POST|http://127.0.0.1/access/api/v1/system/backup/export|401|0|134|JFrog Access Java Client/3.2.2 2018-04-25T15:50:42.995+0000|127.0.0.1|jfrt@01c94cf2cpdmx60xvtsf8j1jy4|GET|http://127.0.0.1/access/api/v1/users/|200|0|114|JFrog Access Java Client/3.2.2 2018-04-25T15:50:43.086+0000|127.0.0.1|jfrt@01c94cf2cpdmx60xvtsf8j1jy4|GET|http://127.0.0.1/access/api/v1/groups/|200|0|64|JFrog Access Java Client/3.2.2 ``` Please let me know if I can provide additional relevant information that can help you to get more insight in my envoirnment. Thank you again for you help
55,445
I'm currently watching a cooking series (The Everyday Gourmet) and in one of the lessons the chef talks about what to look for in a wine. For red wine he mentions to look for a wine with a deep red colour as well as a good tannin content, mentioning that subtleties of flavour will likely be lost during cooking. As he was talking about it, rosehip tea popped up as something that meets those two criterias. I tried searching online but couldn't find anything on the subject. It seems a bit far fetched but it has me curious. I don't drink alcohol and have no idea what red wine tastes like so I can't test it as I don't have anything to compare it to. What are your thoughts? EDIT: Instead of straight rosehip, would there be anything I could add that would make it resemble red wine a little more (i.e. a bit of sugar, something acidic, etc)?
2015/03/06
[ "https://cooking.stackexchange.com/questions/55445", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/26666/" ]
One cause of gumminess in 100% rye breads is excessive starch degradation related to amylase enzyme actions. Amylase action is slowed down by increasing acidity. You can increase the acidity by adding a small amount of lemon juice or cream of tartar to your dough as described [here](http://www.veganbaking.net/recipes/breads/enriched-breads/yeasted-enriched-breads/one-hundred-percent-rye-bread). In his books "Whole Grain Breads" and "Crust and Crumb", Peter Reinhart comments that you can use ascorbic acid (1/8 tsp / 125 mg per loaf) to increase acidity and inhibit both amylase and protease activity. Since rye bread doesn't have significant gluten for structure, but instead relies completely on starches and pentosans, it is imperative to let the loaf cool completely before cutting it so that the starches crystallize and the gums solidify.
Try steaming it instead of baking.
184,737
Do the changes in the following sentences change the meaning at all? > > He's my friend > > > I'm his friend > > > Or > > He's my co-worker > > > I'm his co-worker > > > Or > > he's my brother > > > I'm his brother > > > Besides emphasis - is there any change in meaning in these sentences? Can they be interchangeable? (Assuming friends are not just one sided!)
2014/07/12
[ "https://english.stackexchange.com/questions/184737", "https://english.stackexchange.com", "https://english.stackexchange.com/users/68094/" ]
Yes, it depends on whether the relationships are symmetric. Brotherhood is not symmetric, because if you're a girl and he's your brother, then you could say > > he's my brother > > > but switching it and saying > > I'm his brother > > > is clearly wrong, you'd say > > I'm his sister. > > > In other words, "He's my brother" doesn't imply anything about your gender, but "I'm his brother" clearly does, so the two phrases have different meaning. The "co-worker" relationship is symmetric. "Friendship" is debatable. You might consider someone your friend but they may not consider you their friend, sadly.
I agree with what Amit wrote, but would add besides, that in each case the two pairs are not interchangeable because of the point of view of each sentence of each of the pairs. In one case, it's from your point of view (first person singular) in one of the sentences, and from the other person's point of view (third person singular) in the other. If the relationships were described in the third person plural, e.g. "we're friends", "we're brothers" (or if one is male and one female, "we're siblings", or "we're co-workers", these would be equivalent to both parties.
8,797,568
I have a `HTML` webform (**NOT** asp.net webform) that submits its form to an `aspx` script. On the `aspx` script, I'd like to simply forward the form submission to a different form processing script. (after checking just one or two things using `Request.Form["variable"]`) What is the simplest way to forward the original html page's form submission? ``` Currently: html1 -> aspx1 -> html2 Desired: html1 -> aspx1 -> aspx2 -> html2 ```
2012/01/10
[ "https://Stackoverflow.com/questions/8797568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691887/" ]
**I would attempt to solve this problem in the following fashion** 1. Create a Repeater 2. Set the Request.Form as the datasource of the repeater. If this does not work, i would convert Request.Form into a suitable datastructure, such as a Dictionary or Datatable for binding to the Repeater 3. Each repeater item would have an input tag, and would receive the appropriate name/id and value. I would not use a server-control input tag. I would emit the string in a more organic fashion. 4. I would then post to the second aspx page. The purpose of the repeater is to build an equivalent Form NameValueCollection for processing on the second aspx page. **References** * [Cross Page Postback](http://msdn.microsoft.com/en-us/library/ms178139.aspx) * [Posting to another page](http://msdn.microsoft.com/en-us/library/ms178140.aspx) * [Binding a Dictionary to a Repeater](http://forums.asp.net/p/1184360/2020322.aspx) * [Binding Dictionary to DropDownList](http://geekswithblogs.net/mnf/archive/2006/12/19/101546.aspx) - (Note, "Key", "Value")
If it is only about simplest way then it is using session variable. Just save your form values to the session and then you can access it anywhere in your application during the particular session. So I would have my aspx1 page something like this ``` // ASPX1 page's Page_Load protected void Page_Load(object sender, EventArgs e) { if (Request.Form["variable"] == "SomeValue")//some condition { // save these values to session so that they will // be available when I will be in aspx2 page Session["FormValues"] = Request.Form; Response.Redirect("ASPX2.aspx"); // your aspx2 page's link } } ``` And aspx2 page something like this ``` // ASPX2 page's Page_Load protected void Page_Load(object sender, EventArgs e) { // form values from aspx1 page NameValueCollection formValuesCollection = (NameValueCollection)Session["FormValues"]; string variableValue = formValuesCollection["variable"]; // some processing using form values from aspx1 page Response.Redirect("HTML2.html"); } ```
27,453,118
C++ compiler not letting me use an array as parameter to function call in a userdefined function. Can some one explain this to me and help me with a solution? ``` #include <iostream> using namespace std; double GetAverage(int[], int = 10); int GetAboveAverage(int[], int = 10); const int ARRAYSIZE = 10; void main() { int mArray[ARRAYSIZE]; cout << "Input the first number" << endl; for (int i = 0; i <= ARRAYSIZE - 1; i++) { cin >> mArray[i]; cout << "Input the next number" << endl; } cout << "The average of the nummbers is " << GetAverage(mArray, ARRAYSIZE) << endl; cout <<"The the amount above average is " << GetAboveAverage(mArray, ARRAYSIZE) <<endl; system("pause"); } ``` The function whit the problem calls this function. ``` double GetAverage(int fArray[], int arrSize) { int sum = 0; int average; for (int i = 0; i <= arrSize- 1; i++) sum += fArray[i]; average = sum / arrSize; return average; } ``` Hear is where the problem is. ``` int GetAboveAverage(int gArray[], int arrSize) { int amtAboveAve; int average = GetAverage( gArray[], arrSize); //where i get the error its on the bracket and it says "error: expected and expression" for (int i = 0; i <= 9; i++) if (gArray[i] > average) amtAboveAve++; return amtAboveAve; } ```
2014/12/12
[ "https://Stackoverflow.com/questions/27453118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4355721/" ]
If you want to call method BEFORE constructor you can use initializer block. <https://www.geeksforgeeks.org/g-fact-26-the-initializer-block-in-java/> ``` class A { { init() } public A() { //todo } private final void init() { //todo } } ```
Why not this : ``` Class A { public A() { //... Do you thing this.init(); } public void init() { //Call after the constructor } } ```
30,482,083
I am trying to learn how to utilize Java 8 features(such as lambdas and streams) in my daily programming, since it makes for much cleaner code. Here's what I am currently working on: I get a string stream from a local file with some data which I turn into objects later. The input file structure looks something like this: ``` Airport name; Country; Continent; some number; ``` And my code looks like this: ``` public class AirportConsumer implements AirportAPI { List<Airport> airports = new ArrayList<Airport>(); @Override public Stream<Airport> getAirports() { Stream<String> stream = null; try { stream = Files.lines(Paths.get("resources/planes.txt")); stream.forEach(line -> createAirport(line)); } catch (IOException e) { e.printStackTrace(); } return airports.stream(); } public void createAirport(String line) { String airport, country, continent; int length; airport = line.substring(0, line.indexOf(';')).trim(); line = line.replace(airport + ";", ""); country = line.substring(0,line.indexOf(';')).trim(); line = line.replace(country + ";", ""); continent = line.substring(0,line.indexOf(';')).trim(); line = line.replace(continent + ";", ""); length = Integer.parseInt(line.substring(0,line.indexOf(';')).trim()); airports.add(new Airport(airport, country, continent, length)); } } ``` And in my main class I iterate over the object stream and print out the results: ``` public class Main { public void toString(Airport t){ System.out.println(t.getName() + " " + t.getContinent()); } public static void main(String[] args) throws IOException { Main m = new Main(); m.whatever(); } private void whatever() throws IOException { AirportAPI k = new AirportConsumer(); Stream<Airport> s; s = k.getAirports(); s.forEach(this::toString); } } ``` My question is this: How can I optimize this code, so I don't have to parse the lines from the file separately, but instead create a stream of objects Airport straight from the source file? Or is this the extent in which I can do this?
2015/05/27
[ "https://Stackoverflow.com/questions/30482083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140728/" ]
You need to use [`map()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-) to transform the data as it comes past. ``` Files.lines(Paths.get("resources/planes.txt")) .map(line -> createAirport(line)); ``` This will return a `Stream<Airport>` - if you want to return a `List`, then you'll need to use the `collect` method at the end. This approach is also stateless, which means you won't need the instance-level `airports` value. You'll need to update your createAirport method to return something: ``` public Airport createAirport(String line) { String airport = line.substring(0, line.indexOf(';')).trim(); line = line.replace(airport + ";", ""); String country = line.substring(0,line.indexOf(';')).trim(); line = line.replace(country + ";", ""); String continent = line.substring(0,line.indexOf(';')).trim(); line = line.replace(continent + ";", ""); int length = Integer.parseInt(line.substring(0,line.indexOf(';')).trim()); return new Airport(airport, country, continent, length); } ``` If you're looking for a more functional approach to your code, you may want to consider a rewrite of `createAirport` so it doesn't mutate line. Builders are also nice for this kind of thing. ``` public Airport createAirport(final String line) { final String[] fields = line.split(";"); return new Airport(fields[0].trim(), fields[1].trim(), fields[2].trim(), Integer.parseInt(fields[3].trim())); } ``` Throwing it all together, your class now looks like this. ``` public class AirportConsumer implements AirportAPI { @Override public Stream<Airport> getAirports() { Stream<String> stream = null; try { stream = Files.lines(Paths.get("resources/planes.txt")) .map(line -> createAirport(line)); } catch (IOException e) { stream = Stream.empty(); e.printStackTrace(); } return stream; } private Airport createAirport(final String line) { final String[] fields = line.split(";"); return new Airport(fields[0].trim(), fields[1].trim(), fields[2].trim(), Integer.parseInt(fields[3].trim())); } } ```
The code posted by Steve looks great. But there are still two places can be improved: 1, How to split a string. 2, It may cause issue if the people forget or don't know to close the stream created by calling getAirports() method. So it's better to finish the task(toList() or whatever) in place. Here is code by [AbacusUtil](https://github.com/landawn/AbacusUtil) ``` try(Reader reader = IOUtil.createBufferedReader(file)) { List<Airport> airportList = Stream.of(reader).map(line -> { String[] strs = Splitter.with(";").trim(true).splitToArray(line); return Airport(strs[0], strs[1], strs[2], Integer.valueOf(strs[3])); }).toList(); } catch (IOException e) { throw new RuntimeException(e); } ``` // Or By the [Try](https://cdn.rawgit.com/landawn/AbacusUtil/master/docs/Try_view.html): ``` List<Airport> airportList = Try.stream(file).call(s -> s.map(line -> { String[] strs = Splitter.with(";").trim(true).splitToArray(line); return Airport(strs[0], strs[1], strs[2], Integer.valueOf(strs[3])); }).toList()) ``` Disclosure: I'm the developer of AbacusUtil.
5,603,052
How does HTTPS work with respect to accepting a certificate?
2011/04/09
[ "https://Stackoverflow.com/questions/5603052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686257/" ]
Very sipmly put with a **little story**: > > **Client** : *(Connects to the server and, sticks out it's hand)* "Hello! Here are my encryption details." > > > **Server** : (Takes hand of the client) "Hello. Here are my encryption details. Here is my certificate." (Handshake negotiation complete. Client check the cerificate) > > > **Client** : Great, here's my key! So from now on everything is encrypted using this key. OK? > > > **Server** : OK! (SSL Handshake complete) > > > **Client** : Great, Here comes my data over HTTP!! > > > [Certificates](http://en.wikipedia.org/wiki/Digital_certificates) are used in the [SSL handshake](http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake_in_detail). The certificate that the server hands to the client is [signed](http://en.wikipedia.org/wiki/Certificate_signing_request) by a [Certificate Authority](http://en.wikipedia.org/wiki/Certificate_authority) (CA) like VeriSign and is specific to the server. There are various checks that happens in the SSL handshake. One of the important ones to know about is the **Common Name** attribute of the certificate must match the host / DNS name of the server. The client has a copy of the CA's [public certificate (key)](http://en.wikipedia.org/wiki/Public_key_certificate) and can thus use it (calculate with SHA1 for example) to see if the server's certificate is still ok.
First of all we need to distinguish server-side and client-side certificates. In most cases only the server-side certificate is used. It is used to let the client verify the authenticity of the server that the client has connected to by validating the server's certificate (validation procedure will be described below). Doing this should prevent man-in-the-middle (MITM) attack. Client-side certificate is used when we need to restrict access to the server to only some set of users. To do this the client authenticates itself with the certificate. As the set of users is usually limited (by some criteria, it can be quite large in real life), validation procedure is often a bit different from the server cert validation procedure. Next, about validation itself. When validating the server's certificate on the client, the client takes the following steps: 1. Find issuer (CA) certificate and check the signature of the server's certificate using issuer certificate (technical details skipped). 2. Check certificate validity period (from when to when the certificate should be accepted). 3. Check certificate intended usage (each certificate can be restricted to only some purposes). 4. Check that the certificate has been issued for domain name (or IP address) that the server is located on. 5. Check that the certificate has not been canceled (revoked) by the CA. This is done by checking certificate revocation lists (CRL) and by sending an on-the-fly request using OCSP protocol. 6. As CRLs and OCSP responses are signed using certificates, their signatures are also validated as described above. 7. The procedure is repeated for the CA certificate mentioned in step (1) and this goes on until you get to trusted root CA certificate (it is assumed that the client has a set of trusted root certificates). When the server validates client's certificate, the above procedure is usually simplified because the same system is a CA and a server access to which is verified. In this case certificates can be either matched directly to the list of allowed certificates or most of the above steps can be unnecessary.
35,498,389
When I search Google, I got SBShortcutMenuSimulator, it's can simulator Quick Action operate in iOS simulator. But, how test peek and pop operate?
2016/02/19
[ "https://Stackoverflow.com/questions/35498389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4361355/" ]
I find way! If your have MacBook Pro with ForceTouch Trackpad, you can do it. Follow: Choose iOS 9.3 with iPhone 6S Simulator, Find Hardware option on menu bar, check "Use Trackpad force for 3D Touch", then use your force touch Trackpad simulate 3D Touch.
You can use FLEX to check it on the simulator. Using a combination of the command, control, and shift keys, you can simulate different levels of 3D touch pressure in the simulator. Each key contributes 1/3 of maximum possible force. Note that you need to move the touch slightly to get pressure updates. <https://github.com/Flipboard/FLEX> Just remember to **exclude FLEX from Release (App Store) Builds**
18,473
I've been googling around for a cheap CDN service and came across: <http://code.google.com/speed/pss/index.html> This seems to be a competitor to other CDN services, is this the case? Thanks
2011/08/19
[ "https://webmasters.stackexchange.com/questions/18473", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/3512/" ]
Anything that helps a search engine better understand the content and makeup of a web page is ostensibly better for SEO. The information a spider is able to discern about the structure of your page directly increases the accuracy of the spider's effective grading of your page. This is not to say that it will necessarily give you a better ranking, only to say that the spider will more accurately rank your page based on its content (which typically results in a positive gain). This is why table based layouts are so bad for SEO... it is nearly impossible for a spider to distinguish between body copy, headers, sidebars, etc. Therefore it is significantly more difficult for the bot to determine contextual relevancy of any one keyword/phrase against another. This makes the end weight of the page far lighter than what it would have been otherwise, had the bot been able to understand the correlation between the content on a page.
The direct answer is: No. You could use HTML4 designing the document with block elements (`<div>`) instead of using semantic elements (`<main>`, `<article>`, `<aside>`, `<nav>`, etc), and the result in the SERPs would be exactly the same. It would affect if you had a really bad design, for example using HTML frames: that would be negative because crawlers could not read all the content of the site. It would also affect if you used Flash for the design, instead of using HTML elements with its content.
35,363,443
I have an input type number element with a min and max values. Preventing the default function I have customized it to use the with separate inputs. I don't know how can we trigger the max value from the input element which contains min and max attributes. Though i give max range the plus crosses the value. ```js $('.plus').on('click', function(e) { var val = parseInt($(this).prev('input').val()); $(this).prev('input').attr('value', val + 1); }); $('.minus').on('click', function(e) { var val = parseInt($(this).next('input').val()); if (val !== 0) { $(this).next('input').attr('value', val - 1); } }); ``` ```css body { background-color:#eeeeee; margin: 40px; } .minus, .plus { border: none; padding: 10px; width: 40px; font-size: 16px; } input[type=number].quantity::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .quantity { padding: 10px; border: none; width: 40px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="quantity-block"> <input class="minus" type="button" value="-"> <input type="number" value="1" class="quantity" size="4" min="1" max="5"/> <input class="plus" type="button" value="+"> </div> ```
2016/02/12
[ "https://Stackoverflow.com/questions/35363443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5257219/" ]
You can read the `max` attribute and then use it in a condition.: ```js $('.plus').on('click', function(e) { var val = parseInt($(this).prev('input').val()); var max = parseInt($(this).prev('input').attr('max')); if(val < max) { $(this).prev('input').attr('value', val + 1); } }); $('.minus').on('click', function(e) { var val = parseInt($(this).next('input').val()); if (val !== 0) { $(this).next('input').attr('value', val - 1); } }); ``` ```css body { background-color:#eeeeee; margin: 40px; } .minus, .plus { border: none; padding: 10px; width: 40px; font-size: 16px; } input[type=number].quantity::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .quantity { padding: 10px; border: none; width: 40px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="quantity-block"> <input class="minus" type="button" value="-"> <input type="number" value="1" class="quantity" size="4" min="1" max="5"/> <input class="plus" type="button" value="+"> </div> ```
You just had to put an if condition, ```js $('.plus').on('click', function(e) { var val = parseInt($(this).prev('input').val()); if (val < $(this).prev('input').attr('max')) { $(this).prev('input').attr('value', val + 1); } }); $('.minus').on('click', function(e) { var val = parseInt($(this).next('input').val()); if (val !== 0) { $(this).next('input').attr('value', val - 1); } }); ``` ```css body { background-color:#eeeeee; margin: 40px; } .minus, .plus { border: none; padding: 10px; width: 40px; font-size: 16px; } input[type=number].quantity::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .quantity { padding: 10px; border: none; width: 40px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="quantity-block"> <input class="minus" type="button" value="-"> <input type="number" value="1" class="quantity" size="4" min="1" max="5"/> <input class="plus" type="button" value="+"> </div> ```
916,987
We know the common result : - If every vertex of a graph **G** has degree at least2, then **G** contains a cycle. Can I conclude that 2-regular graphs are cycles where degree is exactly two of every vertex? I am not getting any contradictory example. Please help me if am wrong. Need some help. I worked like this: If the graph **G** has n vertices of degree two. Let us assume that all vertices have degree two except two vertices, say vertex ***v*** and ***u***. now to make degree two of vertex ***v*** and ***u***, we must attach them with other vertices. only possible case is to make vertices ***u*** and ***v*** together. otherwise if we make them adjacent to some other vertex, then degree of that vertex will be three or more. Contradiction. Is my conclusion right? NOTE: $G$ is a connected graph.
2014/09/02
[ "https://math.stackexchange.com/questions/916987", "https://math.stackexchange.com", "https://math.stackexchange.com/users/42830/" ]
Suppose $G$ isn't cyclic. We know that $G$ contains at least one cycle $C$ (because every graph with $\delta (G)>1$ contains a cycle). $G$ is connected and that means that there exists vertices, for example $v$, that are not in $C$ but are neigbors to some vertices in $C$, for example $w \in C$. But since $w$ is in cycle, it has some neigbors that are too in that cycle, for example $w\_1, w\_2$. So if $w$ is adjacent at the same time to $w\_1, w\_2$ and $v$ then $deg(w)>2$ and that is contradiction because $G$ is $2$-regular thus there are no vertices with degree greater than $2$.
Note that if $G$ is connected then in the case that every vertex has a degree of exactly 2, not only that there exists a cycle, there exists an Eulerian cycle (in which you use every edge exactly once).
37,987,563
I'm new to Jade and i got the assignment to create a select option in a webpage. Everything seems good until i get an empty option element which is created when the drop-down list is empty and the Page is refreshed. I want to somehow remove this empty option element. I went through most posts here but didn't seem to get any help. Below is my Jade logic. Jade: ``` #remarksField h1#remarksHeader Remarks select#shortDesc option(value= "")= "---" each index in data if (index) option(value= index.id)= index.short_desc // else ``` Don't know how to post a Fiddle because it's part of a large Code but I hope someone gets to help me out here. [![How it looks when trying to select an option](https://i.stack.imgur.com/8Essm.png)](https://i.stack.imgur.com/8Essm.png)
2016/06/23
[ "https://Stackoverflow.com/questions/37987563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277469/" ]
The extra indentation after the first `option` tag causes all of the following options to be inside the first tag. Remove that extra indentation and it should all work: ``` #remarksField h1#remarksHeader Remarks select#shortDesc option(value= "")= "---" each index in data if (index) option(value= index.id)= index.short_desc // else ```
Add placeholder ``` option(value="1" placeholder="Select") ``` It would avoid it from getting blank on refresh.
309,101
How do I get the `GridView` control to render the `<thead>` `<tbody>` tags? I know `.UseAccessibleHeaders` makes it put `<th>` instead of `<td>`, but I cant get the `<thead>` to appear.
2008/11/21
[ "https://Stackoverflow.com/questions/309101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28543/" ]
This should do it: ``` gv.HeaderRow.TableSection = TableRowSection.TableHeader; ```
I know this is old, but, here's an interpretation of MikeTeeVee's answer, for a standard gridview: aspx page: ``` <asp:GridView ID="GridView1" runat="server" OnPreRender="GridView_PreRender"> ``` aspx.cs: ``` protected void GridView_PreRender(object sender, EventArgs e) { GridView gv = (GridView)sender; if ((gv.ShowHeader == true && gv.Rows.Count > 0) || (gv.ShowHeaderWhenEmpty == true)) { //Force GridView to use <thead> instead of <tbody> - 11/03/2013 - MCR. gv.HeaderRow.TableSection = TableRowSection.TableHeader; } if (gv.ShowFooter == true && gv.Rows.Count > 0) { //Force GridView to use <tfoot> instead of <tbody> - 11/03/2013 - MCR. gv.FooterRow.TableSection = TableRowSection.TableFooter; } } ```
2,688,002
So far, I've been merely using YARV (ruby 1.9) as merely a faster implementation of ruby than ruby 1.8, and ensured that all of my code is backwards-compatible with ruby 1.8.6. What circumstances, if any, are stopping you from writing 1.9-specific code? One reason per answer.
2010/04/22
[ "https://Stackoverflow.com/questions/2688002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38765/" ]
I wish I could [forget about Iconv](https://stackoverflow.com/questions/2445175/tab-lf-cr-unicode-character) when handling unicode data, like this: ``` Iconv.conv("utf-8", "utf-16le", blob).split("\n") ``` but so far I **could not find good examples**/tutorial of 1.9 unicode handling yet.
Nothing is discouraging me. I've been using Ruby 1.9.1 for everything I do for close to a year now and had few problems. My [major](http://github.com/SFEley/candy) [gems](http://github.com/SFEley/acts_as_icontact) *require* 1.9 for various reasons (easy UTF-8, fibers, etc.) and I've felt no qualms about it. For some other [trivial](http://github.com/SFEley/sinatra-sessionography) gems I might make a token effort to keep them 1.8 compatible, which mostly just means not using the cleaner new hash syntax. 1.9 is the current Ruby. I can see needing to keep the old Ruby around for legacy code that isn't worth updating, or having a preference for an alternative Ruby (JRuby, Rubinius, etc.) -- but it truly baffles me why so many people are still starting new projects in the slower, obsolete Ruby 1.8.x line.
3,723,044
If I input `5 5` at the terminal, press enter, and press enter again, I want to exit out of the loop. ``` int readCoefficents(double complex *c){ int i = 0; double real; double img; while(scanf("%f %f", &real, &img) == 2) c[i++] = real + img * I; c[i++] = 1 + 0*I; // most significant coefficient is assumed to be 1 return i; } ``` Obviously, that code isn't doing the job for me (and yes, I know there is a buffer overflow waiting to happen). `scanf` won't quit unless I type in a letter (or some non-numeric, not whitespace string). How do I get scanf to quit after reading an empty line?
2010/09/16
[ "https://Stackoverflow.com/questions/3723044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449021/" ]
There's a way to do what you want using just scanf: ``` int readCoefficents(double complex *c) { int i = 0; double real; double img; char buf[2]; while (scanf("%1[\n]", buf) == 0) { // loop until a blank line or EOF if (scanf("%lf %lf", &real, &img) == 2) // read two floats c[i++] = real + img * I; scanf("%*[^\n]"); // skip the rest of the line scanf("%*1[\n]"); // and the newline } c[i++] = 1 + 0*I; // most significant coefficient is assumed to be 1 return i; } ``` If the user only enters 1 float on a line, it will read the next line for the second value. If any random garbage is entered, it will skip up to a newline and try again with the next line. Otherwise, it will just go on reading pairs of float values until the user enters a blank line or an EOF is reached.
re PAXDIABLO solution: it does not work properly with EMPTY line entered by user, so this line shall be added in your getLine() function ``` if (strlen(buff) <= 1) return NO_INPUT; ``` after the line: ``` if (fgets (buff, sz, stdin) == NULL) return NO_INPUT; ``` So it will become : ``` ... if (strlen(buff) <= 1) return NO_INPUT; if (fgets (buff, sz, stdin) == NULL) return NO_INPUT; .... ```
30,840,961
I'd like to run a function that is identified by a string. ``` toRun = 'testFunction' def testFunction(): log.info('In the function'); run(toRun) ``` Where `run` would be whatever command I need to use. I've tried with `exec`/`eval` without much luck.
2015/06/15
[ "https://Stackoverflow.com/questions/30840961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079477/" ]
The build in function [`getattr()`](https://docs.python.org/2/library/functions.html#getattr) can be used to return an named attribute of the object passed as argument. **Example** ``` >>> import sys >>> def function(): ... print 'hello' ... >>> fun_object = getattr( sys.modules[ __name__ ], 'function') >>> fun_object() hello ``` **What it does** * `sys.modules[ __name__ ]` returns the current module object. * `getattr( sys.modules[ __name__ ], 'function')` returns an attribute by the name `function` of the object, `sys.modules[ __name__ ]` which is the current object. + [Read more about sys.modules](https://docs.python.org/2/library/sys.html#sys.modules) * `fun_object()` calls the returned function.
You can use `eval` ``` eval("testFunction()") # must have brackets in order to call the function ``` Or you could ``` toRun += "()" eval("eval(toRun)") ```
41,833,798
I have a dropdown menu and I wanna use angular2 directive to handling open/close of this dropdown. How can I add `open` class to the `latest-notification` div . by knowing that my directive applied to the `button` tag! Here is my html code: ``` <div class="header-notification" (clickOutside)="showPopupNotification = false"> <button appDropdown> <span [class.has-notification]="hasNotification"></span><icon name="ico_notification"></icon> </button> <div class="latest-notification"> <span class="top-pointer"><icon name="arrow-popup"></icon></span> <div class="wrap"> <ul> <li *ngFor="let notify of notifications" [class.seen]="notify.seen"> <a> <avatar src="{{notify.userProfileUrl}}" size="35"></avatar> <time>{{notify.createAt}}</time> <h5>{{notify.name}}</h5> <p>{{notify.message}}</p> </a> </li> </ul> </div> </div> </div> ``` And here's my directive: ``` import {Directive, HostBinding, HostListener} from '@angular/core'; @Directive({ selector: '[appDropdown]' }) export class DropdownDirective { private isOpen = false; @HostBinding('class.open') get opened() { return this.isOpen; } @HostListener('click') open() { this.isOpen = !this.isOpen; } constructor() { } } ```
2017/01/24
[ "https://Stackoverflow.com/questions/41833798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184592/" ]
Sorry for late respond. You could use `exportAs` meta property in directive to achieve what you want. ***(I'll show you relevant lines only where you need to make changes)*** --- ``` /* #temp is a local template variable */ /* mydir is defined in dropdowndirective as exportAs meta property */ <button #temp=mydir appDropdown> ``` --- ``` /* using vc which is defined in dropdown component */ <div class="latest-notification" [class.open]="vc.isOpen" [class.close]="!vc.isOpen"> ``` --- ``` import {DropdownDirective} from 'path'; export class DropDownComponent{ @Viewchild('temp') vc:DropdownDirective; // vc can hold isOpen variable directly defined in Dropdowndirective. } ``` --- ``` @Directive({ selector: '[appDropdown]' exportAs:'myDir' // addded this line }) ``` **Demo : <http://plnkr.co/edit/AE8n4McCez7ioxiTSExL?p=preview>**
Hello i made an improved update to @Sajad answer regarding: * angular11 * bootstrap 4 * Renderer2 * addClass(), removeClass() HTML ``` <div class="btn-group"> <button type="button" class="btn btn-primary dropdown-toggle" appDropdown > Manage Recipe </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">To Shop List</a> <a class="dropdown-item" href="#">Edit Recipe</a> <a class="dropdown-item" href="#">Delete Recipe</a> </div> </div> ``` Directive ``` import {Directive, ElementRef, EventEmitter, HostListener, Renderer2} from '@angular/core'; @Directive({ selector: '[appDropdown]' }) export class DropdownDirective { isOpen:boolean = false; constructor( private elRef: ElementRef, private renderer: Renderer2 ) { } // TOGGLE dropdownMenu @HostListener('click') toggleOpen(): void { const dropdownMenu: HTMLElement = this.elRef.nativeElement.nextSibling; this.isOpen = !this.isOpen; if( this.isOpen ) { this.renderer.addClass(dropdownMenu, 'show'); } else{ this.renderer.removeClass(dropdownMenu, 'show'); } console.log(this.isOpen); } // CLOSE dropdown if outside click clickOutside = new EventEmitter<Event>(); @HostListener('document:click', ['$event', '$event.target']) onClick( event: Event, targetElement: HTMLElement ): void { if (!targetElement || this.isOpen === false ) return; const dropdownMenu: HTMLElement = this.elRef.nativeElement.nextSibling; let clickedInside = this.elRef.nativeElement.contains(targetElement); if (!clickedInside) { this.clickOutside.emit(event); this.renderer.removeClass(dropdownMenu,'show'); this.isOpen = false; } } } ```
71,668,268
In a jupyter notebook, I can fairly easily check with python code if some libraries are installed on the current kernel of the python notebook. However there is also the "host" kernel which has its own python env (ie the python process that was launched when `jupyter notebook` was called). Depending on what libraries/extensions were installed on the host, it may not be possible to do specific things on the jupyter notebook client itself. Is there a way to query what libraries/modules/extensions are installed on the host, from the "client" notebook ? thanks
2022/03/29
[ "https://Stackoverflow.com/questions/71668268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875295/" ]
I guess you can use `!pip list` to show the modules/libraries installed on the current env. But I don't think you can view extensions.
I believe !pip list should work- if not, then pydoc most likely would, see above.
7,579,385
I have a java web application that use spring security for log in users, restriction access etc. , and it is working without problems on Glassfish 2.1, Tomcat, jetty, but on glassfish v3 doesn't work, when I try to login, and press button login, I'm getting login box from glassfish server(the box "The server xxxx requires user name and password"). Has somebody got such issue? Please let me know how I can solve this. Thanks, Iurie
2011/09/28
[ "https://Stackoverflow.com/questions/7579385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/627346/" ]
I don't know what is causing this (and potentially it could be one of a number of things), but I suggest that you turn the logging level up to the max and see if that gives you some clues as to what is going on. (When the logging level is DEBUG or higher, SpringSecurity generates lots of logging.) --- > > ... the request is not sent to spring security, the glassfish stopped it with his basic authentication, the question is why. > > > I don't know what the cause of this is, but it sounds like some aspect of Glassfish authentication / authorization needs to be turned off if you want to use SpringSecurity. (Maybe you did this in your Glassfish 2.1 installation ...) The way that SpringSecurity works, you will definitely see logging messages if a request goes to a servlet that has the SS filter chain in place. It is possible that there is a SS misconfiguration that means that you've not got the SS filter chain in place, but I suspect that the real problem is that Glassfish is doing its bit **before** the requests get sent to the filter chain.
Did you create a JDBC Connection pool and Resource in Glassfish server? For ex: ``` User: root Password: java databaseName: theDatabase serverName: localhost portNumber: 3306 driverClass: com.mysql.jdbc.Driver URL: jdbc:mysql://localhost:3306/dbname ```
25,816,333
Recently I got a interview programming question about how to find maximum number M less than N, and some specific digit is not allowed to exist in M. For example, N = 123, digit = 2,then it will output: 119 My ideas is to convert N to string first, and then find the first position of digit from left to right to make this digit decreased by 1. Then I set all the remaining digits in N to 9 to make this number maximized. Does some could point out some corner case which I ignored? and is there some good implementation in Java of this problem for reference?
2014/09/12
[ "https://Stackoverflow.com/questions/25816333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2052141/" ]
Attempt 3. Still O(n) but due to the special 0 case needing to cascade back up: ``` static int banDigit(int number, int digit) { int length = (Integer.toString(number)).length(); int result = 0; boolean foundDigit = false; for (int i = length - 1; i >= 0; i--) { if (!foundDigit) { int currentDigit = (int) number / ((int) Math.pow(10, i)); number = number % (int) Math.pow(10, i); if (currentDigit == digit) { //if nonzero digit banned, we can just decrement and purge 9 or 8 to right if (digit > 0) { currentDigit--; } else { // we have to subtract one from the previous result = result - (int) Math.pow(10, i); //then we have to check if doing that caused a bunch of ones prior for (int j = i + 1; j < length; j++) { if ((int) (result % (int) Math.pow(10, j + 1)) / (int) Math.pow(10, j) == 0) { result = result - (int) Math.pow(10, j); } } } foundDigit = true; } result += currentDigit * Math.pow(10, i); } else if (digit == 9) { result += 8 * Math.pow(10, i); } else { result += 9 * Math.pow(10, i); } } return result; } ```
I think it works, please tell me if you see any case not well handled. ``` public static void main(String[] args) { int N = 100211020; int digit = 0; int m; for (m = 9 ; m > 0 && m == digit; m--); String sres; String s = N + ""; int length = s.length(); int i = s.indexOf(digit + ""); if (i < 0) sres = s; else { StringBuilder sb = new StringBuilder(); if (digit != 0) { for (int j=0 ; j<i ; j++) sb.append(s.charAt(j)); sb.append(digit - 1); for (int j=i + 1 ; j<length ; j++) sb.append(m); } else { if (s.charAt(0) != '1') sb.append(mod10(s.charAt(0) - '0' - 1)); for (int j=1 ; j<length ; j++) sb.append(9); } sres = sb.toString(); } System.out.println(sres); } public static int mod10(int n) { int res = n % 10; return res < 0 ? res + 10 : res; } ``` **EDIT :** I finally decided to use strings to handle the case of `digit = 0`, which was quite complicated with my first approach.
65,772
I'm new to magento so please remember when responding. What I want to do is change the text on the magento check option. I had the ability to change the title to "wire transfer" but would like to change the text that says "make check payable to" and "send check to". Please let me know if this is possible and where I would find this file. Thank you for your help! ![enter image description here](https://i.stack.imgur.com/5MvWz.png)
2015/05/05
[ "https://magento.stackexchange.com/questions/65772", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/24930/" ]
You can do that by enabling the translation mode in magento. Connect to the admin Go in `System-> Configuration ->Advanced -> developper -> Translated Inline -> Front End switch` to `yes` You should see on the front end some red box around every texts, click on the one you need to translate, change it and then re-stwitch to off the translated inline mod when you are done. Don't forget to disable the cache before doing that.
You can change the text for those by going to `your_web_root/app/design/frontend/base/default/template/payment/form/checkmo.phtml` The text that gets displayed on the frontend can be found here. I would copy this file to your theme and then make the necessary text changes. After you make the change clear your cache if it is enabled.
10,189,331
I have a very simple Child-Parent relationship, where OlderSon inherits from Parent and a Parent has a pointer to his OlderSon, such as: ```cpp #ifndef PARENT_HXX #define PARENT_HXX #include <iostream> #include <string> //#include "OlderSon.hxx" class OlderSon; class Parent { private : OlderSon* _os; public : int _age; std::string _name; Parent(){ _name="parent name"; _age=60; //OlderSon* _os=new OlderSon(); } }; #endif //PARENT_HXX ``` And son: ```cpp #ifndef OLDERSON_HXX #define OLDERSON_HXX #include <iostream> #include <string> #include "Parent.hxx" class OlderSon: public Parent { public: OlderSon(){ _age=25; _name="Olderson name"; } }; #endif //OLDERSON_HXX ``` However whenever I try to uncomment the line where the pointer is initialized `OlderSon* _os=new OlderSon();` I get an error message: ``` Parent.hxx: In constructor ‘Parent::Parent()’: Parent.hxx:25:31: error: invalid use of incomplete type ‘struct OlderSon’ Parent.hxx:8:7: error: forward declaration of ‘struct OlderSon’ ``` I tried in different ways, namely including both .hxx or by forward declaration, but nothing seems to help. I guess it's not a very complex issue, but it is starting to be frustrating. Any ideas? Thanks in advance!
2012/04/17
[ "https://Stackoverflow.com/questions/10189331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1338339/" ]
You are attempting the impossible. You can fix the bug by moving the implementation of `Parent:Parent` to the implementation file, but your code would still be disastrous. Constructing a Parent would require constructing an OlderSon and constructing an OlderSon would require constructing a Parent too (since an OlderSon *is* a Parent). You would have infinite recursion. You can't both have Parent's constructor call OlderSon's *and* vice-versa!
why not you define child pointer to as Parent \* like; ``` class Parent { private : Parent* _os; . . . } ``` Since base class of child is parent.
1,430,726
I find it hard to answer the question below. I just don't know how to use the fact that $$\lim\_{n\to\infty} \frac{a\_n}{n}=2.$$ Maybe with limit arithmetic? > > Let $(a\_n)$ be a sequence, where $$\lim\_{n\to\infty} \frac{a\_n}{n}=2$$ > > > Is it correct that $$\lim\_{n\to\infty}(a\_n-n)=\infty$$ > > > I think it is correct since from limit arithmetic I can get to the conclusion that $$\lim\_{n\to\infty}a\_n=2\lim\_{n\to\infty}n$$ But I just can't prove it. Thanks.
2015/09/11
[ "https://math.stackexchange.com/questions/1430726", "https://math.stackexchange.com", "https://math.stackexchange.com/users/88027/" ]
for $\forall n>N\_{\epsilon}: \mid(\frac{a\_n}{n}-2)\mid<\epsilon$ which equals to $\mid\frac{a\_n-n}{n}-1\mid<\epsilon$, hence $1-\epsilon\leq\frac{a\_n-n}{n}\leq1+\epsilon$. As $n>0$ we find $n-n\times\epsilon\leq{a\_n-n}\leq n+n\times\epsilon$. A posteriori, choose now $\epsilon<\frac{1}{n^3}$ you will have the desired result as $n\times\epsilon<\frac{1}{n^2}<\epsilon\_0$ if $n>\sqrt{\epsilon\_0^{-1}}=N\_{\epsilon\_0}$. Here you are.
$$\because \lim\_{n\to\infty}\frac{a\_n}{n}-1=\lim\_{n\to\infty}\frac{a\_n-n}{n}=1$$ $$\therefore a\_n-n=O(n) \rightarrow \infty (n\to\infty)$$
32,260,538
So i have this script in python. It uses models from django to get some (to be precise: a lot of) data from database. A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code): There are objects of A type. For each A object there are related objects of B type (1 to many). For each B object there are related objects of C type (1 to many). For each C object there is one related object that is particularly interesting for me- let's call it D (1 to 1 relation). For each A object in database(not many) i need to get all B objects related to it and all the D objects related to it to create a summary of the A object. Each summary is a separate worksheet (i am using **openpyxl**). The code i wrote is valid (meaning: it does what i want it to do), but there's problem with garbage collection, so the process gets killed. I have tried not using prefetching, since time is not that much of a concern, but it doesn't really help. Abstract code: ``` a_objects = A.objects.all() wb = Workbook() for a_object in a_objects: ws = wb.create_sheet() ws.title = a.name summary_dictionary = {} << 1 >> b_objects = B.objects.filter(a_object=a_object) for b_object in b_objects: c_objects = C.objects.filter(b_object=b_object) for c_object in c_objects: # Here i put a value in dictionary, or alter it, # depending on whether c_object.d_object has unique fields for current a_object # Key is a tuple of 3 floats (taken from d_object) # Value is array of 3 small integers (between 0 and 100) summary_dictionary = sorted(summary_dictionary.items(), key=operator.itemgetter(0)) for summary_item in summary_dictionary: ws.append([summary_item[0][0], summary_item[0][1], summary_item[0][2], summary_item[1][0], summary_item[1][1], summary_item[1][2], sum(summary_item[1])]) wb.save("someFile.xlsx") ``` While theoretically the whole xlsx file could be huge - possibly over 1GB, if all the d\_objects values were unique, i estimate it to be a lot under 100 MB even at the end of the script. There's about 650 MB free memory in system while script is being executed. There are about 80 A objects and the script is killed after 6 or 7 of them. I used "top" to monitor memory usage and didn't notice any memory being freed, which is weird, because, let's say: 3rd a\_object had 1000 b\_objects related to it and each b\_object had 30 c\_objects related to it and 4th a\_object had only 100 b\_objects related to it and each b\_object had only 2 c\_objects related to it. A lot of memory should be freed some time after <<1>> in 4th iteration, right? My point is that what i thought this program should behave like, is that it would run as long as the following can fit into memory: - the whole summary - a single set of all b\_objects and its c\_objects and its d\_objects for any a\_object in database. What am i missing then?
2015/08/27
[ "https://Stackoverflow.com/questions/32260538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915216/" ]
As of 8 August 2019 (Mongoose Version 5.6.9), the property to set is "rawResult" and not "passRawResult": ``` M.findOneAndUpdate({}, obj, {new: true, upsert: true, rawResult:true}, function(err, d) { if(err) console.log(err); console.log(d); }); ``` Output: ``` { lastErrorObject: { n: 1, updatedExisting: false, upserted: 5d4befa6b44b48c3f2d21c75 }, value: { _id: 5d4befa6b44b48c3f2d21c75, rating: 4, review: 'QQQ' }, ok: 1 } ``` Notice also the result is returned as the second parameter and not the third parameter of the callback. The document can be retrieved by d.value.
I'm afraid Using **FindOneAndUpdate** can't do what you whant because it doesn't has middleware and setter and it mention it the docs: Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied: * defaults * Setters * validators * middleware <http://mongoosejs.com/docs/api.html> search it in the findOneAndUpdate if you want to get the docs before update and the docs after update you can do it this way : ``` Model.findOne({ name: 'borne' }, function (err, doc) { if (doc){ console.log(doc);//this is ur document before update doc.name = 'jason borne'; doc.save(callback); // you can use your own callback to get the udpated doc } }) ``` hope it helps you
3,051,775
This is a follow-up to my question [here](https://math.stackexchange.com/q/3049863/71829). A subset $A$ of a uniform space is said to be bounded if for each entourage $V$, $A$ is a subset of $V^n[F]$ for some natural number $n$ and some finite set $F$. A subset of a metric space is said to be bounded if it is contained in some open ball. Now [this answer](https://math.stackexchange.com/a/3051843/71829) shows that if $U$ is the uniformity induced by a metric $d$, then a set bounded with respect to $U$ is also bounded with respect to $d$, but the converse need not be true. But I’m interested in whether something weaker is true. Suppose that $(X,U)$ is a metrizable uniform space, and $A$ is a subset of $X$ which is bounded with respect to every metric which induces $U$. Then is $A$ bounded with respect to $U$? To put it another way, is the collection of bounded sets with respect to a metrizable uniformity equal to the intersection of the collections of bounded sets with respect to each of the metrics for the uniformity?
2018/12/25
[ "https://math.stackexchange.com/questions/3051775", "https://math.stackexchange.com", "https://math.stackexchange.com/users/71829/" ]
In the context of real functions $$f(x) = \sqrt x + \sqrt{-x}$$ has a graph consisting of only the point $(0,0)$
The graph of the function f = {(x,y)} is a single point. The constant function f:{0} -> {1}, x -> 1, for example. You could conjure up a meaningless monster like f(x) = x/0 if x /= 0; f(0) = 0/0 = 1 or whatever. I don't see any slick answer for a dubious problem. Use the set theory definition of function instead of a naive calculus notion.
62,991,420
I'm having a module-structure in python3.8 like this: ``` module |- __init__.py |- foo.py |- bar.py ``` with ```py # init.py from .foo import Foo from .bar import Bar __all__ = ['Foo', 'Bar', ] ``` I now want to implement a multiplication `foo * bar`. So I'm writing: ```py # foo.py from .bar import Bar class Foo: def __init__(self): self.value = 5 def __mul__(self, other): if not isinstance(other, Bar): raise ValueError('') return self.value * other.number ``` and ```py # bar.py from .foo import Foo class Bar: def __init__(self): self.number = 2 def __mul__(self, other): if not isinstance(other, Foo): raise ValueError('') return other * self ``` This unfortunately doesn't work as expected. Is there a way for type-checking in this case? I know I could import Foo inside of `Bar.__mul__` – but that seems rather untidy to me.
2020/07/20
[ "https://Stackoverflow.com/questions/62991420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6160723/" ]
Try the `execute()` function. It executes the code directly in the `JavaScript` Console. ``` driver.execute("document.getElementsByClassName(' lazy-load-image-background opacity lazy-load-image-loaded')[0].click()") ``` IF that did not work out, There is a second method using the `WebdriverWait()`. ``` from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC WebDriverWait(self.webdriver, 60).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'span[class=" lazy-load-image-background opacity lazy-load-image-loaded"]'))) ```
Please use following xpath "**//img[@src='xxx.jpg']** Before to click you should wait for that element
17,318,914
I have two string arrays in `ar1` and `ar2`, and I am reading the input from file and storing in arrays , `ar1` contains ``` Cat Lam Orange Kam Ramveer None Tue Apple ``` ar2 contains ``` Dog elephant Kam Monday Parrot Queen Ramveer Tuesday Xmas ``` I am trying to sort the arrays in alphabetical order, and i am using `Array.sort()` , but getting the exception ``` Exception in thread "main" java.lang.NullPointerException at java.util.ComparableTimSort.binarySort(ComparableTimSort.java:232) at java.util.ComparableTimSort.sort(ComparableTimSort.java:176) at java.util.ComparableTimSort.sort(ComparableTimSort.java:146) at java.util.Arrays.sort(Arrays.java:472) at CompareArrays.pr1(CompareArrays.java:51) at CompareArrays.main(CompareArrays.java:86) ``` Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds) **Code** ``` File file1= new File("C:\\Users\\Ramveer\\Desktop\\updates\\f1.txt"); File file2=new File("C:\\Users\\Ramveer\\Desktop\\updates\\f2.txt"); Scanner sc1=new Scanner(file1); Scanner sc2=new Scanner(file2); while(sc1.hasNextLine()){ ar1[c1]=sc1.nextLine(); c1++; } while(sc2.hasNextLine()){ ar2[c2]=sc2.nextLine(); c2++; } Arrays.sort(ar1); for(int k=0;k<c1;k++){ System.out.println(ar1[k]);} } ``` Any help would be great. Thanks!
2013/06/26
[ "https://Stackoverflow.com/questions/17318914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2424821/" ]
Use an Arraylist as then you dont have to estimate the size of your array as the ArrayList grows dynamically as you add more strings, your code would go something like this ``` File file1= new File("C:\\Users\\Ramveer\\Desktop\\updates\\f1.txt"); File file2=new File("C:\\Users\\Ramveer\\Desktop\\updates\\f2.txt"); Scanner sc1=new Scanner(file1); Scanner sc2=new Scanner(file2); List<String> list1 = new ArrayList<String>() List<String> list2 = new ArrayList<String>() while(sc1.hasNextLine()) list1.add(sc1.nextLine().toLowerCase()); //edited -- bad approach but would work if case not important while(sc2.hasNextLine()){ list2.add(sc2.nextLine().toLowerCase()); //edited -- bad approach but would work if case not important Collections.sort(list1); Collections.sort(list2); for(String s: list1) System.out.println(s); ``` Or you could do this to implement a case insensitive sort, which would be better then altering the string as you add it to array ``` Collections.sort(list1, new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { String s1 = (String) o1; String s2 = (String) o2; return s1.compareToIgnoreCase(s2); } } ``` Then repeat for list2. But an even better way would be to write a new comparator method as such ``` public class SortIgnoreCase implements Comparator<Object> { public int compare(Object o1, Object o2) { String s1 = (String) o1; String s2 = (String) o2; return s1.compareToIgnoreCase(s2); } } ``` then call `Collections.sort(list1, new SortIgnoreCase());` which is a cleaner way to write the code to sort multiple lists
If your Array don't have null values `Arrays.sort()`works properly. So it is better to use `List` to avoid that kind of a scenario. Then you can convert your arrays to `ArrayList` and use `Collections.sort()` to sort them. ``` String[] str1 = {"Cat","Lam","Orange","Kam","Ramveer","None","Tue","Apple"}; String[] str2 = {"Dog","Elephant","Kam","Monday","Parrot","Queen","Ramveer","Tuesday","Xmas"}; List<String> lst1=Arrays.asList(str1); List<String> lst2=Arrays.asList(str2); Collections.sort(lst1); Collections.sort(lst2); System.out.println(lst1+"\n"+lst2); ```
3,337,787
Question: Suppose $\left( L, \prec \right)$ is a linear ordering such that for every $X \subseteq L, \left( X, \prec \right)$ is isomorphic to an initial segment of $\left( L, \prec \right)$. Show that $\left( L, \prec \right)$ is a well ordering. This is what i have gotten so far. In order to show that $\left( L, \prec \right)$ well ordering I need to show that $\left( L, \prec \right)$ is a linear ordering and every non empty subset of $X$ has a $\prec-$ least member. Since $\left( X, \prec \right) \cong \left( L, \prec \right)$ there is a bijective function $f:X \to L$ such that for any $x, y \in X$, if $x \prec y$ than $f(x)\prec f(y)$. Since $f$ sends $x \in X$ to $f(x) \in L$, there is a subset $W=\{v \in L : f(v) \prec v \}$ which is non-empty. This is what I have gotten and I am stuck after this. Also, is my set $W$ wrong? Help is much appreciated.
2019/08/29
[ "https://math.stackexchange.com/questions/3337787", "https://math.stackexchange.com", "https://math.stackexchange.com/users/546922/" ]
We don't have an isomorphism $f:(X,\prec) \, \to\, (L,\prec)$, only an order-preserving embedding such that the range of $f$ is an *initial segment* of $L$. Now it's very easy: if we show that $L$ has a smallest element, then every initial segment of $L$ will have a smallest element, thus by the embedding being order-preserving, $X$ will have a smallest element, too. To show that $L$ has minimum, simply take any singleton $X:=\{a\}$ with $a\in L$. By the hypothesis, $X$ is isomorphic to an initial segment of $L$, thus $f(a)$, the correspondent of $a$, must be minimal.
First suppose (L, ≺) is a well-ordering. Fix A ⊆ L. We’ll construct an isomorphism from (A, ≺) to an initial segment of (L, ≺). Define f ={ (x,a) ∈ L×A: (pred(L,≺,x),≺) ∼= (pred(A,≺,a),≺)} (i) f is a function: Clearly, f is a relation. To see that it is a function, fix (x, a), (x, b) ∈ f and we’ll show that a = b. Towards a contradiction suppose a $neq$ b. Without loss of generality suppose a ≺ b. Since (x, a) and (x, b) are both in f , we get (pred(L, ≺, x), ≺) ∼= (pred(A, ≺, a), ≺) and (pred(L, ≺, x), ≺) ∼= (pred(A, ≺, b), ≺). Hence (pred(A, ≺, a), ≺) ∼= (pred(A, ≺, b), ≺). But this means that (pred(A, ≺, b), ≺) is a well-ordering that is isomorphic to a proper initial segment of itself. Contradiction. So f is a function. (ii) f is injective: The proof is similar to (i) above. (iii) dom(f ) is an initial segment of (L, ≺): Suppose x ∈ dom(f ) and y ≺ x. We need to show that y ∈ dom(L). Let f(x) = a. Fix an isomorphism h : (pred(L, ≺, x), ≺) → (pred(A, ≺, a), ≺). Note that y ∈ dom(h). Let h(y) = b. It is clear that h pred(L, ≺, y) is an isomorphism from (pred(L, ≺, y), ≺) to (pred(A, ≺, b), ≺). Hence (y, b) ∈ f and so y ∈ dom(f). (iv) range(f) is an initial segment of (A,≺): The proof is similar to (iii) above. (v) f is an isomorphism from (dom(f ), ≺) to (range(f ), ≺): Suppose x ≺ y are in dom(f). Put a = f(x) and b = f(y). Using the definition of f, it follows that (pred(L, ≺, x), ≺) ∼= (pred(A, ≺, a), ≺) and (pred(L, ≺, y), ≺) ∼= (pred(A, ≺, b), ≺). As x ≺ y, it follows that (pred(A, ≺, a), ≺) is isomorphic to an initial segment of (pred(A, ≺, b), ≺). Since no well-ordering can be isomorphic to a proper initial-segment of itself, it follows that a ≺ b. So f is an isomorphism from (dom(f),≺) to (range(f),≺). (vi) range(f) = A: Suppose not. Let a = min(A \ range(f )). Since range(f) is an initial segment of (A, ≺), it follows that range(f ) = pred(A, ≺, a). We claim that dom(f) = L. For suppose not and let x = min(L \ dom(f)). Then dom(f) = pred(L, ≺, x). But this implies that (a, b) ∈ f using (i)-(v) above which is a contradiction. So dom(f) = L. Hence a ∈ dom(f). Now observe that f(a) ≺ a (since range(f ) = pred(A, ≺, a)) and iteratively applying f , we get a ≻ f(a) ≻ f(f(a)) ≻ . . . . But this means that (L, ≺) has an infinite ≺-descending sequence which is impossible by part (a). (i)-(vi) implies that (A,≺) is isomorphic (via f−1) to an initial segment of (L,≺) (namely dom(f)). Next, we show the converse. Suppose for every A ⊆ L, (A, ≺) is isomorphic to an initial segment of (L, ≺). We’ll show that (L, ≺) must be well-ordering. We can assume that L ̸= ∅. Let a ∈ L. Then ({a}, ≺) is isomorphic to an initial segment f (L, ≺). This implies that L has a ≺-least element, say x. Now let A ⊆ L be nonempty and fix an isomorphism f : (A, ≺) → (W, ≺) where W is an initial segment of (L,≺). Note that x ∈ W. Put a = f−1(x). Then a is the ≺-least element of A. It follows that (L, ≺) is a well-ordering.
868,006
I'm looking for a lightweight text editor for web.config files which has colour syntax highlighting (like in visual studio). Any suggestions?
2009/05/15
[ "https://Stackoverflow.com/questions/868006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15613/" ]
You can use [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm). When you work with web.config select XML language to get color syntax highlighting. It looks like [this](http://notepad-plus.sourceforge.net/commun/screenshots/scrsh_lexerXML.gif).
Well obviously you can use any editor (e.g. EditPlus or Notepad++) but if you're looking for a light weight editor client that "knows" what a web.config is have a look at ASPhere <http://blogs.msdn.com/publicsector/archive/2007/12/07/free-utility-web-config-editor-with-a-great-ui.aspx>
37,414,513
I looked on here but I have not been able to find what I want to do. I simply have a onclick event for a button, and I want to increase the date value of a label by any number of days each time I click the button. So lets say that number would be 2 days. If the current value of the label is 5/1/2016 when I click the button it should be 5/3/2016, and if again 5/5/2016 and so on. I can get it to do update once on the first click but not on a second click. Here i my code ``` protected void NDateOn_Click(object sender, EventArgs e) { lblCurrentDate.Text = DateTime.Today.AddDays (2).ToString ("dd"); } ``` I know it has somthing to to with the "Today" but I am not sure what to do from here I appreciate any help in advance.
2016/05/24
[ "https://Stackoverflow.com/questions/37414513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4596738/" ]
The problem is that you are adding 2 days to TODAY's date every time. What you want to do is add 2 to the date already stored there. You would want to do something like this (warning: have not tried compiling this). ``` lblCurrentDate.Text = DateTime.Parse(lblCurrentDate.Text).AddDays(2).ToString("MM/DD/YYYY"); ``` The parameter passed to `ToString()` formats the datetime. You can modify that to get different formats. If you want to only store the days and not the month/year then you might need to do some more work. Hope this helps.
You need maintain the data in viewstate, each button click increment by 2 ``` protected void Button1_Click(object sender, EventArgs e) { if (ViewState["datacount"] == null) { ViewState["datacount"] = 0; } ViewState["datacount"] = ((int)ViewState["datacount"]) + 2; Label1.Text = DateTime.Today.AddDays((int)ViewState["datacount"]).ToString("dd"); } ``` I hope this may helpful for you **Note : viewstate data can maintain in same page only, can maintain in multiple pages**
8,265,699
I'm having trouble bringing back data from my PHP file. I guess I don't really understand the data parameter of this jquery function so I just went off some tutorials. Jquery ``` $.ajax( { url: 'test.php', dataType: 'text', data: {test: '1'}, success: function(data) { window.alert(data); } }) ``` Now from my understanding the `test:` declares the variable used in php and `1` is the value in that variable. But I'm not entirely sure... Here's my PHP ``` $item1 = $_POST['test']; echo $item1; ``` Now it's just supposed to alert that value so I know it is at least returning something but in the alert it's just blank so I'm losing the value somewhere, but where?
2011/11/25
[ "https://Stackoverflow.com/questions/8265699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/800452/" ]
**This is work for me** ajax code ``` <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> <title>Test Page</title> <script> $.ajax( { url: 'test.php', type: 'POST', dataType: 'text', data: {latitude: '7.15588546', longitude: '81.5659984458'}, success: function (response) { alert(response); } }); </script> </head> <body> </body> </html> ``` php code (test.php) ``` <?php $lat = $_REQUEST['latitude']; $lon = $_REQUEST['longitude']; echo 'latitude- '.$lat . ', longitude- ' . $lon; ?> ```
``` just add "type" POST or GET //example $.ajax( { url: 'test.php', type: 'POST', data: {test: '1'}, success: function(data) { window.alert(data); } }) ```
52,555
We all know those breathtaking tales of dragonslayers soloing a winged lizard. We all love them, and we all think they're badass. But today one thought began to bug me - how in the hell adventurers manage to do that? I mean, in games, for example, you just have to club it to death while drinking healing potions. But that approach wouldn't work in real life. What good would it do to wave your toothpick in front of that beast, if he can just smash you with his tail or chomp your head off. Ballistas and the likes don't count - it's not an army, just a lone man seeking adventures, riches and princesses. So, how would **you** approach the dragon? **[UPDATE]** **Adventurer** Capabilities of the adventurer I leave to your imagination, as long as it's possible for normal human being. He can be strong, smart, nimble - whatever you like. **Equipment** Equipment - again, as long as it's possible to make in medieval settings - no objections. Now magic is a tricky one. For the sake of wrecking your brains - no magic >:D **Dragon** Couldn't find a good winged version, so here's a wingless dragon. [![enter image description here](https://i.stack.imgur.com/1MTgW.jpg)](https://i.stack.imgur.com/1MTgW.jpg) His hide is tough, but possible to cut with a strong blow. He can fly(obvsly), relatively fast, and... I gave it some thought, but both fire-breathing and non-breathing dragons seem legit, so whether he has powers of fire is up to you. I'd like to see both solutions anyways. He is extremely aware of the situation, and can not be caught while asleep.
2016/08/23
[ "https://worldbuilding.stackexchange.com/questions/52555", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/16753/" ]
There's actually a surprisingly simple solution here, even if it's without any hint of glory, honour, etc. It wouldn't make for a very good story for the local townspeople, hardly the stuff of legends, but it would be effective and the individual attempting it would have good odds of surviving even a failure. Poison the dragon. Not necessarily quick, despite what you see in all too many movies and books and games with poisons that act in seconds (tranquilizer darts take minutes to hours under normal use to put an animal down), but a good strong dose of the right toxin would be fatal. Perhaps kill a cow, stuff its guts with your poison of choice, and leave it outside the dragon's cave as an "offering". The dragon's not likely to refuse free food, so you simply need to come back in a day or two, finishing the dragon off if necessary, and plunder away! If the dragon only eats live prey, it gets a bit trickier: you'd have to force-feed the poison to your cow, and hope the dragon eats the thing before the cow starts to show symptoms of being poisoned, but it could still be done. If the poison doesn't do the job, it's going to suck (the dragon will be suspicious after this, most likely), but you will be well away from the area and still living to try again. I'm not well-versed in what poisons were available in the medieval era, but I'm confident that something vicious and very deadly existed and could be found. Some plant that could have its leaves brewed into a toxic tea, or a very poisonous mushroom, or just a colossal overdose of a sleeping potion, or some other lethal poison entirely.
Overwhelming military might, you take each of the dragon's strengths and turn them against him. Flight ------ This is easy to overcome, you get your dragon in a cave! somewhere low so he can't take out Strength -------- The dragon is stronger than you, that means you need to either stay out of reach or get within it's reach - if you rush it, avoid the claws and fangs and get within it's reach you should be able to stab it from where it can't reach you. Speed/Fire ---------- Ok, so you don't want to get too close to a fire breathing quick dragon, I suppose I can see where you're coming from... say hello to my [lil friend](https://en.wikipedia.org/wiki/Ballista).. Set up your ballista (more than one would be ideal!) at the mouth of the cave and fire as soon as you see him enter the passage that he can't fly in. He won't be faster than a ballista and he'll be too far away for the his fire to be in effect, you can even duck to the side of the cave and he won't be able to get you.
2,244,084
> > Let $ABC$ be a triangle with $AB=AC$ and $\angle BAC=90^{\circ}$. Let $P,Q$ be points on $AB, AC$ respectively such that $PQ=AB$, and let $O$ be the center of the circle passing through $P,Q$ and tangent to $BC$. Show that $OA\parallel BC$. > > > It would be enough to show that $A,O,P,Q$ are concyclic. It seems like $\triangle OPQ\sim\triangle ABC$, which would imply the concyclic points, but I'm unsure how to do this.
2017/04/20
[ "https://math.stackexchange.com/questions/2244084", "https://math.stackexchange.com", "https://math.stackexchange.com/users/304635/" ]
Let the circle through points $P, \,Q$ and tangent to the segment $BC$ be denoted by $k$ and let the point of tangency of $k$ and $BC$ be denoted by $T$. Let line $PQ$ intersect line $BC$ at point $E$ and let us assume, without loss of generality, that point $E$ is located so that $B$ is between $E$ and $C$, while $P$ is between $E$ and $Q$. Then by the tangent-secant theorem (or whatever you call that statement) $$ET^2 = EP \cdot EQ$$ Let the line through point $P$ perpendicular to $AB$ and the line through point $W$ perpendicular to $AC$ intersect at point $R$. Then $APRQ$ is a rectangle and $PQ = AR = AB = AC$. Denote by $T^\*$ the orthogonal projection of $R$ onto the edge $BC$. **Claim.** *Point $T$ coincides with point $T^\*$, i.e. $T\equiv T^\*$ meaning that the circle $k$ touches edge $BC$ at point $T^\*$* *Proof:* Draw the circle $k\_A$ centered at $A$ and of radius $AB = AC = AR$. Then $k\_A$ passes through the points $B, \, R$ and $C$. If you denote say $\angle \, BAR = \alpha$, and observe that the quads $BPT^\*R$ and $CQT^\*R$ are cyclic, you can chase a bunch of angles and find that $$\angle \, PQT^\* = \frac{\alpha}{2} = \angle \, PT^\*B$$ (in fact, one can even show that $T^\*$ is the incenter of triangle $PQR \, $) **Edit.** $\angle \, PQT^\* = \frac{\alpha}{2} = \angle \, PT^\*B$ *Proof of edit:* First, angle $\angle \, RAB = \alpha$ is central for circle $k\_A$. Hence, $\angle \, RCB = \frac{1}{2} \, \angle \, RAB = \frac{1}{2} \alpha$. By cyclicity of $CQT^\*R$ $$\angle \, RQT^\* = \angle \, RCT^\* = \angle \, RCB = \frac{1}{2} \alpha$$ However, $APRQ$ is a rectangle, so $\angle \, RQP = \angle \, RAP = \angle \, RAB = \alpha$. Hence $$\angle \, PQT^\* = \angle \, RQP - \angle \, RQT^\* = \alpha - \frac{1}{2} \alpha = \frac{1}{2} \alpha$$ Second, $AR = AB$ so $ABR$ is an isosceles triangle, so $$\angle \, ABR = \angle \, ARB = 90^{\circ} - \frac{1}{2} \alpha$$ and since $RP$ is orthogonal to $AB$, $$\angle \, PRB = 90^{\circ} - \angle \, ABR = \frac{1}{2} \alpha$$ By cyclicity of $BPT^\*R$ $$\angle \, PT^\*B = \angle \, PRB = \frac{1}{2} \alpha$$ Thus $\angle \, PQT^\* = \frac{\alpha}{2} = \angle \, PT^\*B$. The latter equality of angles yields, for example, that triangles $EPT^\*$ and $ET^\*Q$ are similar. Therefore, $$\frac{EP}{ET^\*} = \frac{ET^\*}{EQ}$$ which is equivalent to $$ET^{\*2} = EP \cdot EQ = ET^2$$ meaning that $ET^\* = ET$. Since, by construction, both points $T$ and $T^\*$ lie on the line $BC$ and are on the same side of point $B$, one can conclude that $T^\* \equiv T$. **Concluding the proof.** Let Let $M = PQ \cap AR$. Then $M$ is the midpoint of both diagonal segments $PQ$ and $AR$ of rectangle $APRQ$. Since the point of tangency $T$ of the circle $k$ and the segment $BC$ is the orthogonal projection of point $R$, the center of $k$ lies on the intersection of the line $RT$ and the orthogonal bisector of diagonal $PQ$ through $M$. Again, if you chase some angles, you get $$\angle \, ORM = \angle \, TRA = 45^{\circ} - \alpha$$ and $$\angle \, AMO = 90^{\circ} - \angle \, AMQ = 90^{\circ} - 2\,\alpha$$ Therefore, $$\angle \, ROM = \angle \, AMO - \angle \, ORM = 90^{\circ}- 2\,\alpha - 45 + \alpha = 45^{\circ} - \alpha = \angle \, ORM$$ which means that triangle $ORM$ is isosceles with $MO = MR$ which means that $$MO = MR = MA$$ Consequently, triangle $AOR$ is right-angled with $\angle \, AOR = 90^{\circ}$ so line $AO$ is orthogonal to line $RT$. However, $BC$ is also orthogonal to $BC$ (the claim). Thus $AO$ is parallel to $BC$.
This isn't a proof, because I'm starting with the assumption $OA \parallel BC$. Per questioner's request, writing this up as an answer. Note that $O$ can't be equal to $A$ because $OA$ wouldn't be a line segment. Let $D$ be the midpoint of $BC$. The circle won't be tangent to $BC$ at $D$. Let's say it is tangent at $E$. Then $OE$ = $AD$ and $OE \parallel AD$. $AD = \sqrt{2}/2 \* AB = OE$. Thus radius is $r=\sqrt{2}/2 \* AB$. Since $P$ and $Q$ lie on circle $OP = OQ = r$. And it's given that $PQ = AB$. So $\triangle OPQ$ has two sides equal to $r$ and one side equal to $\sqrt{2}r$. Therefore it is a right triangle (by Pythagoras) with equal sides, so $\,\triangle OPQ \sim \triangle ABC$. Further $\triangle OPQ = \triangle ABD = \triangle ACD$.
4,203,211
Is there a replacement technology for TAPI that supports third-party call control (3pcc)? I want to provide the following 3pcc functionalities in an application: 1. Outgoing call: * User clicks at a button in the application. * The user's phone goes off hook, and the callee's phone rings. * The callee's phone shows the phone number of the callee, not the phone number used for the application. * When the callee picks up the phone, the connection is established. 2. Incoming call: * When user's phone rings, the caller's number and the called number are sent to the application. * The application evaluates the numbers and shows e.g. a customer record. In the past, I would have done this with TAPI, but it seems that Microsoft does not actively develop TAPI any more (even though TAPI is supported with all current Windows versions, up to Windows 7). Therefore, I am searching for a technology that is more likely supported in the future by the majority of telephony system providers. I am aware of CSTA, which could be used to do this, but this also is a pretty old technology and not very widespread (it has 100 times less Google hits than TAPI, for example). I am also aware of SIP, which does not have direct support for 3pcc features, but there are ways to work around this: * For outgoing calls: use application's SIP endpoint to connect to the two phones first, then connect them by making a kind of "conference call". * For incoming calls: use SUBSCRIBE and NOTIFY and dialog event package. Problem is that the procedure for outgoing calls is very clumsy, and the called phone would not display the correct phone number (i.e. the caller's number) when ringing. Furthermore, SIP is not a single standard, but a collection of many different RFCs, and it seems that telephony system manufacturers only implement parts of those RFCs, and there usually is no good documentation which parts are implemented. So, my question is: is there any other telephony integration standard that supports third-party call control, and that can be considered as a widely supported standard in the foreseeable future?
2010/11/17
[ "https://Stackoverflow.com/questions/4203211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'd suggest you consider CSTA3. ECMA CSTA3 is a comprehensive standard for 3rd party telephony call control far superior to TAPI in detail and implemented by several vendors. A web service definition exists for CSTA. See [ECMA CSTA 3](http://www.ecma-international.org/activities/Communications/TG11/cstaIII.htm) I can highly recommend the standard but would suggest you carefully consider if the target vendor supports the CSTA standard as you require.
The answer to the OP is yes. A couple years ago I was trying to do TAPI work and had all of the same issues as everyone else. Rather than using local hardware and drivers, I found cloud services which do everything requested in the OP. I won't mention a specific service unless someone PM's me. But my recommendation is to go off the standard path, and stop beating your head against the TAPI wall. HTH
7,180,185
I am new to Linq-to-SQL. I want to retrieve the identity value from Linq-to-SQL while using `DBContext.SubmitChanges()`.
2011/08/24
[ "https://Stackoverflow.com/questions/7180185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674652/" ]
It should automatically update your record. Something like this: ``` Customer cust = new Customer(); cust.Company = "blah"; context.Customers.Add( cust ); context.SubmitChanges(); int NewPk = cust.Pk; ```
After you have called `SubmitChanges()` you can access the id field of your object to retrieve the ID.
19,401,966
I have a problem with parsing results of google images search. I've tried to do it with `selenium webdriver`. It returned me 100 results, but it was rather slow. I decided to request a page with `requests` module and it returned me only 20 results. How can I get the same 100 results? Is there any way to paginate or something? this is `selenium` code: ``` _url = r'imgurl=([^&]+)&' for search_url in lines: driver.get(normalize_search_url(search_url)) images = driver.find_elements(By.XPATH, u"//div[@class='rg_di']") print "{0} results for {1}".format(len(images), ' '.join(driver.title.split(' ')[:-3])) with open('urls/{0}.txt'.format(search_url.strip().replace('\t', '_')), 'ab') as f: for image in images: url = image.find_element(By.TAG_NAME, u"a") u = re.findall(_url, url.get_attribute("href")) for item in u: f.write(item) f.write('\n') ``` and here is `requests` code: ``` _url = r'imgurl=([^&]+)&' for search_url in lines[:10]: print normalize_search_url(search_url) links = 0 request = requests.get(normalize_search_url(search_url)) soup = BeautifulSoup(request.text) file = 'cars2/{0}.txt'.format(search_url.strip().replace(' ', '_')) with open(file, 'ab') as f: for image in soup.find_all('a'): if 'imgurl' in image.get('href'): links += 1 u = re.findall(_url, image.get("href")) for item in u: f.write(item) f.write('\n') print item print "{0} links extracted for {1}".format(links, ' '.join(soup.title.name.split(' ')[:-3])) ```
2013/10/16
[ "https://Stackoverflow.com/questions/19401966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1776946/" ]
I've never tried doing that with selenium, but have you tried using Google's search engine API? It might be useful for you: <https://developers.google.com/products/#google-search> Also, their restriction for the API is 100 requests per day, so I don't think you'll get more than 100
You can scrape Google images by using the `beautifulsoup` and `requests` libraries, `selenium` is not required. To get a batch of 100 images you can use in query param. `"ijn=0"` -> 100 images, `"ijn=1"` -> 200 images. In order to scrape the full-res image URL with `requests` and `beautifulsoup` you need to scrape data from the page source code via `regex`. Find all `<script>` tags: ```py soup.select('script') ``` Match images data via `regex` from the `<script>` tags: ```py matched_images_data = ''.join(re.findall(r"AF_initDataCallback\(([^<]+)\);", str(all_script_tags))) ``` Match desired images (full res size) via `regex`: ```py # https://kodlogs.com/34776/json-decoder-jsondecodeerror-expecting-property-name-enclosed-in-double-quotes # if you try to json.loads() without json.dumps() it will throw an error: # "Expecting property name enclosed in double quotes" matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) matched_google_full_resolution_images = re.findall(r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", matched_images_data_json) ``` Extract and decode them using `bytes()` and `decode()`: ```py for fixed_full_res_image in matched_google_full_resolution_images: original_size_img_not_fixed = bytes(fixed_full_res_image, 'ascii').decode('unicode-escape') original_size_img = bytes(original_size_img_not_fixed, 'ascii').decode('unicode-escape') ``` --- Code and [full example in the online IDE](https://replit.com/@DimitryZub1/Scrape-and-Download-Google-Images-with-Python#bs4_original_images.py) that also downloads images: ```py import requests, lxml, re, json from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } params = { "q": "pexels cat", "tbm": "isch", "hl": "en", "ijn": "0", } html = requests.get("https://www.google.com/search", params=params, headers=headers) soup = BeautifulSoup(html.text, 'lxml') def get_images_data(): print('\nGoogle Images Metadata:') for google_image in soup.select('.isv-r.PNCib.MSM1fd.BUooTd'): title = google_image.select_one('.VFACy.kGQAp.sMi44c.lNHeqe.WGvvNb')['title'] source = google_image.select_one('.fxgdke').text link = google_image.select_one('.VFACy.kGQAp.sMi44c.lNHeqe.WGvvNb')['href'] print(f'{title}\n{source}\n{link}\n') # this steps could be refactored to a more compact all_script_tags = soup.select('script') # # https://regex101.com/r/48UZhY/4 matched_images_data = ''.join(re.findall(r"AF_initDataCallback\(([^<]+)\);", str(all_script_tags))) # https://kodlogs.com/34776/json-decoder-jsondecodeerror-expecting-property-name-enclosed-in-double-quotes # if you try to json.loads() without json.dumps it will throw an error: # "Expecting property name enclosed in double quotes" matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) # https://regex101.com/r/pdZOnW/3 matched_google_image_data = re.findall(r'\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",', matched_images_data_json) # https://regex101.com/r/NnRg27/1 matched_google_images_thumbnails = ', '.join( re.findall(r'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]', str(matched_google_image_data))).split(', ') print('Google Image Thumbnails:') # in order for fixed_google_image_thumbnail in matched_google_images_thumbnails: # https://stackoverflow.com/a/4004439/15164646 comment by Frédéric Hamidi google_image_thumbnail_not_fixed = bytes(fixed_google_image_thumbnail, 'ascii').decode('unicode-escape') # after first decoding, Unicode characters are still present. After the second iteration, they were decoded. google_image_thumbnail = bytes(google_image_thumbnail_not_fixed, 'ascii').decode('unicode-escape') print(google_image_thumbnail) # removing previously matched thumbnails for easier full resolution image matches. removed_matched_google_images_thumbnails = re.sub( r'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]', '', str(matched_google_image_data)) # https://regex101.com/r/fXjfb1/4 # https://stackoverflow.com/a/19821774/15164646 matched_google_full_resolution_images = re.findall(r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", removed_matched_google_images_thumbnails) print('\nDownloading Google Full Resolution Images:') # in order for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images): # https://stackoverflow.com/a/4004439/15164646 comment by Frédéric Hamidi original_size_img_not_fixed = bytes(fixed_full_res_image, 'ascii').decode('unicode-escape') original_size_img = bytes(original_size_img_not_fixed, 'ascii').decode('unicode-escape') print(original_size_img) get_images_data() ------------- ''' Google Images Metadata: 9,000+ Best Cat Photos · 100% Free Download · Pexels Stock Photos pexels.com https://www.pexels.com/search/cat/ ... Google Image Thumbnails: https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR2cZsuRkkLWXOIsl9BZzbeaCcI0qav7nenDvvqi-YSm4nVJZYyljRsJZv6N5vS8hMNU_w&usqp=CAU ... Full Resolution Images: https://images.pexels.com/photos/1170986/pexels-photo-1170986.jpeg?cs=srgb&dl=pexels-evg-culture-1170986.jpg&fm=jpg https://images.pexels.com/photos/3777622/pexels-photo-3777622.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500 ... ''' ``` --- Alternatively, you can achieve the same thing by using [Google Images](https://dev.to/dimitryzub/how-to-reduce-chance-being-blocked-while-web-scraping-search-engines-1o46) API from SerpApi. It's a paid API with a free plan. The difference is that you don't have to deal with `regex`, bypass blocks from Google, and maintain it over time if something crashes. Instead, you only need to iterate over structured JSON and get the data you want. Code to integrate: ```py import os, json # json for pretty output from serpapi import GoogleSearch def get_google_images(): params = { "api_key": os.getenv("API_KEY"), "engine": "google", "q": "pexels cat", "tbm": "isch" } search = GoogleSearch(params) results = search.get_dict() print(json.dumps(results['images_results'], indent=2, ensure_ascii=False)) get_google_images() --------------- ''' [ ... # other images { "position": 100, # img number "thumbnail": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRR1FCGhFsr_qZoxPvQBDjVn17e_8bA5PB8mg&usqp=CAU", "source": "pexels.com", "title": "Close-up of Cat · Free Stock Photo", "link": "https://www.pexels.com/photo/close-up-of-cat-320014/", "original": "https://images.pexels.com/photos/2612982/pexels-photo-2612982.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500", "is_product": false } ] ''' ``` P.S - I wrote a more in-depth blog post about how to scrape [Google Images](https://dev.to/dimitryzub/scrape-google-images-with-python-1ee2), and [how to reduce the chance of being blocked while web scraping search engines](https://dev.to/dimitryzub/how-to-reduce-chance-being-blocked-while-web-scraping-search-engines-1o46). > > Disclaimer, I work for SerpApi. > > >
1,221
Today and since I have joined islam.se, I have seen that almost all of the decisions made by the moderators against other member and me, are too much strict. Today, during a chat thread, I was blocked for multiple times for just sharing my opinion about the Shias, "which is even accepted by the Shias themselves" there is nothing dos-respectful or non-civil in it, but he kept on blocking me for this. Also, he has blocked a user Ali, for just sharing a video "videos are also just opinions about anyone else". The videos of all kinds are viable everywhere, anyone has right to see, agree or dis-agree with them, it’s not like it was porn or something that the user was blocked. I personally think goldPseudo needs to be removed from islam.se moderator-ship. As there are many other Meta complaints about him by many other members. i am going to present anger of other members as well, so that this case can be seriously considered and a decision can be made against him. Because his moderator-ship is destroying the actual purpose of site. **I am not sure but even the comments direct to him, he deletes them right away. i wrote a comment against his reply, and he deleted it, without any notification.**
2014/07/05
[ "https://islam.meta.stackexchange.com/questions/1221", "https://islam.meta.stackexchange.com", "https://islam.meta.stackexchange.com/users/58/" ]
There's nothing wrong with discussing the views of any sect so long as you don't pass negative *immature* judgements on them. Keep in mind, any fair critique of any particular sect (or any group of people) is better to take place in presence of their representatives so that they have the opportunity to present their views and defenses, and make sure you even understand their beliefs and practices correctly before going on attacking them! Therefore, public judgements, denunciations and condemnations against large groups of people when done in absence of their representatives can be open to charges of defamation, backbiting and hate-mongering. I think this is an ill practice that goldPseudo is trying to prevent from becoming a norm in this site. But admittedly this took me, too, a little time to understand this wise rationale behind his perceived 'strict' moderation.
I had the experience of goldpseudo deleting an answer in which I presented some relevant scholarly references which (I assume) he considered irrelevant or did not like - perhaps because they were more modernist and liberal in tone. So I posted another answer challenging his deletion - which has not been deleted yet! Postcript - my challenge has been deleted by goldpseudo. I guess he does not consider the opinion of al-Ghazali, one of the most prominent and influential jurists and mystics of Sunni Islam, d. 505 AH, to be relevant to the issue of the permissibility of music in Islam.
15,020,622
I know that ``` Application.ExecutablePath ``` can get the installation folder. But how can I get the location of publishing folder that I put in "PUBLISH" tab of my project? say.. (of course this will not work) ``` Application.PublishingPath ``` I am just trying to get the manifest file there so that I could know the current version number of the application inside the publishing folder.
2013/02/22
[ "https://Stackoverflow.com/questions/15020622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862513/" ]
you should just manually store the publishing path to a variable..
Simply: ``` ApplicationDeployment.CurrentDeployment.ActivationUri ```
18,226
I understand that the public key does not expose the private key. That is not the question. The question is: Given a EC public key, can a different, but *plausible* and *functional* private key be derived to match the public key? In other words: In basic arithmetic, if you know `a x b = c`, and you know any two variables, then you can calculate the third. But in ECC, we have a public key `q`, a well known point `G`, and a private number `d`. The public key is derived from the private key by [ECPoint q = CreateBasePointMultiplier().Multiply(parameters.G, d);](https://github.com/bcgit/bc-csharp/blob/master/crypto/src/crypto/generators/ECKeyPairGenerator.cs#L122). I have to assume `Multiply` is a special form of multiplication, such that knowing `q` and `G` do not result in knowing `d`. Maybe it's essentially looping over a finite field many times over, or something like that. But could a *different* private key be selected that would result in the same public key? In other words, specifically, let Alice and Bob both have ECDH keypairs, and exchange public keys. They each remember the other's public key for later authentication. When somebody claims to Alice "I am Bob, and here's my public key," then Alice confirms the public key matches what she remembers, and she challenges him, "Ok, prove it. Here is my (Alice) public key. Use it to derive our shared secret, and HMAC sign the following challenge. Send me back the result as a challenge response. If you can do that, you must know your private key corresponding to the exposed public key." Could Eve capture Bob's public key, then derive some different private key to correspond to it, and then impersonate Bob by saying "I am Bob, and here's my public key." Even though Eve doesn't have Bob's private key, she's able to produce some *other* private key that's compatible with Bob's public key?
2014/07/19
[ "https://crypto.stackexchange.com/questions/18226", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/12656/" ]
> > Given a EC public key, can a different, but plausible and functional private key be derived to match the public key? > > > No, a public key will correspond to only one private key (with one minor exception, which I will explain below). With Elliptic Curve systems, the private key is an integer $d$ between 1 and $q$ (the order the generator point $G$), and the public key is most commonly the point $dG$, which defined to be $\underbrace{G + G + ... + G}\_\text{d copies}$. Now, the order of the generator has this property: all multiples less than the order will be distinct. That is, if we consider the sequence of points $G, 2G, 3G, 4G, ..., (q-1)G, qG$, there will be no duplicates in that sequence. What this means is that, since a public key occurs somewhere in the sequence, that is the only occurance; there won't be another private key (less than $q$) that will also yield that public key. Now, the minor exception I mentioned: some elliptic curve systems don't use the full point $dG$ as the public key, sometimes they use only the x-coordinate as the public key. It turns out, in that case, there is a second private key value that would yield the same public key; the value $q-d$. There are no others, and that second key turns out to be of no use to an attacker; recovering that value is no easier than recovering the original value of $d$.
I obviously don't understand the mathematics behind ECC, but I am quite certain that the mentioned `Multiply` is not as simple as regular multiplication, nor as simple as wrapping around a finite field many times over. Because: When Alice and Bob exchange ECDH public keys, and then they each do `DeriveKeyMaterial()` or `CalculateAgreement()`, the result is supposed to be a *shared secret* that is known to Alice and Bob, and *not known* by any evesdropper. If it were possible for Eve to derive *any* private key (even different from Bob's) that were plausible and functional with Bob's public key, then Eve would be able to derive the same result from `DeriveKeyMaterial()` or `CalculateAgreement()`, which means Eve is able to discover Alice & Bob's shared secret, which is assumed to be implausible. If this property did not hold, then ECDH would be completely broken.
47,334,139
I'm currently trying to make Controlling an RGB LED With an Android Smartphone Using Arduino and Bluetooth Module. As in below link tutorial. > > <http://www.instructables.com/id/Controlling-an-RGB-LED-With-an-Android-Smartphone-/> > > > I'm using Arduino Uno. I made as in tutorial and code and upload to Arduino then It's Show as below Error Messages and cannot upload to Arduino. ``` avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch System wide configuration file is "/Applications/Arduino.app/ Contents/Java/hardware/tools/avr/etc/avrdude.conf" User configuration file is "/Users/kyawzinwai/.avrduderc" User configuration file does not exist or is not a regular file, skipping Using Port : /dev/cu.usbmodem1421 Using Programmer : arduino Overriding Baud Rate : 115200 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00 avrdude done. Thank you. Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions. ```
2017/11/16
[ "https://Stackoverflow.com/questions/47334139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7130882/" ]
I found the "programmer is not responding" error when I tried to flash my attiny85. I got rid of the annoying error when I switched to Arduino IDE 1.6.4 and chose the Arduino Genuino/ Uno as board. That's the important part and a common error: don't switch to "Arduino as ISP" mode when you upload the example sketch named "ArduinoISP". And another thing to remember is to use the right capacitor. I first used a 1000mF cap and thought it could work but I was wrong. Use something in the 10mf - 100mF range. Thanks for your attention, Good luck
Make sure RESET and GND pins of Arduino are not
14,621,953
I have a composite (X) like this: ``` <composite:interface> <composite:attribute name="textValue" /> <composite:attribute name="textValueChangeListner" method-signature="void valueChanged(javax.faces.event.ValueChangeEvent)" /> ``` ``` <composite:implementation> <ice:inputText value="#{cc.attrs.textValue}" valueChangeListener="#{cc.attrs.textValueChangeListner}"/> ``` In the JSF page I have something like: ``` <X:iText textValue="#{cardBean.getCardValue}" textValueChangeListner="#{cardHandler.cardValueChanged}" /> ``` The above code works fine. But it does not work when NO "textValueChangeListner" is passed to the composite from JFace page; i.e: ``` <X:iText textValue="#{cardBean.getCardValue}" /> ``` Error I got: [javax.enterprise.resource.webcontainer.jsf.lifecycle] Unable to resolve composite component from using page using EL expression '#{cc.attrs.textValueChangeListner}': javax.faces.FacesException: Unable to resolve composite component from using page using EL expression '#{cc.attrs.textValueChangeListner}' In my scenario it is necessary that page developer may or may not supply the "textValueChangeListner" to the composite component. How can I achieve that ?
2013/01/31
[ "https://Stackoverflow.com/questions/14621953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2028132/" ]
Use `whereHas` to filter by any relationship. It won't join the relation but it will filter the current model by a related property. Also look into local scopes to help with situations like this <https://laravel.com/docs/5.3/eloquent#local-scopes> Your example would be: ``` Restaurant::whereHas('facilities', function($query) { return $query->where('wifi', true); })->get(); Restaurant::whereHas('cuisines', function($query) use ($cuisineId) { return $query->where('id', $cuisineId); })->get(); ``` To achieve the same thing with local scopes: ``` class Restaurant extends Eloquent { // Relations here public function scopeHasWifi($query) { return $query->whereHas('facilities', function($query) { return $query->where('wifi', true); }); } public function scopeHasCuisine($query, $cuisineId) { return $query->whereHas('cuisines', function($query) use ($cuisineId) { return $query->where('id', $cuisineId); }); } } ``` For local scopes you DO NOT want to define them as static methods on your model as this creates a new instance of the query builder and would prevent you from chaining the methods. Using a local scope will injects and returns the current instance of the query builder so you can chain as many scopes as you want like: ``` Restaurant::hasWifi()->hasCuisine(6)->get(); ``` Local Scopes are defined with the prefix `scope` in the method name and called without `scope` in the method name as in the example abover.
Do you absolutely have to load it from the Restaurant model? In order to solve the problem, I usually approach it inversely. ``` Facilities::with('restaurant')->where('wifi' ,'=', 0)->get(); ``` This will get all the restaurant facilities that match your conditions, and eager load the restaurant. You can chain more conditions and count the total like this.. ``` Facilities::with('restaurant') ->where('wifi' ,'=', 1) ->where('parking','=', 1) ->count(); ``` This will work with cuisine as well ``` Cuisine::with('restaurant')->where('id','=',1)->get(); ``` This grabs the cuisine object with the id of 1 eager loaded with all the restaurants that have this cuisine
1,667,420
I assumed joinable would indicate this, however, it does not seem to be the case. In a worker class, I was trying to indicate that it was still processing through a predicate: ``` bool isRunning(){return thread_->joinable();} ``` Wouldn't a thread that has exited not be joinable? What am I missing... what is the meaning of boost thread::joinable?
2009/11/03
[ "https://Stackoverflow.com/questions/1667420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
Use [thread::timed\_join()](http://www.boost.org/doc/libs/1_35_0/doc/html/thread/thread_management.html#thread.thread_management.thread.timed_join) with a minimal timeout. It will return false if the thread is still running. Sample code: ``` thread_->timed_join(boost::posix_time::seconds(0)); ```
I am using boost 1.54, by which stage timed\_join() is being deprecated. Depending upon your usage, you could use joinable() which works perfectly for my purposes, or alternatively you could use try\_join\_for() or try\_join\_until(), see: <http://www.boost.org/doc/libs/1_54_0/doc/html/thread/thread_management.html>
53,602,320
How can I architect code to run a pyqt GUI multiple times consecutively in a process? (pyqtgraph specifically, if that is relevant) The context ----------- A python script that performs long running data capture on measurement equipment (a big for loop). During each capture iteration a new GUI appear and displays live data from the measurement equipment to the user, while the main capture code is running. I'd like to do something like this: ``` for setting in settings: measurement_equipment.start(setting) gui = LiveDataStreamGUI(measurement_equipment) gui.display() measurement_equipment.capture_data(300) #may take hours gui.close() ``` The main issue -------------- I'd like the data capture code to be the main thread. However pyqt doesn't seems to allow this architecture, as its `app.exec_()` is a blocking call, allowing a GUI to be created only once per process (e.g., in `gui.display()` above).
2018/12/03
[ "https://Stackoverflow.com/questions/53602320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50135/" ]
An application is an executable process that runs on one or more foreground threads each of which can also start background threads to perform parallel operations or operations without blocking the calling thread. An application will terminate after all foreground threads have ended, therefore, you need at least one foreground thread which in your case is created when you call the `app.exec_()` statement. In a GUI application, this is the UI thread where you should create and display the main window and any other UI widget. Qt will automatically terminate your application process when all widgets are closed. IMHO, you should try to follow the normal flow described above as much as possible, the workflow could be as follows: > > Start Application > Create main window > Start a background thread for each calculation > Send progress to UI thread > Show results in a window after each calculation is finished > Close all windows > End application > > > Also, you should use `ThreadPool` to make sure you don't run out of resources. Here is a complete example: ``` import sys import time import PyQt5 from PyQt5 import QtCore, QtWidgets from PyQt5.QtCore import QRunnable, pyqtSignal, QObject from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QDialog class CaptureDataTaskStatus(QObject): progress = pyqtSignal(int, int) # This signal is used to report progress to the UI thread. captureDataFinished = pyqtSignal(dict) # Assuming your result is a dict, this can be a class, a number, etc.. class CaptureDataTask(QRunnable): def __init__(self, num_measurements): super().__init__() self.num_measurements = num_measurements self.status = CaptureDataTaskStatus() def run(self): for i in range(0, self.num_measurements): # Report progress self.status.progress.emit(i + 1, self.num_measurements) # Make your equipment measurement here time.sleep(0.1) # Wait for some time to mimic a long action # At the end you will have a result, for example result = {'a': 1, 'b': 2, 'c': 3} # Send it to the UI thread self.status.captureDataFinished.emit(result) class ResultWindow(QWidget): def __init__(self, result): super().__init__() # Display your result using widgets... self.result = result # For this example I will just print the dict values to the console print('a: {}'.format(result['a'])) print('b: {}'.format(result['b'])) print('c: {}'.format(result['c'])) class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.result_windows = [] self.thread_pool = QtCore.QThreadPool().globalInstance() # Change the following to suit your needs (I just put 1 here so you can see each task opening a window while the others are still running) self.thread_pool.setMaxThreadCount(1) # You could also start by clicking a button, menu, etc.. self.start_capturing_data() def start_capturing_data(self): # Here you start data capture tasks as needed (I just start 3 as an example) for setting in range(0, 3): capture_data_task = CaptureDataTask(300) capture_data_task.status.progress.connect(self.capture_data_progress) capture_data_task.status.captureDataFinished.connect(self.capture_data_finished) self.thread_pool.globalInstance().start(capture_data_task) def capture_data_progress(self, current, total): # Update progress bar, label etc... for this example I will just print them to the console print('Current: {}'.format(current)) print('Total: {}'.format(total)) def capture_data_finished(self, result): result_window = ResultWindow(result) self.result_windows.append(result_window) result_window.show() class App(QApplication): """Main application wrapper, loads and shows the main window""" def __init__(self, sys_argv): super().__init__(sys_argv) self.main_window = MainWindow() self.main_window.show() if __name__ == '__main__': app = App(sys.argv) sys.exit(app.exec_()) ```
If you want your GUI to keep updating in **realtime** and to not be freezed, you have **two main ways** to do it: 1. **Refresh the GUI from time to time** calling `QApplication.processEvents()` inside your time consuming function. 2. **Create a separate thread** (I mean, `QThread`) where you run your time consuming function My personal preference is to go for the latter way. [Here](https://nikolak.com/pyqt-threading-tutorial/) is a good tutorial for getting started on how to do multi-threading in Qt. Having a look at your code: ``` ... gui.display() measurement_equipment.capture_data(300) #may take hours gui.close() ... ``` it seems you are calling `app.exec_` inside `gui.display`. Its very likely you will have to decouple both functions and call `app.exec_` outside of `gui.display` and after calling `capture_data`. You will also have to connect the `finished` signal of the new thread to `gui.close`. It will be something like this: ``` ... gui.display() # dont call app.exec_ here thread = QThread.create(measurement_equipment.capture_data, 300) thread.finished.connect(gui.close) app.exec_() ... ``` I hope this can help you and to not be late!!
28,179,413
Cannot figure out what this regex pattern does. Searches in google just return generic regex uses. Help please!!! ``` const string HTML_TAG_PATTERN = "<.*?>"; return Regex.Replace(inputString, HTML_TAG_PATTERN, string.Empty); ```
2015/01/27
[ "https://Stackoverflow.com/questions/28179413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2631233/" ]
The above replaces all HTML style tags with an empty space. It matches as follows: ``` < - Match the < character literally .*? - Match any single character that is not a line break character between zero and unlimited times, as few times as possible, expanding as needed > - Match the > character literally ``` The replacement call says: replace all matches of `HTML_TAG_PATTERN` in `inputString` with `string.Empty`.
Try running it through a regex tester (any of a dozen of which canbe found via a search) * Seeing as the angle brackets (`<` and `>`) aren't typical Regex syntax, those symbols get matched exactly. * The `.` means "any character except newline" * the `*` means "zero or more of the preceding element" * the `?` means "zero or one of the preceding element" (**EDIT**: also "as few as possible" since it'll avoid matching this element if it can) In all, this will match against any text in angle brackets - it's probably looking for HTML/XML tags.
58,783,730
In Thymeleaf, to trigger the index.html page (present in templates folder of resources) providing a new @RequestMapping method in the application's Main class does not work (outputs the string instead of rendering the HTML page) but creating a separate @Controller class with same @RequestMapping method is triggering the desired UI. Method 1 -------- The @RequestMapping method in Main class ``` package com.personal.boot.spring.helloworld; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class HelloworldApplication { public static void main(String[] args) { SpringApplication.run(HelloworldApplication.class, args); } @RequestMapping(value = "/index") public String index() { return "index"; } } ``` Now, a get request to /index outputs "index" as a string Method 2 -------- The @RequestMapping method in a separate @Controller class ``` package com.personal.boot.spring.helloworld.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class WebController { @RequestMapping(value = "/index") public String index() { return "index"; } } ``` Now, a get request to /index renders the index.html page in templates folder. Why is this the case? Please help.
2019/11/09
[ "https://Stackoverflow.com/questions/58783730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5009920/" ]
In my case I didn't have to eject the settings. I used the packages [react-app-rewired](https://www.npmjs.com/package/react-app-rewired) with the [cutomize-cra](https://www.npmjs.com/package/customize-cra). 1. I created the *config-overrides.js* to overrides the config about **cra** (create-react-app) ``` /* config-overrides.js */ const { override, useBabelRc } = require('customize-cra'); module.exports = override(useBabelRc()); ``` 2. And i create the *.babelrc* because the jest config has a file *babelTransform.js* an in this file already has a property **usebabelrc: true** then you only needs add to run on project build and startup. ``` /* .babelrc */ { "plugins": [ ["@babel/plugin-transform-typescript", { "allowNamespaces": true }] ] } ``` I don’t know if you use the react-app-rewired but if you no use, you need to follow some steps [this steps](https://github.com/timarney/react-app-rewired/) to config
There's a nice tool to avoid the error thrown: <https://github.com/harrysolovay/rescripts> How to: 1. Install rescripts > > npm i -D @rescripts/cli > > > 2. In package.json, replace "react-scripts" with "rescripts": > > > ``` > "scripts": { > "start": "rescripts start", > "build": "rescripts build", > "test": "rescripts test", > "eject": "rescripts eject" }, > > ``` > > 3. Install the rescripts plugin for babel: > > npm i @rescripts/rescript-use-babel-config > > > 4. Add this snipper to *package.json*: > > > ``` > "rescripts": [ > [ > "use-babel-config", > { > "presets": [ > "react-app", > [ > "@babel/preset-typescript", > { > "allowNamespaces": true > } > ] > ] > } > ] > ] > > ``` > >
70,106,975
in my laravel application i have an input field to insert date of birth, my date format has to be `d/m/y` and my age limit has to be 18-70 inside my controller's `store` method I have following validation rule for the dob. ``` 'date_of_birth'=>['required','bail','date','date_format:d/m/y',function ($attribute, $value, $fail) { $age=Carbon::createFromFormat('d/m/y', $value)->diff(Carbon::now())->y; if($age<18||$age>70){ $fail('Âge invalide. l\'âge devrait être 18-70'); } },] ``` but every time when I try to submit the form with a correct date like `23/12/1995` it kept saying date format is invalid
2021/11/25
[ "https://Stackoverflow.com/questions/70106975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10249502/" ]
you have two problems with your code: 1- you should remove 'date' from validation, since you are passing a string not a date. 2- you should correct the format to be right: 'd/m/Y' Y is capital letter. ``` $rules = ['date_of_birth' => ['required', 'bail', 'date_format:d/m/Y', function ($attribute, $value, $fail) { $age = Carbon::createFromFormat('d/m/Y', $value)->diff(Carbon::now())->y; if ($age < 18 || $age > 70) { $fail('Âge invalide. l\'âge devrait être 18-70'); } }, ]]; ```
Use `format` method in function ``` $age=Carbon::createFromFormat('d/m/y', $value)->diff(Carbon::now())->format('%y'); ```
2,340,572
How can we use global.asax in asp.net? And what is that?
2010/02/26
[ "https://Stackoverflow.com/questions/2340572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227848/" ]
Global asax events explained **Application\_Init:** Fired when an application initializes or is first called. It's invoked for all HttpApplication object instances. **Application\_Disposed:** Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources. **Application\_Error:** Fired when an unhandled exception is encountered within the application. **Application\_Start:** Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances. **Application\_End:** Fired when the last instance of an HttpApplication class is destroyed. It's fired only once during an application's lifetime. **Application\_BeginRequest:** Fired when an application request is received. It's the first event fired for a request, which is often a page request (URL) that a user enters. **Application\_EndRequest:** The last event fired for an application request. **Application\_PreRequestHandlerExecute:** Fired before the ASP.NET page framework begins executing an event handler like a page or Web service. **Application\_PostRequestHandlerExecute:** Fired when the ASP.NET page framework is finished executing an event handler. **Applcation\_PreSendRequestHeaders:** Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser). **Application\_PreSendContent:** Fired before the ASP.NET page framework sends content to a requesting client (browser). **Application\_AcquireRequestState:** Fired when the ASP.NET page framework gets the current state (Session state) related to the current request. **Application\_ReleaseRequestState:** Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data. **Application\_ResolveRequestCache:** Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution. **Application\_UpdateRequestCache:** Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests. **Application\_AuthenticateRequest:** Fired when the security module has established the current user's identity as valid. At this point, the user's credentials have been validated. **Application\_AuthorizeRequest:** Fired when the security module has verified that a user can access resources. **Session\_Start:** Fired when a new user visits the application Web site. **Session\_End:** Fired when a user's session times out, ends, or they leave the application Web site.
The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application