qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
2,109,852
I recently got a reply from a server company asking if we are using an ORM in our application which does all the work of sifting application side (like Rails) or if we write reams of SQL, embedded functions etc which would make the database server do the processing for you. Can anyone explain what is meant by this. Our web application is made up of PHP scripts with functions that make calls to the database to retrieve rows of data, then PHP processes these rows as needed to return results to the user. thanks
2010/01/21
[ "https://Stackoverflow.com/questions/2109852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77174/" ]
It basically makes your database tables appear like objects on the PHP side of your site so you can easily manipulate data. For example if you have a User table, getting this user's name is as easy as doing: `$myUser->getName();` adding a new user in your database would be: ``` $myUser = new User(); $myUser->setName('John Doe'); $myUser->save(); ``` Of course this is pseudo code (actually PHP Symfony/Doctrine code), but it's a simple example so you get the point.
Object Relational Mapping is an easy way of mapping Database objects ( tables, views ... ) to classes/objects in OOPL. Hibernate and NHibernate are a few examples of ORM. it does all the tedious task of handling and mapping result sets..
63,527,962
I'm trying to pass object props to Payments component using render method in route. I have tried pass props to the functional components, but still no luck. **App.js** ``` class App extends Component { state = { user: {}, }; componentDidMount() { const url = "/api/current-user"; fetch(url, { headers: { Accept: "application/json", "Content-Type": "application/json", }, credentials: "same-origin", method: "GET", }) .then((response) => { if (!response.ok) { return response.json().then((err) => { throw err; }); } return response.json(); }) .then((results) => { const user = results.user; this.setState({ user, }); }) .catch((error) => { console.log("Error", error); }); } render() { console.log(this.state.user); return ( <div className="container"> <h1 className="is-size-3">Test</h1> {this.state.user && ( <Route exact path="/payments" render={(props) => <Payments {...props} user={this.state.user} /> } /> )} </div> ); } } ``` **Payments.js** ``` function Payments() { return ( <> <CheckoutForm user={this.props.user} /> <CurrentSubscription subscription={subscription} /> </> ); } ``` I have tried a few approaches,but still I'm getting 'props' of undefined. Thanks in advance
2020/08/21
[ "https://Stackoverflow.com/questions/63527962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13143463/" ]
Can't you use a std::function, and use lambdas to capture everything you need? It doesn't appear that your functions take parameters, so this would work. ie ``` std::function<void()> callIt; if(/*case 1*/) { callIt = [](){ myTemplatedFunction<int, int>(); } } else { callIt = []() {myTemplatedFunction<float, float>(); } } callIt(); ```
Your choice of manual memory management and over-use of the keyword `struct` suggests you come from a C background and have not yet really converted to C++ programming. As a result, there are many areas for improvement, and you might find that your current approach should be tossed. However, that is a future step. There is a learning process involved, and incremental improvements to your current code is one way to get there. First, I'd like to get rid of the C-style memory management. Most of the time, using `calloc` in C++ code is wrong. Let's replace the raw pointer with a smart pointer. A [`shared_ptr`](https://en.cppreference.com/w/cpp/memory/shared_ptr) looks like it will help the process along. ``` // Instead of a raw pointer to void, use a smart pointer to void. std::shared_ptr<void> args; // Use C++ memory management, not calloc. args = std::make_shared<args_st<int,float>>(); // or args = std::make_shared<args_st<float,float>>(); ``` This is still not great, as it still uses a pointer to `void`, which is rarely needed in C++ code unless interfacing with a library written in C. It is, though, an improvement. One side effect of using a pointer to `void` is the need for casts to get back to the original type. This should be avoided. I can address this in your code by defining correctly-typed variables inside the `if` statement. The `args` variable will still be used to hold your pointer once the correctly-typed variables go out of scope. More improvements along this vein can come later. The key improvement I would make is to use the functional [`std::function`](https://en.cppreference.com/w/cpp/utility/functional/function) instead of a function pointer. A `std::function` is a generalization of a function pointer, able to do more albeit with more overhead. The overhead is warranted here in the interest of robust code. An advantage of `std::function` is that the parameter to `g()` does not need to be known by the code that invokes the `std::function`. The old style of doing this was `std::bind`, but lambdas provide a more readable approach. Not only do you not have to worry about the type of `args` when it comes time to call your function, you don't even need to worry about `args`. ``` int someFunction() { // Use a smart pointer so you do not have to worry about releasing the memory. std::shared_ptr<void> args; // Use a functional as a more convenient alternative to a function pointer. // Note the lack of parameters (nothing inside the parentheses). std::function<void()> func; if ( /* some runtime condition */ ) { // Start with a pointer to something other than void. auto real_args = std::make_shared<args_st<int,float>>(); // An immediate function call: f(real_args.get()); // Choosing a function to be called later: // Note that this captures a pointer to the data, not a copy of the data. // Hence changes to the data will be reflected when this is invoked. func = [real_args]() { g(real_args.get()); }; // It's only here, as real_args is about to go out of scope, where // we lose the type information. args = real_args; } else { // Similar to the above, so I'll reduce the commentary. auto real_args = std::make_shared<args_st<float,float>>(); func = [real_args]() { g(real_args.get()); }; args = real_args; } /* other code that does stuff with args */ /* This code is probably poor C++ style, but that can be addressed later. */ // Invoke the function. func(); return 0; } ``` Your next step probably should be to do some reading on these features so you understand what this code does. Then you should be in a better position to leverage the power of C++.
61,820,673
I have an extension in my personal account, and I already created a Group Publisher account, and now I want to move the extension from my personal account to the Group publisher account I've created. I already read this document: <https://developer.chrome.com/webstore/publish#move-existing-items-to-a-group-publisher-account> I was able to create and setup the Group publisher, but the problem now is that I can't see the Transfer existing item(s) option (that's supposed to be next to Add New Item button, according to the documentation). and I'm stuck there! Any recommendation?[![This is what my Group Publisher Account dashboard looks like](https://i.stack.imgur.com/GkTlJ.jpg)](https://i.stack.imgur.com/GkTlJ.jpg)
2020/05/15
[ "https://Stackoverflow.com/questions/61820673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9434604/" ]
It is my first answer here, and I am glad to be helpful to you. «Transfer existing item(s)» option is not available in new version of Developer Dashboard, which you are using. In lower left-corner find Feedback window, press «Show more» and click «Opt out». You will be redirected to older version of Dashboard, when the needed button is available.
You can find the option "transfer to group publisher" in the kebab menu on the right of the "Submit for review" button now. [![Screenshot showing the three dots menu button on the right of the toolbar of an Google Chrome Extension Dashboard, showing a dropdown with the options Preview, Unpublish and Transfer to group publisher](https://i.stack.imgur.com/2MrHs.png)](https://i.stack.imgur.com/2MrHs.png)
26,398
Namo Budhaya. In the [Mindfulness of Death](https://suttacentral.net/an8.73/en/sujato) sutta Buddha says the following: > > When this was said, the Buddha said to those mendicants: “The > mendicants who develop mindfulness of death by wishing to live for a > day and night … or to live for a day … or to live for half a day … or > to live as long as it takes to eat a meal of alms-food … or to live as > long as it takes to eat half a meal of alms-food … or to live as long > as it takes to chew and swallow four or five mouthfuls … These are > called mendicants who live negligently. They slackly develop > mindfulness of death for the ending of defilements. > > > But the mendicants who develop mindfulness of death by wishing to live > as long as it takes to chew and swallow a single mouthful … or to live > as long as it takes to breathe out after breathing in, or to breathe > in after breathing out … These are called mendicants who live > diligently. They keenly develop mindfulness of death for the ending of > defilements. > > > Buddha corrects wrong way to mindfulness of death. But as far as I see , a person who wishes to live as long as it takes to chew and swallo a single mouthful , is same as a person who wishes to live as long as as it takes to chew and swallow ....The translator of the text failed to point out the difference between the mendicant's way of mindfulness of death and Buddha's way of mindfulness of death. I will thankful if someone could explain this sutta in its true essence. My question is :How should one be mindful of death?
2018/05/12
[ "https://buddhism.stackexchange.com/questions/26398", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/11541/" ]
Oh, this is easy. This one I was taught many *many* times. Here is how it goes: Regular untrained people live their life as if they will live forever. They 1) worry about small unimportant stuff, get offended, or scared, or enraged at things that are not really important. And 2) they waste days, months and years of life *waiting* for better life. However, 1) Everyone dies, sooner or later. Even the Buddha had to die. First, our parents will die. Then our friends of same age will start dying. Then the day will come when our breathing will stop and we will die too. Every day we get a day closer to death. Every time we celebrate our birthday, that's one less year we have left to live. The time seems to go slowly, but if you look back you realize it did not take you that long to reach your current age. Similarly, one day you will look back and realize you have spent all of your time. Also 2) Death comes without a warning. The other day my friend (a doctor) called me and said his patient died in a car accident. He had a big house, 3 children and a housewife. As he was coming home from work, a truck made a mistake shifting lanes, and pushed his car off the road. We have no idea how we'll die. We hope we'll die from old age, in our bed, surrounded by grandchildren - but there is no guarantee it will be that nice. People die from all kinds of causes: from accidents, to disease, to terrorism, to allergic reactions, to poisonous snakes or insects, to plane crashes, to sudden heart attacks, to cancer. So 3) We should stop expecting we'll live much longer. There is absolutely no guarantee that we will live to see the next summer, or next Christmas, or our next birthday. In fact, we should get into habit thinking that any day could be our last day on Earth. When we go to work, we should expect that we may not come back. When we go to bed, we should expect that we may not wake up. Therefore 4) We should not live a lukewarm life. We should live our life as if this was our last day. This pertains both to our Dharma practice, but also to our attitude to life in general. We should perform every act, every conversation as if this was our last battle on earth. And 5) If we feel like we worry about something too much, we should compare this problem with death. If the problem is worse than death, then we are allowed to worry. But if the problem is not as bad as death, then we should sober up and stop worrying too much. Mindfulness of death gives us a useful perspective in which truly important things matter and non-important things are seen correctly as unimportant. It also gives us strength to act with courage and not live lukewarm life. So no matter how you look at it, it is a very useful perspective to cultivate. And the way you cultivate it is by thinking about it, meditating on it, until you feel it, until it is with you at all times - judging all of your action and inaction. Then the death becomes your solemn friend: "You don't have that long left. Use it wisely"
In the Lamrim, there is what is known as the nine fold contemplation on death. This has three main points and each of the three has three sub points. I will list and try to explain them: The main points are: 1. Contemplating death’s certainty. 2. Contemplating the uncertainty of the time of death. 3. Contemplating that at the time of death nothing but the dharma will be of any use. The first has three parts: \* It is certain that the Lord of Death will come and that nothing whatsoever can turn him back. \* Life span cannot be extended and it shortens unceasingly. \* Dying without having had the time to practise the teaching while alive. As part of this first set of contemplation we should understand that there is nobody around us who has lived for ever. Average lifespan maybe increasing due to better healthcare but immortality is still nowhere in the scientific horizon. Moreover there is a concept of your karmic lifespan, this cannot be extended and death can come in many ways, Old-age, illness, accidents or wars can bring us death. The second, contemplating the uncertainty of the time of death, has three parts: \* In this world in general and in the degenerate age in particular life span is uncertain. \* Time of death is uncertain as the causes of death are many and those sustaining life few. \* Time of death is uncertain also as bodies are very fragile. The second contemplation is about the time of death. I could pass away by the end of this sentence or may be not. There is no telling. In fact we are constantly moving towards death from the moment of our conception. The third, contemplating that at the time of death nothing but the dharma will be of any use, has three parts: Contemplating that \* Wealth is useless. \* Friends and relatives will be useless. \* And even your body will be useless. Finally we should understand that our understanding of dharma and the Karma that we accumulate is the only thing that will help us during the time of our death. This according to the Lamrim is the primary way to contemplate on death. And it will provide us with the primary motivation to practice the dharma. Death itself is the grossest manifestation of Impermanence. This should be followed with contemplation on subtle Impermanence and how things arise and pass away from moment to moment.
43,742,772
I am getting a class "fluid-width-video-wrapper" with padding"59%". can anybody let me know, how can i get rid of this class. I don't found this class in files also. Thanks
2017/05/02
[ "https://Stackoverflow.com/questions/43742772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7903273/" ]
I want just to extend a bit @FEMP's answer. Indeed, the wrapper added by the FitVids.js plugin. You can simply add the `fitvidsignore` class to your `<iframe>` to ignore all effects of the plugin. It will be useful if you still need this script on some other page...
Check your code for FitVids.js it's a plugin for fitting video on the page, check it here: <https://github.com/davatron5000/FitVids.js>
44,193,045
I know `RecyclerView` animates item additions/deletions for us for free. Is it supposed to support animating item height changes as well? **For example** : Consider a row item with the following xml :- ``` <LineaLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/tv1" /> <TextView android:id="@+id/tv2" android:visibility="gone" /> </LinearLayout> ``` If I set "tv2" visibility to `View.VISIBLE`, the row height changes without any animation. I've seen a few approaches of attempting to run your own `ValueAnimator` on the view itself, but my understanding is that it is (1) not efficient (2) you shouldn't run animations directly on the views themselves as they may get recycled from user interaction while the animation is running.
2017/05/26
[ "https://Stackoverflow.com/questions/44193045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219278/" ]
Add a `visibility` component to your object that you're using in your adapter. In the item view's `onClickListener`, change the state of that object's visibility component depending on the current state. In the `onBindViewHolder`, set the visibility of `tv2` depending on the state of your object and notify the adapter that the object has changed. Here's an example: ``` @Override public void onBindViewHolder(MyViewHolder holder, int position) { MyObject obj = myObjects.get(position); holder.itemView.findViewById(R.id.tv2).setVisibility(obj.isVisible() ? View.VISIBLE : View.GONE); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { obj.setVisible(!obj.isVisible()); notifyItemChanged(position); } }); } ```
Try setting `android:animateLayoutChanges="true"` in the `LinearLayout` in XML
72,893,643
I have a pandas data frame like so. | fruit | year | price | | --- | --- | --- | | apple | 2018 | 4 | | apple | 2019 | 3 | | apple | 2020 | 5 | | plum | 2019 | 3 | | plum | 2020 | 2 | and I want to add column [last\_year\_price] please help......
2022/07/07
[ "https://Stackoverflow.com/questions/72893643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19500501/" ]
You can use the shift function: ``` df['last_year_price'] = df.sort_values(by=['year'], ascending=True).groupby(['fruit'])['price'].shift(1) ```
Use [`DataFrameGroupBy.idxmax`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmax.html) for rows with maximal years and join to oriinal DataFrame: ``` df = df.merge(df.loc[df.groupby('fruit')['year'].idxmax(), ['fruit','price']].rename(columns={'price':'last_year_price'}), on='fruit', how='left') print (df) fruit year price last_year_price 0 apple 2018 4 5 1 apple 2019 3 5 2 apple 2020 5 5 3 plum 2019 3 2 4 plum 2020 2 2 ```
327,929
> > This coffee is also available in packs **with** smaller amounts? > > > > > This coffee is also available in packs **of** smaller amounts? > > > Which preposition should I use in the sentence above “of” or “with”? I thought a pack has an amount of something but I couldn’t decide whether I should use “with” or “of”. I gave such an example to understand which preposition should be used for the verb “have”.
2022/11/23
[ "https://ell.stackexchange.com/questions/327929", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/145531/" ]
"Packs **of** smaller amounts" means the packs themselves are smaller, so they hold a smaller amount of the substance. They will likely be marked with a smaller number on the outside, like packs of 1 kg, 500 g, etc. "Packs **with** smaller amounts" could mean the same as above, OR it could mean the *same sized packs, but having a smaller amount inside*.
> > This coffee is also available in packs with/of smaller amounts > > > Both versions are so awkward that as a native I honestly don't know which might be technically right or wrong. You can count packs using 'of', but there would usually be a quantifier. "You can buy these in packs of ten." etc. No-one would really say it that way, unless they were counting, they'd just get the whole thing done with > > This coffee is also available in smaller packs. > > > Or, to give out full information, including the count, all in one shot > > This coffee is available in packs of 250g, 500g and 1Kg > > >
18,946,863
So I have to get words from a text file, change them, and put them into a new text file. The problem I'm having is, lets say the first line of the file is hello my name is bob the modified result should be: ellohay myay amenay isay bobay but instead, the result ends up being ellomynameisbobhay so scanner has .nextLine() but I want to have a method that is .nextWord() or something, so that it will recognize something as a word until it has a space after it. how can I create this?
2013/09/22
[ "https://Stackoverflow.com/questions/18946863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2780384/" ]
I realized I was making this too complicated. If I'm going to implement a factory method for each `enum` instance, I may as well just have separate factory methods for each interface. ``` public interface Factory { IFooBar createFooBar(); IFooBaz createFooBaz(); } class CodeFactory implements Factory { public FooBarImpl createFooBar() { // etc. } } ``` Of course now I have to change the Factory API if there are ever new interfaces, but I expect that will be rare.
A possible solution would be defining a wrapper that implements `IFoo` and the `getCode()` method, and your method would return the intended class in one of such wrappers. If the wrapped instance has a `getCode` implemented, the wrapper would return its value, return it, otherwise return `null`.
18,669,966
Blender noob trying to render an object but certain parts of it keep coming out black. I'm not sure why. My image is here which might help: ![some faces come out black](https://i.stack.imgur.com/r5K3T.jpg) A few extra details: * The shelves I've been trying to render are just a collection of planes which I've aligned to form shelves * All of them have no material or texture on them * Despite this, the very furthest plane (back of the shelves) and the front one which says laundry render properly in white, but the others render in black * I've tried adding material/texture to all of them, but they still come out black * My light source is set to "Sun" and sits a little bit behind the camera and shines directly onto the shelves Is this a lighting issue?? If so any suggestions for how to fix?
2013/09/07
[ "https://Stackoverflow.com/questions/18669966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979071/" ]
``` android:listSelector="@drawable/list_selectorcolor" ``` In drawable create like this ``` <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <gradient android:angle="90" android:endColor="#000000" android:startColor="#000000" android:type="linear"/> <stroke android:width="1dp" android:color="#800080" android:dashWidth="2dp"/> </shape> ```
Try this according to your code ``` viewHolder.imageview.setText(entry.getString("calculator")); if(position % 2 == 0){ viewHolder.linearLayout.setBackgroundResource(R.color.grey); } else{ //viewHolder.linearLayout.setBackgroundResource(R.color.white); } ``` It will change the color of row
18,720,714
I have a session object in my c# class, that contains an [ArrayList](http://msdn.microsoft.com/en-us/library/system.collections.arraylist%28v=vs.90%29.aspx) type of data. How can I access the array within the session object? Given the image below, how would I access \_confNum value? ![enter image description here](https://i.stack.imgur.com/UeMPN.png)
2013/09/10
[ "https://Stackoverflow.com/questions/18720714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72324/" ]
HttpSession is a key-object store. C# is strongly typed, you need to cast the result of the []-accessor. ``` TripAssignment[] logs = (TripAssignment[])HttpContext.Current.Session["DriverTripLog"]; TripAssignment log = logs[0]; ``` By the way, you shouldnt use ArrayList, if possible. ``` ArrayList logs = (ArrayList)HttpContext.Current.Session["DriverTripLog"]; TripAssignment log = (TripAssignment)logs[0]; ```
``` var list = Session["DriverTripLog"]!=null? (ArrayList)Session["DriverTripLog"]:null; ```
3,394,194
I refer to this page: [Post array of multiple checkbox values](https://stackoverflow.com/questions/1557273/jquery-post-array-of-multiple-checkbox-values-to-php) ``` <input type="checkbox" class="box" value="blue" title="A" /> <input type="checkbox" class="box" value="red" title="B" /> <input type="checkbox" class="box" value="white" title="C"/> $('#include').click(function(){ var val = $('.box:checked').map(function(i,n) { return $(n).val(); }).get(); //get converts it to an array var title = $('.box:checked').map(function(i,n) { return $(n).attr('title'); }).get(); //get converts it to an array $.post(url, {'val[]': val,'title[]':title}, function(response) { alert('scuess'); }); return false; }) --------------------------------------------- <?php foreach($_GET['val'] as $numA) { foreach($_GET['title'] as $numB) { $str="insert into user_photos (val,title) values ('$numA','$numB')"; mysql_query($str,$link); } } ?> ``` Please tell me how to do that...
2010/08/03
[ "https://Stackoverflow.com/questions/3394194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409329/" ]
<http://jsfiddle.net/PgKEt/2/> This is the best that I can do. If you try to use setInterval and such to animate it, it will keep redrawing even when it does not need to. So by doing this, you essentially only redraw when the mouse moves, and only draw 2 lines, instead of whatever content you want it on top. In addition, if you have any detection such as mousedown and such, it has to be on whatever canvas is on the top, otherwise it will not detect them anymore.
This approach works fast enough for me in Firefox 3.6.8 to do in a mousemove event. Save the image before you draw the crosshair and then restore it to erase: To save: ``` savedImage = new Image() savedImage.src = canvas.toDataURL("image/png") ``` The to restore: ``` ctx = canvas.getContext('2d') ctx.drawImage(savedImage,0,0) ```
19,451,150
I am making a basic calculator for Android by eclipse and Java. The task is there are two values, like input and result. So when the first number is pressed, it saves it, then a plus or minus sign is pressed ad then the second value which is result. My idea was to create a method for every button something like this: ``` public void number1(View view){ value1 = value2; value2 = 1; displayValue(); } ``` But did not work and also I am repeating a few lines many times which isnt nice. So what about using switch, or any idea to have one single method and put it on all `android:onClick""` for buttons. So if you have any idea just explain it or write an example. Thanks in advance.
2013/10/18
[ "https://Stackoverflow.com/questions/19451150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2888552/" ]
First, no space between `<` and `div` (saw here: `< DIV id="phone_valid" class="popup-value"></DIV>'` ) Second: ``` function checkSubmit(){ var country=$("#phone_valid").text(); // it is a div not input to get val(). if(country=="No") { alert("Not a valid number"); return false; } ```
If you need to include HTML comments then consider using [contents() method](http://api.jquery.com/contents/) `$('#mydiv').contents()` Other wise `html()` method or even `text()` will be what you are looking for because `val()` purpose is for form elements ;)
30,712,474
Is it possible to completely disable sanitizingof HTML? What I want to achieve is to have in my controller: ``` $scope.greeting = '<h2>Hello World</h2>' ``` And in my view ``` {{greeting}} ``` I cannot (and dont want to) use ng-bind-html and such, I want to disable sanitizing all together. Just to give some more context - I am preparing simple "framework wrap around" for developing a template for specific system. When you develop template for this system, they have pre-defined snippets that you can place on your page by writing "{{something}}" but it is not running on angular (probably mustache or something). Now the template can be developed only online and it is VERY user-unfriendly proccess. Therefore I setup simple project in angular with corresponding routes etc, so everyone can develop the template on their machine and then simply copy it over to the system. That is why in the template files it shouldnt be noticable that its done in angular, it just be as close to their system as possible. One last note - I did try: ``` myApp.config(['$sceProvider',function($sceProvider){ $sceProvider.enabled(false); }]); ``` Didn't do anything for me
2015/06/08
[ "https://Stackoverflow.com/questions/30712474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/820942/" ]
Try enhance or change standard behavior of $sce using decorators: ``` angular .module( appName, [ ] ) .config([ "$provide", function( $provide ) { // Use the `decorator` to enhance or change behaviors of original service instance; $provide.decorator( '$sce', [ "$delegate", function( $delegate ) { // Save the original $sce.parseAsHtml var parseAsHtml= $sce.parseAsHtml; $delegate.parseHtml= function( ) { // Implements your custom behavior... }; return $delegate; }]); }]); ```
I managed to find another way of solving the problem without using any directives. Basically I use an injector to use the $compile service. JS: ``` angular.injector(['ng']).invoke(function($compile, $rootScope) { $('.html-content').append($compile('<h2>Hello World</h2>')($rootScope)); }); ``` Here's a demo: <https://jsfiddle.net/davguij/tby59sk7/1/>
6,913,532
How can I display `Decimal('40800000000.00000000000000')` as `'4.08E+10'`? I've tried this: ``` >>> '%E' % Decimal('40800000000.00000000000000') '4.080000E+10' ``` But it has those extra 0's.
2011/08/02
[ "https://Stackoverflow.com/questions/6913532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
Given your number ``` x = Decimal('40800000000.00000000000000') ``` Starting from Python 3, ``` '{:.2e}'.format(x) ``` is the recommended way to do it. `e` means you want scientific notation, and `.2` means you want 2 digits after the dot. So you will get `x.xxE±n`
I prefer Python 3.x way. ``` cal = 123.4567 print(f"result {cal:.4E}") ``` `4` indicates how many digits are shown shown in the floating part. ``` cal = 123.4567 totalDigitInFloatingPArt = 4 print(f"result {cal:.{totalDigitInFloatingPArt}E} ") ```
8,806,659
I'm learning `backbone.js` for a `Rails 3` application I'm working on. Backbone uses `underscore` which, I believe, has its own template engine built in. I've read good things about mustache but was wondering if I should consider using it instead of the built in template engine of underscore? What are your thoughts? Thanks
2012/01/10
[ "https://Stackoverflow.com/questions/8806659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59202/" ]
I am about halfway through my first enterprise level backbone app. I am currently using underscores built in templates because when I started the way I had learned was with underscore.. I don't necessarily have any problem with them. All of the templating solutions are pretty straight forward. I have since looked at a few of the other solutions and am contemplating switching, but only because I think some of the other solutions look cleaner. Also some of the solutions have a tad bit more functionality. I like mustache because of its shorter syntax. Looks cleaner. But I if I do switch I think I'm going to go with Handlebars.js. Handlebars has the same short syntax, plus a ton of other features such as custom helper methods and setting object context inside your template. Check it out [here](http://handlebarsjs.com/). If I had known about handlebars at the beginning of my project I probably would have jumped on it for sure. I wouldn't worry so much about adding another dependency as others have mentioned. Backbone apps done right will run lightning fast anyways. :D If you have any other questions let me know. I've been really enjoying backbone so I'm trying to watch the tagged posts. But seriously. Handlebars looks legit. EDIT: I also meant to add that the documentation for handlebars looks way more legit than underscores...
The question asks Rails, but isn't tagged so; so a con is conflicts with languages using mustache-like syntax such as django's templates. If a django template parses a block first, it will attempt to fill in the `{{ }}` blocks before ever writing the JS. I am using a `verbatim` django template tag that ignores `{{}}` blocks to solve the issue but I now wish I used the default `<%=%>` syntax so that I don't have to explicitly escape these blocks written in the django template engine.
3,092,686
> > It is given that > $$f(x)= \sin(x+30^\circ) + \cos(x+60^\circ)$$ > > > A) Show that $$f(x)= \cos(x)$$ > > > B) Hence, show that > $$f(4x) + 4f(2x) =8\cos^4(x)-3$$ > > > I managed to prove $f(x)$ equals $\cos(x)$, but after that I'm stumped.
2019/01/29
[ "https://math.stackexchange.com/questions/3092686", "https://math.stackexchange.com", "https://math.stackexchange.com/users/639594/" ]
You can use the property: $$cos(2x) = cos^2(x)-sin^2(x)$$ Since this will allow you to express $cos(4x)$ = $$cos^2(2x)-(1-cos^2(2x)) = 2cos^2(2x)-1$$ By substituting again $cos(2x)$ by the aforementioned expression you will be able to express $4cos(2x)+cos(4x)$ in terms of $sin(x)$ and $cos(x)$ raised to some powers. The sinus will cancell out and will obtained the desired result.
$$f(x)=\sin(30^{\circ}+x)+\sin(30^{\circ}-x)=2\sin30^{\circ}\cos{x}=\cos{x}.$$ Thus, $$f(4x)+4f(2x)=\cos4x+4\cos2x=8\cos^4x-8\cos^2x+1+8\cos^2x-4=8\cos^4x-3.$$
1,940,175
I am appending some text containing '\r\n' into a word document at run-time. But when I see the word document, they are replaced with small square boxes :-( I tried replacing them with `System.Environment.NewLine` but still I see these small boxes. Any idea?
2009/12/21
[ "https://Stackoverflow.com/questions/1940175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186280/" ]
Have you not tried one or the other in isolation i.e.`\r` or `\n` as Word will interpret a carriage return and line feed respectively. The only time you would use the Environment.Newline is in a pure ASCII text file. Word would handle those characters differently! Or even a Ctrl+M sequence. Try that and if it does not work, please post the code.
Word uses the `<w:br/>` XML element for line breaks.
97
Как правильно писать: «при**йт**и» или «при**дт**и»?
2011/12/19
[ "https://rus.stackexchange.com/questions/97", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/17/" ]
Глагол «идти» (или устаревший «итти») — одно из самых древних слов русского языка. Раньше действительно употреблялась форма «при**дт**и» (с корнем *ид*, как в слове «пр**ид**ешь»), однако сейчас она исчезла из русского языка, заменившись формой «пр**ий**ти». Таким образом, правильно — «пр**ий**ти».
**Кодифицированным** написанием (по Розенталю) является «пр**ий**ти». До некоторого времени несколько десятилетий обе формы употреблялись одновременно, в 19 веке и начале 20-го литературной формой была только «при**дт**и» («пр**ий**ти» относилась к просторечиям).
28,757,056
I came across this code in Googles Web login example ([Here](https://github.com/googleplus/gplus-quickstart-csharp.git)) and I dont know why this is purple. I believe that it is some kind of global value, kinda like the Author item in Office. but if thats so, how do you set them? what is it even called? ![Purple Text](https://i.stack.imgur.com/LWueW.png)
2015/02/27
[ "https://Stackoverflow.com/questions/28757056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2921949/" ]
The html file that you see there is read in by the application and the values that you see between the curly braces are replaced with values from the application. Look at the c# code to see where this is happening. <https://github.com/googleplus/gplus-quickstart-csharp/blob/master/gplus-quickstart-csharp/signin.ashx.cs> around line 117 you'll see where the values are replaced.
the purple text is a placeholder to be replaced by the actual value. look at signin.ashx.cs for the following code: ``` static public string APP_NAME = "Google+ C# Quickstart"; //... templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME); ```
6,127,729
I have a Postgres DB running 7.4 (Yeah we're in the midst of upgrading) I have four separate queries to get the Daily, Monthly, Yearly and Lifetime record counts ``` SELECT COUNT(field) FROM database WHERE date_field BETWEEN DATE_TRUNC('DAY' LOCALTIMESTAMP) AND DATE_TRUNC('DAY' LOCALTIMESTAMP) + INTERVAL '1 DAY' ``` For Month just replace the word `DAY` with `MONTH` in the query and so on for each time duration. Looking for ideas on how to get all the desired results with one query and any optimizations one would recommend. Thanks in advance! NOTE: date\_field is timestamp without time zone UPDATE: Sorry I do filter out records with additional query constraints, just wanted to give the gist of the date\_field comparisons. Sorry for any confusion
2011/05/25
[ "https://Stackoverflow.com/questions/6127729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93966/" ]
I have some idea of using prepared statements and simple statistics (record\_count\_t) table for that: ``` -- DROP TABLE IF EXISTS record_count_t; -- DEALLOCATE record_count; -- DROP FUNCTION updateRecordCounts(); CREATE TABLE record_count_t (type char, count bigint); INSERT INTO record_count_t (type) VALUES ('d'), ('m'), ('y'), ('l'); PREPARE record_count (text) AS UPDATE record_count_t SET count = (SELECT COUNT(field) FROM database WHERE CASE WHEN $1 <> 'l' THEN DATE_TRUNC($1, date_field) = DATE_TRUNC($1, LOCALTIMESTAMP) ELSE TRUE END) WHERE type = $1; CREATE FUNCTION updateRecordCounts() RETURNS void AS $$ EXECUTE record_count('d'); EXECUTE record_count('m'); EXECUTE record_count('y'); EXECUTE record_count('l'); $$ LANGUAGE SQL; SELECT updateRecordCounts(); SELECT type,count FROM record_count_t; ``` Use updateRecordCounts() function any time you need update statistics.
Yikes! Don't do this!!! Not because you can't do what you're asking, but because you probably shouldn't be doing what you're asking in this manner. I'm guessing the reason you've got `date_field` in your example is because you've got a `date_field` attached to a user or some other meta-data. Think about it: you are asking PostgreSQL to scan 100% of the records relevant to a given user. Unless this is a one-time operation, you almost assuredly do not want to do this. If this is a one-time operation and you are planning on caching this value as a meta-data, then who cares about the optimizations? Space is cheap and will save you heaps of execution time down the road. You should add 4x per-user (or whatever it is) meta-data fields that help sum up the data. You have two options, I'll let you figure out how to use this so that you keep historical counts, but here's the easy version: ``` CREATE TABLE user_counts_only_keep_current ( user_id , -- Your user_id lifetime INT DEFAULT 0, yearly INT DEFAULT 0, monthly INT DEFAULT 0, daily INT DEFAULT 0, last_update_utc TIMESTAMP WITH TIME ZONE, FOREIGN KEY(user_id) REFERENCES "user"(id) ); CREATE UNIQUE INDEX this_tbl_user_id_udx ON user_counts_only_keep_current(user_id); ``` Setup some stored procedures that zero out individual columns if `last_update_utc` doesn't match the current day according to `NOW()`. You can get creative from here, but incrementing records like this is going to be the way to go. Handling of time series data in **any** relational database requires special handling and maintenance. Look in to PostgreSQL's table inheritance if you want good temporal data management.... but really, don't do whatever it is you're about to do to your application because it's almost certainly going to result in bad things(tm).
43,758,971
I'm trying to do a button like the number pad key but with a number in the left corner. It supose to have a glyphicon in the center, a text bellow that and a small number on the left top corner. I can't put the number in the top left corner he always stand on the left of the glyphicon. ```css .btn-default{ height: 8vh; font-size: 12px; text-align: center; } .txt{ font-size: 8px; color:blue; right:0; top:0; } ``` ```html <button type="button" id="buttonPlay" class="btn btn-default btn-lg text-center" ng-click="vid.playVideo()"> <span class="txt" > 8 </span> <span class="glyphicon glyphicon-play"></span><br>Play <!-- <span class="tooltiptext">Play</span>--> </button> ``` I already try margin and right: 0 and top:0 but nothing seems to work, any help!?
2017/05/03
[ "https://Stackoverflow.com/questions/43758971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7798293/" ]
Simply, use float left to left item and float right to right item and use padding on button to apply alignment on elements of button.
You need to give the **button** `position:relative` and the **span** `position:absolute`
7,937,369
I am having trouble animating scale of a view to zero. Here's my code: ``` [UIView animateWithDuration:0.3 animations:^{ myView.transform = CGAffineTransformMakeScale(0.0, 0.0); } completion:^(BOOL finished){ }]; ``` For some reason, the view stretches and squeezes horizontally like old TV tube switching off. If I make the scale to `(0.1, 0.1)` instead, it scales properly, but of course, not til zero. Why is this happening?
2011/10/29
[ "https://Stackoverflow.com/questions/7937369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58505/" ]
If someone is still interested, here's what I did (in Swift) to make it work (almost): ``` UIView.animate(withDuration: 1) { myView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) } ``` If the duration is short, you don't get to see that is doesn't scale exactly to 0 and it effectively fades.
In case anyone is still having this issue, the problem lies with the affine transform matrix not being unique for a scale factor of zero – there is no way of knowing how to interpolate "properly" between the initial matrix and the zero matrix, so you get weird effects like you described. The solution is simply to use a small but nonzero scale value, e.g. ``` [UIView animateWithDuration:0.3 animations:^{ myView.transform = CGAffineTransformMakeScale(0.01, 0.01); } completion:nil]; ```
40,875,794
I am making an ajax to call data from database with php and i want to load the result in two inputs(label and listbox) in html page,the problem is that it show the value in the label`#FrmCount` but it is not showing anything in the listbox `#FarmersID`.. Here is the ajax ``` $.ajax({ type:"POST", url:"AddData.php", dataType: 'json', data: { 'Order_ID': Order_ID, 'Frm_ID':Frm_ID, 'Frm_Wet':Frm_Wet, 'Frm_Dry':Frm_Dry, 'Frm_Fermented':Frm_Fermented, 'Frm_Date':Frm_Date }, success: function(data) { $("#FrmCount").html(data.FarmerCount); $("#FarmersID").html(data.FarmersID); }, error: function(jqXHR, textStatus, errorThrown) { console.log('ERROR', textStatus, errorThrown); } }) ``` And this is the php code: ``` $stmt1 ="SELECT distinct Farm_id FROM ordersfarmers WHERE Order_ID='".$_POST["Order_ID"]."'AND Reply='1'"; $results=$conn->query($stmt1)->fetchAll(); $res=count($results); foreach ($conn->query($stmt1) as $row) { $json = array("FarmerCount" => $res, "FarmersID" => $row['Farm_id'] ); echo json_encode($json); } ``` and the html part ``` <div> <select name="FarmersID" id="FarmersID" multiple style="width:280px;height:110px;" onclick="showonmap()"> </select> </div> <div> <label id="FrmCount"></label> </div> ```
2016/11/29
[ "https://Stackoverflow.com/questions/40875794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7171921/" ]
To weed out default cameras, you could query for `startupCamera` using the `cmds.camera`. Here is some code (with comments) to explain. Pymel Version ------------- ``` # Let's use Pymel for fun import pymel.core as pm # Get all cameras first cameras = pm.ls(type=('camera'), l=True) # Let's filter all startup / default cameras startup_cameras = [camera for camera in cameras if pm.camera(camera.parent(0), startupCamera=True, q=True)] # non-default cameras are easy to find now. Please note that these are all PyNodes non_startup_cameras_pynodes = list(set(cameras) - set(startup_cameras)) # Let's get their respective transform names, just in-case non_startup_cameras_transform_pynodes = map(lambda x: x.parent(0), non_startup_cameras_pynodes) # Now we can have a non-PyNode, regular string names list of them non_startup_cameras = map(str, non_startup_cameras_pynodes) non_startup_cameras_transforms = map(str, non_startup_cameras_transform_pynodes) ``` cmds Version ------------ ``` import maya.cmds as cmds # Get all cameras first cameras = cmds.ls(type=('camera'), l=True) # Let's filter all startup / default cameras startup_cameras = [camera for camera in cameras if cmds.camera(cmds.listRelatives(camera, parent=True)[0], startupCamera=True, q=True)] # non-default cameras are easy to find now. non_startup_cameras = list(set(cameras) - set(startup_cameras)) # Let's get their respective transform names, just in-case non_startup_cameras_transforms = map(lambda x: cmds.listRelatives(x, parent=True)[0], non_startup_cameras) ``` Some further reading: <http://ewertb.soundlinker.com/mel/mel.082.php>
You probably need to depend on [listCamera](http://help.autodesk.com/cloudhelp/2015/ENU/Maya-Tech-Docs/CommandsPython/listCameras.html) command which you can list only persp camera or other. eg : perspCameras = cmds.listCameras( p=True )
35,823,599
I have a textfile that has > > 1 > > > 2 > > > 3 > > > 4 > > > I am trying to tokenize the data per line into an array. However,tokens[0] is reading 1 2 3 4. How do I make it in such a way where > > > ``` > tokens[0] = 1 > > tokens[1] = 2; > > tokens[2] = 3; > > ``` > > What is wrong with my code basically. ``` public static void readFile() { BufferedReader fileIn; String[] tokens; String inputLine; try { fileIn = new BufferedReader(new FileReader("test.txt")); inputLine = fileIn.readLine(); while (inputLine != null) { tokens = inputLine.trim().split("\\s+"); System.out.println(tokens[0]); inputLine = fileIn.readLine(); } fileIn.close(); } catch (IOException ioe) { System.out.println("ERROR: Could not open file."); System.out.println(ioe.getMessage()); } } } ```
2016/03/06
[ "https://Stackoverflow.com/questions/35823599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5327929/" ]
I think your problem is the way you are using the tokens array. Using an ArrayList as NullOverFlow suggested will give the behaviour you want. Here's a quick solution using an ArrayList, and Raghu K Nair's suggestion to take the whole line instead of splitting. It is complete - you can run it yourself to verify: ``` import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.util.List; import java.util.ArrayList; public class tokenize { public static List<String> readFile( String fileName ) { FileInputStream fileStrm = null; InputStreamReader reader = null; BufferedReader buffReader = null; List<String> tokens = null; try { // Set up buffered reader to read file stream. fileStrm = new FileInputStream( fileName ); reader = new InputStreamReader( fileStrm ); buffReader = new BufferedReader( reader ); // Line buffer. String line; // List to store results. tokens = new ArrayList<String>(); // Get first line. line = buffReader.readLine(); while( line != null ) { // Add this line to the List. tokens.add( line ); // Get the next line. line = buffReader.readLine(); } } catch( IOException e ) { // Handle exception and clean up. if ( fileStrm != null ) { try { fileStrm.close(); } catch( IOException e2 ) { } } } return tokens; } public static void main( String[] args ) { List<String> tokens = readFile( "foo.txt" ); // You can use a for each loop to iterate through the List. for( String tok : tokens ) { System.out.println( tok ); } } } ``` This relies on a text file formatted as described in your question.
I think this might solve your problem ``` public static void readFile() { try { List<String> tokens = new ArrayList<>(); Scanner scanner; scanner = new Scanner(new File("test.txt")); scanner.useDelimiter(",|\r\n"); while (scanner.hasNext()) { tokens.add(scanner.next()); System.out.println(tokens); } } catch (FileNotFoundException ex) { Logger.getLogger(MaxByTest.class.getName()).log(Level.SEVERE, null, ex); } } ```
35,940,057
I'm pretty sure this is a dumb issue, but I searched and could not find a similar/equal scenario. So, I have a main PHP page in which I include several Javascript files in the `head` section of the HTML. Then at some point I grab content (HTML + Javascript) from an outside source via `file_get_contents` and output it to the main page. This new output will pick up the CSS styles from the main page normally, but any Javascript code that relies on the ones loaded at the main will not work. Even if I put the Javascript needed inside a `document.ready` in the main page, it will still not work. Just to exemplify the code: ``` <html> <head> <link href="style.css" rel="stylesheet"> <script src="somejslib.js"></script> </head> <body> Some HTML here generated by PHP <?php $content = file_get_contents('http://whatever/page'); echo $content; ?> </body> ``` In the grabbed content I will have something like: ``` <div> <form> <input type="text" id="bla"> </form> </div> <script>$('#bla').datepicker({ somecodehere });</script> ``` The `datepicker` was included in the libs loaded in the main page, but will not work, no matter where I put this code. Any hints? P.S: the only way it DOES work is if I include - again - all the Javascript libs inside the new content, which of course is not a solution.
2016/03/11
[ "https://Stackoverflow.com/questions/35940057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440505/" ]
Strictly speaking all SQL statements should be terminated with a semicolon. i.e. ``` SELECT Example FROM Test1 ; SELECT Example FROM Test2 ; ``` In practice SQL Server only enforces this for certain query types, for now. Statements that precede CTEs and MERGEs are an example of this. From [MSDN](https://msdn.microsoft.com/en-us/library/ms177563.aspx): > > ; Transact-SQL statement terminator.Although the semicolon is not > required for most statements in this version of SQL Server, it will be > required in a future version. > > > Of course it doesn't help that the error message tells you to terminate the merge but doesn't mention the preceding query is also required. Try: ``` BEGIN TRANSACTION agcUpsertTran; MERGE AssetGroupClassification AS t .... ; ```
When you are executing your script under the visual studio editor in script file, at end of the script you need to add `;` after adding the semicolon VS will build the script successfully
45,499,152
This is my `advertisements` table: [![advertisements table](https://i.stack.imgur.com/YVK2b.png)](https://i.stack.imgur.com/YVK2b.png) And this is my `works` table: [![works table](https://i.stack.imgur.com/rU2ML.png)](https://i.stack.imgur.com/rU2ML.png) I want to find data from the `advertisements` table which has been clicked 12 hours ago, on recorded from `works` table, by the `add_id` column. **Work Model:** ``` <?php namespace App; use Illuminate\Database\Eloquent\Model; class Work extends Model { } ``` **Advertisement Model:** ``` <?php namespace App; use Illuminate\Database\Eloquent\Model; class Advertisement extends Model { // } ``` **Controller:** ``` public function myadd() { $clicked_add = Work::where('user_id', Auth::user()->id)->where('created_at', '>=', Carbon::now()->subDay())->get(); $adds = Advertisement::orderBy('id', 'desc')->take(5)->get(); return View::make('pages.add', compact("adds","clicked_add")); } ```
2017/08/04
[ "https://Stackoverflow.com/questions/45499152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6898181/" ]
First, you don't use the correct terminology. You didn't declare a inner class but a static nested class. > > Terminology: **Nested classes are divided into two categories**: static > and non-static. Nested classes that are declared static are called > **static nested classes**. Non-static nested classes are called **inner > classes**. > > > You could get accessible and useful information about terminology and how and why use nested classes on the [Java Oracle Nested Classes tutorial](https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html) : About your question : > > Well, Inner class is static, so I assume the above code implicitly > instantiates Question\_3\_4's instance ? > > > You don't need to instantiate the outer class to instantiate a nested class or says also a `static` nested class. Besides, the compiler will not instantiate the outer class for you if it was required but would emit a compilation error. Instantiating the outer class is required only in case of inner classes (no `static` nested class). For example remove the `static` modifier of the nested class and a compilation error will be produced for the `Question_3_4.Inner i = new Inner();` line as it requires to have an instance of the outer class to be instantiated. ``` public class Question_3_4 { public class Inner { private void doIt() { System.out.println("doIt()"); } } public static void main(String[] args) { Question_3_4.Inner i = new Inner(); ^--- error: non-static variable this cannot be referenced from a static context i.doIt(); } } ```
No. You don't need outer class reference to access static inner class. Static nested class is just like any another top level class and just grouped to maintain the relation. It is not at all a member of outer class. You can access it directly. > > Note: A [static nested class](https://docs.oracle.com/javase/tutorial/java/javaOO/nested.) interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience. > > > However in non static inner class, what you said is correct. > > A [nested class](https://docs.oracle.com/javase/tutorial/java/javaOO/nested.) is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. > > > To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: ``` OuterClass.InnerClass innerObject = outerObject.new InnerClass(); ```
4,083,848
What is the equivalent of Linux's /proc/cpuinfo on FreeBSD v8.1? My application reads /proc/cpuinfo and saves the information in the log file, what could I do to get similar information logged on FreeBSD? A sample /proc/cpuinfo looks like this: ``` processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 23 model name : Intel(R) Xeon(R) CPU E5420 @ 2.50GHz stepping : 8 cpu MHz : 2499.015 cache size : 6144 KB fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss nx lm constant_tsc pni ds_cpl bogomips : 5004.54 processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 23 model name : Intel(R) Xeon(R) CPU E5420 @ 2.50GHz stepping : 8 cpu MHz : 2499.015 cache size : 6144 KB fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss nx lm constant_tsc pni ds_cpl bogomips : 5009.45 ```
2010/11/03
[ "https://Stackoverflow.com/questions/4083848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115751/" ]
I don’t believe there is anything as detailed as Linux’s `/proc/cpuinfo`. Look into `sysctl hw` and `/var/run/dmesg.boot`. Most of the information like CPU speed and instruction sets should be in there somewhere. This is what I see (with a few uninteresting `hw.*` fields removed): ``` $ uname -sr FreeBSD 4.10-RELEASE $ grep -i cpu /var/run/dmesg.boot CPU: Pentium III/Pentium III Xeon/Celeron (448.97-MHz 686-class CPU) $ /sbin/sysctl hw hw.machine: i386 hw.model: Pentium III/Pentium III Xeon/Celeron hw.ncpu: 1 hw.byteorder: 1234 hw.physmem: 665989120 hw.usermem: 604614656 hw.pagesize: 4096 hw.floatingpoint: 1 hw.machine_arch: i386 hw.aac.iosize_max: 65536 hw.an.an_dump: off hw.an.an_cache_mode: dbm hw.an.an_cache_mcastonly: 0 hw.an.an_cache_iponly: 1 hw.fxp_rnr: 0 hw.fxp_noflow: 0 hw.dc_quick: 1 hw.ste.rxsyncs: 0 hw.instruction_sse: 0 hw.availpages: 162432 ``` (Note that on OpenBSD, the cpu speed is found in `hw.cpuspeed` instead of in dmesg.)
FreeBSD 11.2 `sysctl hw.model` Result: `hw.model: Intel(R) Xeon(R) CPU E5620 @ 2.40GHz`
48,046,814
Imagine you want to align a series of x86 assembly instructions to certain boundaries. For example, you may want to align loops to a 16 or 32-byte boundary, or pack instructions so they are efficiently placed in the uop cache or whatever. The simplest way to achieve this is single-byte NOP instructions, followed closely by [multi-byte NOPs](https://stackoverflow.com/a/36361832/149138). Although the latter is generally more efficient, neither method is free: NOPs use front-end execution resources, and also count against your 4-wide1 rename limit on modern x86. Another option is to somehow lengthen some instructions to get the alignment you want. If this is done without introducing new stalls, it seems better than the NOP approach. How can instructions be efficiently made longer on recent x86 CPUs? In the ideal world lengthening techniques would simultaneously be: * Applicable to most instructions * Capable of lengthening the instruction by a variable amount * Not stall or otherwise slow down the decoders * Be efficiently represented in the uop cache It isn't likely that there is a single method that satisfies all of the above points simultaneously, so good answers will probably address various tradeoffs. --- 1The limit is 5 or 6 on AMD Ryzen.
2018/01/01
[ "https://Stackoverflow.com/questions/48046814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149138/" ]
Let's look at a specific piece of code: ``` cmp ebx,123456 mov al,0xFF je .foo ``` For this code, none of the instructions can be replaced with anything else, so the only options are redundant prefixes and NOPs. **However, what if you change the instruction ordering?** You could convert the code into this: ``` mov al,0xFF cmp ebx,123456 je .foo ``` After re-ordering the instructions; the `mov al,0xFF` could be replaced with `or eax,0x000000FF` or `or ax,0x00FF`. For the first instruction ordering there is only one possibility, and for the second instruction ordering there are 3 possibilities; so there's a total of 4 possible permutations to choose from without using any redundant prefixes or NOPs. For each of those 4 permutations you can add variations with different amounts of redundant prefixes, and single and multi-byte NOPs, to make it end on a specific alignment/s. I'm too lazy to do the maths, so let's assume that maybe it expands to 100 possible permutations. What if you gave each of these 100 permutations a score (based on things like how long it would take to execute, how well it aligns the instruction after this piece, if size or speed matters, ...). This can include micro-architectural targeting (e.g. maybe for some CPUs the original permutation breaks micro-op fusion and makes the code worse). You could generate all the possible permutations and give them a score, and choose the permutation with the best score. Note that this may not be the permutation with the best alignment (if alignment is less important than other factors and just makes performance worse). Of course you can break large programs into many small groups of linear instructions separated by control flow changes; and then do this "exhaustive search for the permutation with the best score" for each small group of linear instructions. **The problem is that instruction order and instruction selection are co-dependent.** For the example above, you couldn't replace `mov al,0xFF` until after we re-ordered the instructions; and it's easy to find cases where you can't re-order the instructions until after you've replaced (some) instructions. This makes it hard to do an exhaustive search for the best solution, for any definition of "best", even if you only care about alignment and don't care about performance at all.
Depends on the nature of the code. Floatingpoint heavy code ======================== **AVX prefix** One can resort to the longer AVX prefix for most SSE instructions. Note that there is a fixed penalty when switching between SSE and AVX on intel CPUs [[1]](https://software.intel.com/en-us/articles/avoiding-avx-sse-transition-penalties)[[2]](https://stackoverflow.com/a/41349852/388614). This requires vzeroupper which can be interpreted as another NOP for SSE code or AVX code which doesn't require the higher 128 bits. **SSE/AVX NOPS** typical NOPs I can think of are: * XORPS the same register, use SSE/AVX variations for integers of these * ANDPS the same register, use SSE/AVX variations for integers of these
10,422,989
I am eager to know what happens to a object in .NET when it falls out of scope. Something like this: ``` class A { ClassB myObjectB = new ClassB(); } //what happens to object at this point here? ``` What happens in the memory? Does GC get called when it falls out of scope and loose it reference in the heap?
2012/05/02
[ "https://Stackoverflow.com/questions/10422989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529995/" ]
I find "falling out of scope" to be a much more C++-specific way of thinking of things, where at the end of a given scope an object with automatic storage is freed and has its destructor called. In the C# world, there's no "falling out of scope". Variables (read: names) exist in a certain scope, and that's it. The GC really has no concern for this; an object can be collected before the end of its name's scope even exits, or long afterwards depending on what references it and when the GC decides a collection is necessary. The two concepts should then be divorced and reasoned about separately. Scoping is all about names, whereas garbage collection cares only about the reachability of objects. When an object is no longer reachable from one of the known roots, it will be scheduled for collection.
If there's nothing referencing the object, it gets eventually collected by GC. The thing is, you can't predict WHEN exactly it will happen. You just know, it will happen.
21,726,396
I have the following string which is from an ajax response. ``` "<option value="1000133925">Abhishek</option> <option value="1000182033">FRESH</option> <option value="1000390154">Testing</option>" ``` I have another string of the same above format, i need to compare both the strings and remove duplicate values in the second string and then append the remaining options to select. I failed in creating a json object from the above string which will map like { '1000133925' : 'Abhishek', '1000182033' : 'FRESH'}. Please help me with this.
2014/02/12
[ "https://Stackoverflow.com/questions/21726396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1696497/" ]
I don't see why you insist on using regex, when you can do it using `jQuery` like: ``` var options = '<option value="1000133925">Abhishek</option><option value="1000182033">FRESH</option><option value="1000390154">Testing</option>'; $(options).filter(function(index, el){ //put here your condition for instance I have filtered odd values return (!isNaN(parseInt(this.value)) && parseInt(this.value)%2); }).appendTo("#your-select-element"); ```
A regex solution : ``` var obj = {}, m, r = /<option value="([^"]*)">([^<]*)<\/option>/g; while (m = r.exec(s)) obj[m[1]] = m[2]; ``` It builds ``` {1000133925: "Abhishek", 1000182033: "FRESH", 1000390154: "Testing"} ```
4,421
I have to drill a perfectly centred hole in the flat part of a cylinder.I don't know how to do but I thought something like this: I want to take a piece of wood and fix it at the base of the drill press and then drill a hole of the same diameter as the cylinder. Then put the cylinder in the hole and drill it. In this way all the holes will be centred. Is this a good idea? **EDIT:** The cylinder is 4 mm dia and 1.5 cm high.
2016/07/22
[ "https://woodworking.stackexchange.com/questions/4421", "https://woodworking.stackexchange.com", "https://woodworking.stackexchange.com/users/2494/" ]
I've done it as you suggest, and it works. Obviously, the dowel you're drilling has to be fairly short. You also have to make sure it's held securely so it doesn't spin in the wood that's holding it.
For small cylinders as described (4mm dia, 15mm long) the premise in your OP will work, but the drill press used needs to be accurate. My recommended execution of your idea: Assumes negligible play in drill press and use of good brad-point drill bits. Drill press table should be as close to chuck as will still allow the exchange of bits. Cut a piece of 18mm MDF about 100mm wide and 100mm shorter than your drill press table's diameter. Mark centre. Clamp down with centre mark at drill bit centre. Drill a 4mm hole to 2mm deep, and without unclamping drill your desired bore diameter right through the 18mm MDF. Unclamp, set aside and retain. This is the top half of your jig. Clamp a second piece of 18mm MDF to the drill press table (100mm longer than the first, which should equal your drill press table diameter). Clamp at very outermost available places. Bore a 4mm hole to 11mm depth, then drill a 2mm hole clear through the MDF. This second MDF chunk is the jig's lower half. It remains clamped in place until operations are complete. Blow out any dust from drilling, and place first cylinder in place. Place jig top half onto top of work, clamping in place using the extreme ends of the jig half. The two jig halves will compress the work from top and bottom, preventing rotation while drilling. Drill desired bore into work. Unclamp jig top half, remove work by poking up from below through the 2mmm hole. Blow out jig. Repeat. Since this is a very small object, go easy when drilling and don't try to hog it out all in one go. You'll get a good number of cycles out of the jig if you take care to remove and re-clamp gently.
47,229,802
Given a matrix, for example: ``` [[2 5 3 8 3] [1 4 6 8 4] [3 6 7 9 5] [1 3 6 4 2] [2 6 4 3 1]] ``` ...how to find the greatest sub-matrix (i.e. with most values) in which all rows are sorted and all columns are sorted? In the above example the solution would be the sub-matrix at (1,0)-(2,3): ``` 1 4 6 8 3 6 7 9 ``` and its size is 8.
2017/11/10
[ "https://Stackoverflow.com/questions/47229802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8915716/" ]
You could use recursion to get a maximised area that could fit below a given row segment, that itself has already been verified to be a non-decreasing value sequence. The found area will be guaranteed to stay within the column range of the given row segment, but could be more narrow and span several rows below the given row. The area that will be returned can then be extended one row upwards, with the width that area already has. If the segment can not be wider, then we will have found the maximum area that can be made from a subsequence of this segment (or the full segment) combined with rows below it. By filtering the best result from the results retrieved for all segments in all rows, we will have found the solution. To avoid repetition of recursive calculations that had already been done for exactly the same segment, memoisation can be used (direct programming). Here is the suggested code: ``` from collections import namedtuple Area = namedtuple('Area', 'start_row_num start_col_num end_row_num end_col_num size') EMPTY_AREA = Area(0,0,0,0,0) def greatest_sub(matrix): memo = {} # Function that will be called recursively def greatest_downward_extension(row_num, start_col_num, end_col_num, depth=0): # Exit if the described segment has no width if end_col_num <= start_col_num: return EMPTY_AREA next_row_num = row_num + 1 # Use memoisation: # Derive an ID (hash) from the segment's attributes for use as memoisation key segment_id = ((row_num * len(matrix[0]) + start_col_num) * len(matrix[0]) + end_col_num) if segment_id in memo: return memo[segment_id] # This segment without additional rows is currently the best we have: best = Area(row_num, start_col_num, next_row_num, end_col_num, end_col_num - start_col_num) if next_row_num >= len(matrix): return best next_row = matrix[next_row_num] row = matrix[row_num] prev_val = -float('inf') for col_num in range(start_col_num, end_col_num + 1): # Detect interruption in increasing series, # either vertically (1) or horizontally (0) status = (1 if col_num >= end_col_num or next_row[col_num] < row[col_num] else (0 if next_row[col_num] < prev_val else -1)) if status >= 0: # There is an interruption: stop segment # Find largest area below current row segment, within its column range result = greatest_downward_extension(next_row_num, start_col_num, col_num) # Get column range of found area and add that range from the current row size = result.size + result.end_col_num - result.start_col_num if size > best.size: best = Area(row_num, result.start_col_num, result.end_row_num, result.end_col_num, size) if col_num >= end_col_num: break # When the interruption was vertical, the next segment can only start # at the next column (status == 1) start_col_num = col_num + status prev_val = row[col_num] memo[segment_id] = best return best # For each row identify the segments with non-decreasing values best = EMPTY_AREA for row_num, row in enumerate(matrix): prev_val = -float('inf') start_col_num = 0 for end_col_num in range(start_col_num, len(row) + 1): # When value decreases (or we reached the end of the row), # the segment ends here if end_col_num >= len(row) or row[end_col_num] < prev_val: # Find largest area below current row segment, within its column range result = greatest_downward_extension(row_num, start_col_num, end_col_num) if result.size > best.size: best = result if end_col_num >= len(row): break start_col_num = end_col_num prev_val = row[end_col_num] return best # Sample call matrix = [ [2, 5, 3, 8, 3], [1, 4, 6, 8, 4], [3, 6, 7, 9, 5], [1, 3, 6, 4, 2], [2, 6, 4, 3, 1]] result = greatest_sub(matrix) print(result) ``` The output for the sample data will be: ``` Area(start_row_num=1, start_col_num=0, end_row_num=3, end_col_num=4, size=8) ```
One approach, which it sounds like you have tried, would be using brute force recursion to check first the entire matrix, then smaller and smaller portions by area until you found one that works. It sounds like you already tried that, but you may get different results depending on whether you check from smallest to largest sections (in which case you would have to check every combination no matter what) or largest to smallest (in which case you would still end up checking a very large number of cases). Another approach would be to create two matrices with the same dimensions as the original, where each slot in the matrix represents the gap between two numbers and the first slot in each row or column represents the gap above the first number in said row or column. You could fill the first matrix with ones and zeros to represent whether or not a matrix could be formed vertically (a 1 representation of a gap would mean that the number lower than the gap would be larger than the number above the gap) and the second with ones or zeros to represent a similar condition horizontally. You could use AND(a,b) (in other words a binary operation where only 1 1 maps to 1) for each value in the matrix to make a matrix that would essentially be AND(matrix1,matrix2), and then you could find the largest rectangle of ones in the matrix. Example matrix (smaller for simplicity and convenience): ``` [ 1 2 5 ] [ 4 9 2 ] [ 3 6 4 ] ``` Vertical matrix: a one in location L means that the number in position L is greater than the number directly above L, or that L is the top of the column (with brackets signifying that the first row will always fit the vertical conditions). ``` { 1 1 1 } [ 1 1 0 ] [ 0 0 1 ] ``` Horizontal matrix: a one in location L means that the number in position L is greater than the number directly left of L, or that L is the front of the row (leftmost point) (with brackets again signifying that the first row will always fit the vertical conditions). ``` {1} [ 1 1 ] {1} [ 1 0 ] {1} [ 1 0 ] ``` Vertical AND Horizontal (you could ignore the vertical-only and horizontal-only steps and do this at once: for each cell, put in a 0 if the number is larger than the number on its right or directly below it, otherwise put in a 1) ``` [ 1 1 1 ] [ 1 1 0 ] [ 0 0 0 ] ``` The largest rectangle would be represented by the largest rectangle of ones with the same indices as the original rectangle. It should be much easier to find the largest rectangle of ones. Hope this helps! I know I did not explain this very clearly but the general idea should be helpful. It is very similar to the idea you presented about comparing all i and i-1 digits. Let me know if it would help for me to do this for the example matrix you gave.
46,268,491
I have a Spring Boot `@Configuration` class that's located at `com.app.config` and a controller located at `com.app.controller` and my test (in the tests directory) is at `com.app.controller`. When I run it, the configuration class is never used. ``` package com.app.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @EnableWebMvc @ComponentScan("com.app") public class ValidationConfig { @Bean public Validator validator() { //The breakpoint here is never called! return new LocalValidatorFactoryBean(); } } ``` Test class: ``` import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.validation.Validator; @RunWith(SpringRunner.class) @ComponentScan({"com.app","com.app.config"}) public class TestAumController { //...elided... @Autowired private Validator validator; @Test public void testController() throws Exception { //..edlided... } } ```
2017/09/17
[ "https://Stackoverflow.com/questions/46268491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857025/" ]
`@ComponentScan` is for `@Configuration` classes. Try replacing that in your test class with `@SpringBootTest`, which loads and configures the application context
You can make the following changes. In Configuration file, add `@ComponentScan("Your Package path")` ``` import org.springframework.context.annotation.ComponentScan; @Configuration @EnableWebMvc @ComponentScan("com.app") public class ValidationConfig { ``` In Test File, add `@ContextConfiguration(classes = ConfigurationClass.class)` ``` import org.springframework.test.context.ContextConfiguration; @RunWith(SpringRunner.class) @ContextConfiguration(classes = ValidationConfig.class) public class TestAumController { ``` For more Info, You can refer this [link](https://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles).
63,677
When casting [Prayer](http://paizo.com/pathfinderRPG/prd/spells/prayer.html), you give your allies a bonus and your foes a penalty on most rolls. Now, assuming you get to choose who your allies and foes are, can a creature tell which one you've designated him? Example: I'm an evil cleric working with other evil characters. I decide they've outlived their usefulness, so I cast Prayer to give them a penalty hoping they die in combat (or I kill them, whatever). My question is if they can tell that I'm giving them a penalty, rather than a bonus since they think I'm their ally (and I was until recently). Conversely, would foes realize I blest them and maybe not hit me in the face?
2015/06/17
[ "https://rpg.stackexchange.com/questions/63677", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/23196/" ]
A creature doesn't know if it's affected by spell unless the spell says so; likewise, a creature doesn't know *how* a spell is affecting it unless the spell says so -------------------------------------------------------------------------------------------------------------------------------------------------------------------- A creature can identify the spell *prayer* as the spell's being cast with a [Spellcraft](http://www.d20pfsrd.com/skills/spellcraft) skill check (DC 18), and, if a creature also has a way to sense the spell *prayer* in the first place (e.g. the creature uses the spell [*detect magic*](http://www.d20pfsrd.com/magic/all-spells/d/detect-magic)), a creature can identify the spell *prayer* after the spell's in place with a [Knowledge (arcana)](http://www.d20pfsrd.com/skills/knowledge) skill check (DC 23).1 However, lacking explicit text that says otherwise, creatures targeted by a spell don't know they've been targeted by a spell, nor do affected creatures know they're affected by a spell. If that seems a bit unfair, *it is*, but, also, most of the time *it won't matter.* If a target knows it's been targeted or if an affected knows it's affected, that's fine because the target or the affected isn't likely long for this world anyway. However, in a campaign comprised of backstabbing PCs, playing from the beginning that many spells have no obvious effect *at all* is probably a good idea. ### The GM *can* implement setting-dependent rules governing casting a spell or a spell's effects It's not like the spell is [*astral projection*](http://paizo.com/pathfinderRPG/prd/spells/astralProjection.html#astral-projection) or anything, so here's the whole thing: > > ### [Prayer](http://www.d20pfsrd.com/magic/all-spells/p/prayer) > > > **School** enchantment (compulsion) [mind-affecting]; **Level** cleric 3, paladin 3 > > **Casting Time** 1 standard action > > **Components** V, S, DF > > **Range** 40 ft. > > **Area** all allies and foes within a 40-ft.-radius burst centered on you > > **Duration** 1 round/level > > **Saving Throw** none; **Spell Resistance** yes > > > You bring special favor upon yourself and your allies while bringing disfavor to your enemies. You and each of your allies gain a +1 luck bonus on attack rolls, weapon damage rolls, saves, and skill checks, while each of your foes takes a –1 penalty on such rolls. > > > Thus, without further information, if the GM says that the spell's somatic components include giving each ally a thumbs up and each opponent a thumbs down, then it'll be obvious to all what the caster's doing, but if the GM says a caster has a little heads-up display in which all of the various allies, enemies, and, perhaps, other participants appear and the caster mentally ticks off who is in each category... > > ### Example > > > > ``` > Character Ally Enemy > Abel the Wizard X — > Bob the Fighter X — > Orcs 1 through 59 — X > Orc 60 X — > Orcs 61-87 — X > Orc Warlord — X > Restov the Nightblade X — > That Dude over There — — > > ``` > > (Only the caster would see this.) > > > ...then there's no way for those affected to know, short of the obvious: trial and error, an effect like the spell *detect magic*, and so on. A DM could also say, for example, that targeted creatures briefly have yellow exclamation marks above their heads (or equivalent masses) or that affected creatures give off non-illuminating glows (e.g. red for enemies and blue for allies), but this is well beyond many spells' typical descriptions. A GM who deliberately adds such indicators is giving away many spells' targets and, possibly, their effects, but that might be exactly what such a GM desires.2 --- **1** There's also the [hostile tingle](http://www.d20pfsrd.com/magic#TOC-Saving-Throw) that a creature feels when it succeeds on a saving throw *versus* a targeted spell (which the spell *prayer* is not). More information on detecting targeted spells is covered in [this related question](https://rpg.stackexchange.com/q/60466/8610). **2** In an *Advanced Dungeons and Dragons, Second Edition* game in which I played a wizard, the DM house ruled that the spell *teleport* emitted a loud pop both upon departure and arrival, making teleport ambushes not impossible but more difficult. Without a cleric in the party to cast *silence, 15-ft. radius* beforehand, we were limited in the usability of *teleport* to murder our foes. I didn't mind; back then, the spell *teleport* was a lot more dangerous to the caster, having the possibility of killing the caster outright.
First of all, I'm going to assume you are looking for an in character answer, as it will be fairly obvious to the players right away that they have to subtract from their dice rolls instead of add. (And if it's not obvious to them, things are going to get really confusing.) **But can a creature, in game, tell that they have been blessed with suck?** Dice rolls are a purely OOC mechanic, your characters have no idea that somebody rolled a 19 and still missed, they would have to go purely by the fact that they are having a harder time fighting, and if they notice or not will largely depend on how you explain a miss. "You attack the goblin and you miss" is not going to trigger any warning bells from a creature. "You attack the goblin, but you fail to injure it because your hand slips and you almost lose your sword" is starting to sound a lot more like something fishy is up. On the flipside, that Goblin might realize that he is suddenly lucky, but I highly doubt that he is going to be able to tell that is -your- doing. As far as any creature fighting you is concerned, you are an enemy, they don't know you are the reason they are suddenly lucky unless you can somehow telepathically explain it to them. It seems more likely that enemies who suddenly find your "friends" blessed with suck would assume that their own deity is favouring them.
192,425
I'm trying to repair an old circuit based on the Micro-controller S87C751 interfaced with an inductive proximity sensor similar to one already posted here [![NPN Sensor](https://i.stack.imgur.com/libiH.jpg)](https://i.stack.imgur.com/libiH.jpg) The sensor is powered +24V. I followed the circuit paths from the sensor until the input of the Micro controller and i found it wired in the following way: [![enter image description here](https://i.stack.imgur.com/UnL8V.png)](https://i.stack.imgur.com/UnL8V.png) The uC is powered +5V. As you can notice, the circuit designer used a PNP transistor combined with an NPN transistor. My questions are: 1/ What is the purpose of this transistors combination ? 2/ Is it a level shifter ? if yes, is it really necessary ? As i already seen Arduino interfaced with such sensors with only a pull-up resistor not matter power source of the sensor. 3/ During simulation in Proteus ISIS, i simulated the inductive proximity sensor as a switch. the circuit didn't work, and i get always 0V at the uC input, what could be wrong with my drawing? Thank you in advance for your help. **EDIT:** * I plan to use the following level shifter using two NPN TRs instead of an PNP-NPN TRs, is it possible ? * I would like to include an LED in this circuit that gets ON when there is Metal detected to save one of the pins of the uC, how can this be possible? i tried including it however a voltage drop will occurs so i'll not get the 5V output. [![2 NPN level shifter](https://i.stack.imgur.com/JJCAP.png)](https://i.stack.imgur.com/JJCAP.png)
2015/09/27
[ "https://electronics.stackexchange.com/questions/192425", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/59110/" ]
I'm almost1 certain that in your scenario you can connect the ground of USB to the ground of the wall-wart and not worry about it. Wall-warts2 have isolation transformers. Its ground is floating. When you connect the floating ground to the other ground, they will equalize, and there will be no current between the grounds because of the difference in ground potential. Many of the self-powered USB devices have USB ground connected to the external power ground. 1 "Almost", because I have to go by a verbal description rather than a schematic or a block diagram. 2 Properly made wall-warts. I'm not talking about the fake ones from China on eBay.
You cannot have two ground references for one IC (or connected circuit). You need to make sure that all the grounds are at the same potential. If you cannot guarantee that they will be at the same potential you need to implement isolation of the data and ground. If you only need the USB for simple comms you could possibly keep the USB interface IC running on USB power and just isolate the comms.
9,030,446
I accidentally unzipped files into a wrong directory, actually there are hundreds of files... now the directory is messed up with the original files and the wrongly unzip files. I want to pick the unzipped files and remove them using shell script, e.g. ``` $unzip foo.zip -d test_dir $cd target_dir $ls test_dir | rm -rf ``` nothing happened, no files were deleted, what's wrong with my command ? Thanks !
2012/01/27
[ "https://Stackoverflow.com/questions/9030446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1165196/" ]
The following script has two main benefits over the other answers thus far: 1. It does not require you to unzip a whole 2nd copy to a temp dir (I just list the file names) 2. It works on files that may contain spaces (parsing `ls` will break on spaces) --- ``` while read -r _ _ _ file; do arr+=("$file") done < <(unzip -qql foo.zip) rm -f "${arr[@]}" ```
Compacting the previous one. Run this command in the /DIR/YOU/MESSED/UP ``` unzip -qql FILE.zip | awk '{print "rm -rf " $4 }' | sh ``` enjoy
3,817,926
I want to use django template to process plain text file, and tried this: ``` from django.template import loader, Context t = loader.get_template('my_template.txt') ``` however, it works for this: ``` from django.template import loader, Context t = loader.get_template('my_template.html') ``` Can we load txt files using django template loader? how? thanks.
2010/09/29
[ "https://Stackoverflow.com/questions/3817926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/311884/" ]
As @Seth commented I don't see any reason why this shouldn't work. Django doesn't care about the extension of the file. You can very well load `my_template.foo`. Check the following: 1. The file is indeed present where it should be. If it is in a subdirectory then you'll have to use `loader.get_template('<subdirectory>/my_template.txt')` where subdirectory is the name of the directory. 2. Check if you have an app name. It is common to locate all templates for an app in a directory with the app's name. 3. As @Seth said double check your `TEMPLATE_DIRS` setting. The template should be inside one the directories in this list.
I would leave this for some one else to answer as I am not very comfortable with Django. How ever, if you are interested in templates and plain text processing, why don't you look at slew of other products available within python. * <https://stackoverflow.com/questions/98245/what-is-your-single-favorite-python-templating-engine> * <http://wiki.python.org/moin/Templating>
62,136,974
I'm giving mainteinence to an app with Angular 7.0.7 and Node 10.20.1. I were working fine, I installed long ago Sweetalert and the plugin was working fine. Yesterday my PC restarted and when I run `ng serve` I got this error > > ERROR in node\_modules/sweetalert2/sweetalert2.d.ts(277,39): error > TS1005: ',' expected. > node\_modules/sweetalert2/sweetalert2.d.ts(277,68): error TS1011: An > element access expression should take an argument. > node\_modules/sweetalert2/sweetalert2.d.ts(277,69): error TS1005: ';' > expected. node\_modules/sweetalert2/sweetalert2.d.ts(277,70): error > TS1128: Declaration or statement expected. > node\_modules/sweetalert2/sweetalert2.d.ts(277,82): error TS1005: '(' > expected. > > > **My package.json is this** ``` { "name": "frontend", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve --proxy-config proxy.conf.json", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "test2": "ng test" }, "private": true, "dependencies": { "@angular/animations": "^7.0.4", "@angular/cdk": "^7.3.0", "@angular/common": "~7.0.0", "@angular/compiler": "~7.0.0", "@angular/core": "~7.0.0", "@angular/forms": "~7.0.0", "@angular/http": "~7.0.0", "@angular/material": "^7.3.0", "@angular/material-moment-adapter": "^9.2.3", "@angular/platform-browser": "~7.0.0", "@angular/platform-browser-dynamic": "~7.0.0", "@angular/router": "~7.0.0", "@fortawesome/fontawesome-free": "^5.13.0", "@sweetalert2/theme-material-ui": "^3.1.4", "bootstrap": "^4.2.1", "core-js": "^2.5.4", "devextreme": "^18.2.5", "flagkit-web": "0.0.3", "font-awesome": "^4.7.0", "hammerjs": "^2.0.8", "intro.js": "^2.9.3", "ionicons": "^4.5.5", "moment": "^2.25.3", "ngx-bootstrap": "^5.5.0", "ngx-toastr": "^10.0.4", "pixeden-stroke-7-icon": "^1.2.3", "rxjs": "~6.3.3", "sweetalert2": "^9.14.0", "xlsx": "^0.15.6", "zone.js": "~0.8.26" }, "devDependencies": { "@angular-devkit/build-angular": "~0.10.0", "@angular/cli": "~7.0.5", "@angular/compiler-cli": "~7.0.0", "@angular/language-service": "~7.0.0", "@types/intro.js": "^2.4.6", "@types/jasmine": "~2.8.8", "@types/jasminewd2": "~2.0.3", "@types/node": "~8.9.4", "codelyzer": "~4.5.0", "jasmine-core": "~2.99.1", "jasmine-spec-reporter": "~4.2.1", "karma": "~3.0.0", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "~2.0.1", "karma-jasmine": "~1.1.2", "karma-jasmine-html-reporter": "^0.2.2", "pe7-icon": "^1.0.4", "protractor": "~5.4.0", "ts-node": "~7.0.0", "tslint": "~5.11.0", "typescript": "~3.1.6" } } ``` I did a lot of tricks * Removed and installed all node\_modules with `npm install`, didn't works * I downgraded typescript to 2.X version, didn't works * Reinstalled only sweetalert with `npm uninstall sweetalert2 && npm install sweetalert2`, didn't works * I ran `npm audit fix`, I received a lot of problems with the app, didn't works I went to the sweetalert file, on the error line and I found this code ``` /** * Provide an array of SweetAlert2 parameters to show multiple popups, one popup after another. * * @param steps The steps' configuration. */ function queue<T>(steps: readonly (SweetAlertOptions | string)[]): Promise<T>; ``` In all cases, is the same error... What is wrong?
2020/06/01
[ "https://Stackoverflow.com/questions/62136974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6605722/" ]
Hello I also started facing the same issue.Found a fix for the meantime till a better solution comes.I just downgraded it.Check and see if it works for you. npm install sweetalert2@v9.11.0
The problem most probably comes from a mismatch on the typescript version needed by `sweetalert2` and the one of your project. On your package.json you have the following: ``` "sweetalert2": "^9.14.0" // Wants any version like 9.X where X must be >= 14 "typescript": "~3.1.6" // Wants any version like 3.1.Y where Y must be >= 6 ``` Check your package-lock.json to be sure what is the sweetalert2 version that is locked by your project (if you have no lock, it will be `9.17.2`). You can go then to `https://github.com/sweetalert2/sweetalert2/blob/v[THE VERSION]/package.json` to check the version needed by typescript. If you see `9.14.0`, they expect as well typescript version ^3.5
51,330,059
I'm new to VBA so this is probably a very obvious mistake. To keep it short, I am trying to delete rows based on two criteria: In Column A, if they have the same value (duplicate) and in Column B, the difference is *less than* 100, then one row is deleted from the bottom. Example data: ``` Column A Column B 1 300 1 350 SHOULD be deleted as second column diff. is <100 compared to row above 2 500 2 700 Should NOT be deleted as second column diff. is not <100 ``` Here is the code I have come up with: ``` Sub deduplication() Dim i As Long Dim j As Long Dim lrow As Long Application.ScreenUpdating = False With Worksheets("Sheet1") lrow = .Range("A" & .Rows.Count).End(xlUp).Row For i = lrow To 2 Step -1 For j = i To 2 Step -1 If .Cells(i, "A").Value = .Cells(j, "A").Value And .Cells(i, "B").Value - .Cells(j, "B").Value < 100 Then .Cells(i, "A").EntireRow.Delete End If Next j Next i End With End Sub ``` This largely works, but only if the second criterion is *greater than* (>) rather than *less than* (<). When it is less than, it deletes **every row**. What am I doing wrong? Is there an easy fix? Thank you
2018/07/13
[ "https://Stackoverflow.com/questions/51330059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10024322/" ]
Sticking to the format of your code, you can do this using one `For` loop as well. ``` For i = lrow To 3 Step -1 If .Cells(i, "A") = .Cells(i - 1, "A") And (.Cells(i, "B") - .Cells(i - 1, "B")) < 100 Then .Cells(i, "A").EntireRow.Delete End If Next i ```
Why not to use the built-in command: ``` Worksheets("Sheet1").Range("$A:$A").RemoveDuplicates Columns:=1, Header:=xlYes ``` [Range.RemoveDuplicates Method (Excel)](https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-removeduplicates-method-excel?f=255&MSPPError=-2147217396)
59,913,778
I have been coding for a while in Visual Studio with visual basic and there was an option to autoformat code at the same time you were coding. I know i can format it in Android Studio with CTRL+ALT+L but is there any option so the software do it automatically? Thanks.
2020/01/25
[ "https://Stackoverflow.com/questions/59913778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10725028/" ]
All i had to do was add an initContainer and mount the Configmaps to /tmp and have it moved to the necessary path /var/opt/jfrog/artifactory/etc/, instead of mounting the configmap in the volumemount /var/opt/jfrog/artifactory. Reason: ConfigMaps are ReadOnly hence /etc was and would always be Readonly. ``` initContainers: - name: "grant-permissions" image: "busybox:1.26.2" securityContext: runAsUser: 0 imagePullPolicy: "IfNotPresent" command: - 'sh' - '-c' - 'mkdir /var/opt/jfrog/artifactory/etc ; cp -vf /tmp/artifactory* /var/opt/jfrog/artifactory/etc ; chown -R 1030:1030 /var/opt/jfrog/ ; rm -rfv /var/opt/jfrog/artifactory/lost+found' volumeMounts: - mountPath: "/var/opt/jfrog/artifactory" name: artifactory-volume - name: bootstrap mountPath: "/tmp/artifactory.config.import.yml" subPath: bootstrap readOnly: false - name: artifactory-system-properties mountPath: "/tmp/artifactory.system.properties" subPath: artifactory.system.properties readOnly: false ``` then mount the volume to the main container that runs artifactory ``` containers: - name: artifactory image: "registry.eu02.dsg.arm.com/sqa/artifactory-pro:6.17.0" volumeMounts: - name: artifactory-volume mountPath: "/var/opt/jfrog/artifactory" ```
As explained [here](https://serverfault.com/questions/906083/how-to-mount-volume-with-specific-uid-in-kubernetes-pod), [here](https://stackoverflow.com/questions/46974105/kubernetes-setting-custom-permissions-file-ownership-per-volume-and-not-per-p?rq=1), [here](https://github.com/moby/moby/issues/2259) and [here](https://github.com/kubernetes/kubernetes/issues/2630) you cannot change the permission of mounted directory. As a work around you can use `initContainer` which runs before the actual container to change the permission to the directory: ``` initContainers: - name: volume-mount image: busybox command: ["sh", "-c", "chown -R 1030:1030 <your_directory>"] volumeMounts: - name: <your volume> mountPath: <your mountPath> ```
5,327,803
I would like to know whether its possible to execute different http protocol methods like GET,POST,HEAD,etc manually without using browser either through command prompt or using any programming language? If yes, then how to do this? Please enlighten !!!
2011/03/16
[ "https://Stackoverflow.com/questions/5327803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194476/" ]
Almost every language has at least one mechanism for performing HTTP requests. From the command line you can use tools such as wget and cURL.
It's possible, using php's header() functions or using telnet and typing out the headers manually.
39,975,565
IMAGE - ![Input, Scenarios and expected output](https://i.stack.imgur.com/Bo7GL.png) Please refer to the image for better understanding of the scenarios - For input from table I have 5 columns COL1,COL2,COL3,COL4,COL5 - Scenario 1, 2, 3, 4 explains the types of input I will receive. The Value in Col 4 can vary(for example 31-35 or 36-39 for same value in Col1) -The column SUM is summation of values for all numbers in VALUE column of each scenario, and that has to be populated in all the rows. Like 50 in each cell for Scenario 1 under Column (SUM) The requirement - Summation to get the Value ex- 50 and then display all the rows (3-20) + Column G in the out put table So input table has 17 rows 5 Columns(B,C,D,E,F) Output should have 17 rows 6 columns(B,C,D,E,F,G) I could do the summation by grouping and using aggregate transformation in Informatica but I cannot display all the rows as grouping returns one row.
2016/10/11
[ "https://Stackoverflow.com/questions/39975565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6997912/" ]
Do an aggregated sum based on the columns B, C, and D and then use a Joiner transformation to join your aggregated output (4 rows) with original source rows (17 rows). Do not forget to use sorted input in the joiner, which is mandatory for this kind of self join. ``` Source ------> Sorter ----> Aggregator -----> Joiner ----->Target | ^ |________________________________| ``` Configure the joiner for normal join on the columns B, C and D
Why don't you just use the `SUM(Value) OVER (PARTITION BY COL1, ..., COLN) AS ValueSum` analytical functionality in Netezza? All you need to do is to define how to partition the sums. Read more here: <https://www.ibm.com/support/knowledgecenter/SSULQD_7.2.1/com.ibm.nz.dbu.doc/c_dbuser_report_aggregation_family_syntax.html>
98,216
Introduction ------------ I defined the class of antsy permutations in [an earlier challenge](https://codegolf.stackexchange.com/questions/97217/antsy-permutations). As a reminder, a permutation **p** of the numbers from **0** to **r-1** is antsy, if for every entry **p[i]** except the first, there is some earlier entry **p[i-k]** such that **p[i] == p[i-k] ± 1**. As a fun fact, I also stated that for **r ≥ 1**, there are exactly **2r-1** antsy permutations of length **r**. This means that there is a one-to-one correspondence between the antsy permutations of length **r** and the binary vectors of length **r-1**. In this challenge, your task is to implement such a correspondence. The task -------- Your task is to write a program or function that takes in a binary vector of length **1 ≤ n ≤ 99**, and outputs an antsy permutation of length **n + 1**. The permutation can be either 0-based of 1-based (but this must be consistent), and the input and output can be in any reasonable format. Furthermore, different inputs must always give different outputs; other than that, you are free to return whichever antsy permutation you want. The lowest byte count wins. Example ------- The (0-based) antsy permutations of length 4 are ``` 0 1 2 3 1 0 2 3 1 2 0 3 1 2 3 0 2 1 0 3 2 1 3 0 2 3 1 0 3 2 1 0 ``` and your program should return one of them for each of the eight bit vectors of length 3: ``` 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 ```
2016/11/01
[ "https://codegolf.stackexchange.com/questions/98216", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/32014/" ]
JavaScript (ES6), 52 bytes ========================== ``` v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse() ``` Test it out: ```js f=v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse() g=v=>console.log(f((v.match(/[01]/g)||[]).map(x=>+x))) ``` ```html <input oninput="g(this.value)" value="010"> ``` ### Explanation This takes advantage of the fact that when an antsy permutation is reversed, each item is either 1 more than the maximum of the previous low entries, or 1 less than the minimum of the previous high entries. By denoting a higher item as a `0` and a lower item as a `1`, we can create an exact one-to-one correspondance between the antsy permutations of length **n** and the binary vectors of length **n - 1**. The best I could do with Dennis' technique is ~~57~~ 51 bytes: ``` v=>v.reduce((x,n)=>[...x.map(i=>i+n),!n*++j],[j=0]) v=>v.map(n=>x=[...x.map(i=>i+n),!n*++j],x=[j=0])&&x ``` xnor's solution is 56 (saved 1 byte thanks to @Neil): ``` l=>[1,...l].map((x,i)=>i*!x+eval(l.slice(i).join`+`||0)) ```
Haskell, 40 bytes ----------------- ```haskell foldl(\r a->map(+0^a)r++[a*length r])[0] ``` [Dennis's Python solution](https://codegolf.stackexchange.com/a/98231/20260) golfs wonderfully in Haskell with `map` and `fold`. It's shorter than my attempts to port my [direct entrywise construction:](https://codegolf.stackexchange.com/a/98246/20260) ```haskell f l=[i*0^x+sum(drop i l)|(i,x)<-zip[0..]$0:l] f l=[a+c-b*c|(a,c,b)<-zip3(scanr(+)0l)[0..]$0:l] ```
157,800
What technologies (hardware/software) are available for streaming audio in realtime (with some latency, of course) over a Wifi network? Although I'm using mostly Macs, I would like something that any client can access (especially smart phones that can access Wifi).
2010/06/28
[ "https://superuser.com/questions/157800", "https://superuser.com", "https://superuser.com/users/4952/" ]
[Subsonic](http://www.subsonic.org/pages/index.jsp) can stream over WiFi or the internet. I have it running at home so I can listen to my music over the air from work on my PC or from my Android phone, but there is also an iPhone app.
For me: ices + icecast on the ubuntu server side; any stream player on the client side (e.g. XiiaLive Lite on the Android)
60,006,524
I want to replace part of the string with asterisk (\* sign). How can I achieve that? Been searching around but I can't find a solution for it. For example, I getting 0123456789 from backend, but I want to display it as \*\*\*\*\*\*6789 only. Please advise. Many thanks.
2020/01/31
[ "https://Stackoverflow.com/questions/60006524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3180690/" ]
try using replaceRange. It works like magic, no need for regex. its replaces your range of values with a string of your choice. ``` //for example prefixMomoNum = prefs.getString("0267268224"); prefixMomoNum = prefixMomoNum.replaceRange(3, 6, "****"); //Output 026****8224 ```
You can easily achieve it with a `RegExp` that matches all characters but the last `n` char. Example: ``` void main() { String number = "123456789"; String secure = number.replaceAll(RegExp(r'.(?=.{4})'),'*'); // here n=4 print(secure); } ``` Output: `*****6789` Hope that helps!
165,949
I noticed the following today: [Mono at the PDC 2008](http://tirania.org/blog/archive/2008/Oct-01-1.html)? > > My talk will cover new technologies that we have created as part of Mono. Some of them are reusable on .NET (we try to make our code cross platform) and some other are features that specific to Mono's implementation of the CLI. > > > Posted by [Miguel de Icaza](http://tirania.org/blog/) on 01 Oct 2008 Does anybody know what type of new technologies he is refering too? Sounds like a great talk [**UPDATE**] [Here](http://channel9.msdn.com/pdc2008/PC54/) is the video of Miguel's talk * [Mono's SIMD Support: Making Mono safe for Gaming](http://tirania.org/blog/archive/2008/Nov-03.html) * [Static Compilation in Mono](http://tirania.org/blog/archive/2008/Nov-05.html) * [Unity on Linux, First Screenshots](http://tirania.org/blog/archive/2008/Nov-14.html)
2008/10/03
[ "https://Stackoverflow.com/questions/165949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5147/" ]
Looking at the [roadmap](http://www.mono-project.com/Mono_Project_Roadmap), maybe the new JIT/IL implementation that they're quite proud of; could be the C# Evaluation API / C# Shell. However, I suspect we'll have to wait for PDC to find out... Many of the roadmap items are (quite reasonably) like-for-like comparable with MS equivalents - but maybe they've sneaked in a few extras on the quiet ;-p
[Here](http://www.mono-project.com/Release_Notes_Mono_2.0) is more details about Mono 2.0
453,551
I'm curious about the use of the famous British plural verb form with a group noun¹ *in a contraction*. The general custom for the plural is discussed [here](https://english.stackexchange.com/questions/331377/british-mass-nouns-versus-american-count-nouns) and [here](https://english.stackexchange.com/questions/76448/pronouns-for-collective-nouns-british-and-american) but those don't call out contractions. England football fans [are currently singing the following](https://www.bbc.co.uk/news/uk-england-44711734) to the tune of *September* by Earth, Wind, and Fire: > > Woah, England are in Russia, > > Woah, drinking all your vodka, > > Woah, England's going all the way! > > > Now, it's a football song, not high poetry, but note that in the above, the first line uses ***England are*** but the last line uses ***England's***. Unless we magically decide that the first England is the team but the second England is the country, that's...interesting. The plural contraction is really awkward: * England're going all the way * Family're hard work sometimes * The group're on it ...and as we know, awkwardness tends to get smoothed out of language.[citation needed] ;-) Is this just a fudge to make the song's meter work? Or is it a deeper pattern to use the singular form in a contraction even when using the plural form otherwise, perhaps because of the awkwardness? Sadly Google Ngrams won't let me look for *England is going vs. England are going* (and *England is vs. England are* is too general) and in any case, I'd be flooded with American English results. Trying to search [Hansard](https://api.parliament.uk/historic-hansard/index.html), unfortunately Google Search treats the `'` as a space. I can't use my own instinct on this and am having trouble coming up with other examples to look for: I'm an English/American dual national who spent 30 years growing up in the U.S. reading British novels and watching British television on PBS, who's been back in the UK for 18 years. So my dialect is mid-Atlantic and horribly confused. :-) --- ¹ E.g. *the team **are*** vs. American English's *the team **is*** for nouns representing groups of people (roughly; there's lots of nuance).
2018/07/06
[ "https://english.stackexchange.com/questions/453551", "https://english.stackexchange.com", "https://english.stackexchange.com/users/15679/" ]
"England **are** in Russia," because the "guys from England" are in Russia, not the country. "**England's** going all the way" because the team (England) is, not the members individually.
I am Canadian and our school taught that: Nouns like team, group, family, class etc are a singular entity and were therefore treated as such. However I watch some British television and they repeatedly say things like "The team were riding on their new bus" rather than "The team was riding on it's new bus." Of course this is easily resolved by adding the word "members" to team. I always thought that Canada taught "proper" English so it is hard to get used to this.
235,296
Determining genetic fatherhood is very important in my worldbuilding experiment for lots of reasons, one being succession, but regardless it's the genetic component that's important But it's possible that people don't know who the father is of their child as well. Note that this is *not a medieval European world*. I specified tech for a reason as that's the only concept that carries over. The concepts of European royalty or culture really don't apply at all. Given the idealized restrictions below, is there anything that can be done with medieval level technology that can determine with near 0% false positive who is the father given a set known amount of candidates, *or* if there is a false positive, you know there's a false positive and the test is still useful? * Medieval level tech, is anything that was already available or could reasonably be available given aristocratic resources and modern knowledge *quickly* as in not 200 years from then (so you couldn't easily create microelectronics, you could however manufacture a spinning device with spinning glass tubes full of liquids with cork caps, even if it had to be manually turned by a person, as an example). * A false positive is when a *single* candidate is tested positive for being the father, but it wasn't them. When more than one candidate tests positive, it's not a false positive, that's inconclusive. * This is not a magic world. * This genetic fatherhood. * Assume neither candidates nor mother lie in this scenario. * All candidates and mother are cooperative. * The father can be guaranteed to be in the list of candidates. * Man-power is not much of an issue, though I don't know if it's relevant. * Test has to use medieval level technology, so assume you can make glass, work iron etc... * Despite having medieval tech, this does not take place in medieval Europe, there's no need to tie customs there to an answer. * A long the same lines, the test can be used along side *reasonable* original societal customs to aid testing. Maybe there's an invariant in society that means X can't be the father etc... But this can't prohibit non-monogamous relationships in general, otherwise the problem basically solves itself. * The test has to be *useful*. So maybe you could use things like phenotypical traits, but if it mostly always boils down to a few people anyway, and barely ever narrows it down, it's not useful. Useful would be something like 30-50% of the time you can make a pretty strong assertion of the father under some average bounds of number of candidates (like 5 or less). * Test has to have a low false positive rate. If it only works 50%-ish the time, then fine, but those times it better be pretty accurate. * Alternatively, as long as it's still useful, as long as you *know* there's a false positive, so you can call the test "failed", that also works. * The test can take long periods of time, but *ideally* (not a hard requirement) no more than 5 years. * The test can assume some medical knowledge we know today, such as blood types. * If it were possible to do limited genetic testing with said medieval technology, that would be a reasonable solution. * Assume everyone are historically from the same place, so there's no "obvious" physical markers with respect to people from two completely different ethnic backgrounds making this work some significant amount of time. * near 0% does not mean 0%, so 2% false positive may be acceptable, I didn't want to pin point a specific number. EDIT: * Phenotypical Book-keeping is possible, as in physically recording physical phenotypes that can be observed for each individual, from multiple generations prior (so you know a set number of specific phenotypes from parents of each individual, and parents of parents, and so on and so forth for several generations, and those people don't need to be alive for you to know this information, it's recorded). EDIT2: I have a new point that may help that didn't violate the above (which means this isn't really a "new rule", rather it serves to help answerers), but people are getting real stuck on way to euro centric world view of things, to the point where the top voted question earlier quite blatantly violates my entire question and doesn't answer it at all, plus assuming a marriage structure and civilization wide monogamy, or assuming that if there isn't monogamy it must be happening the same day constantly. * Both the mother and men know who and when they had relations with and **when** (assume this knowledge is always accessible, as if they recorded it). * When the father is ambiguous, it's not very common to have had relations with multiple different partners within the same day, and also not that common within the same week. The chance of different partners increases with time period when the father is ambiguous. If time can be used, there are accurate records to help.
2022/09/08
[ "https://worldbuilding.stackexchange.com/questions/235296", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/39866/" ]
Depending on when you need the test to be done by, you say "no more than 5 years" and if knowledge is as functionally unrestricted as you're saying, while *only* technology is restricted... Using precise timing, the list of candidates can be constrained so that we might be able to use [uncommonly known inheritable traits](https://www.ancestry.com/c/traits-learning-hub) like [hair thickness](https://www.ancestry.com/c/traits-learning-hub/hair-thickness), [birth weight](https://www.ancestry.com/c/traits-learning-hub/birth-weight), [finger length](https://www.ancestry.com/c/traits-learning-hub/finger-length) and [bitter taste sensitivity](https://www.ancestry.com/c/traits-learning-hub/bitter-taste-sensitivity), all assessible by the age of 5, to pin down the father?
Medieval and older systems what was used: 1. woman found with a man who was not their husband was banished. 2. woman found with a man who was not their husband was stoned to death. 3. man found with a married woman was castrated. 4. harems; married women were prohibited from meeting men, all work where a man was needed was done by castrated males. 5. harems; all contacts of a wife with a man was noted by first wife/castrated slave. Pregnancy if there was no record in book was punished by death 6. harems; any man who enter harem area and was not castrated was punished by castration/death 7. faith - any contact between unmarried people is a sin punished by death 8. social - women need care from men and other women after birth. If a woman was found with another man than her husband she would not have this support and was treated as a lowest cast person. All of above was used, in many mixes, first notes are Babylon times around 3000BC. As you see 7 and 8 are used till today in Christian related countries, 4, 5, 6, 7 and 8 in Islamic related countries. Most was common in use till end of XIX century in almost whole world. To be honest, most of patriarchal system rules are for determining who the father is or to make sure that husband is.
18,668
I am starting a (mainly) body-weight fitness routine and I have found squats to be WAY to easy. There are two progressions I can try that I know of: I can try to work towards pistol squats OR I can use a backpack and keep adding weights to it. What are the benefits/downsides of each approach? Recommend any alternatives?
2014/08/20
[ "https://fitness.stackexchange.com/questions/18668", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/10441/" ]
Pull ups are much harder for women, than for men. Males have significant more muscle mass on their upper bodies than women does, so it is natural, it is hard. That said, focus on assisted exercises to begin with. Grip strength also plays a role, but should come quite quickly for beginners. * Rubber-bands * Assisted Pull-ups - lift her up by her feet * Row exercises * Jumping Pull-ups Be aware that pull-ups are brutal and very hard for newbies, and try to start easy.
Pull ups require good development of the back muscles , and you are lifting your body weight. So to increase the number of pull ups you can start doing lat pull downs on machine . These pull downs are to be performed with strict form , with no or least bent in the spine, and bringing the bar to your chins.As you progress and reach about 80-90 % of your body weight on the machine , you will be able to do more number of pullups. I myself was unable to do many pullups , still cannot do more than ten, but have increase the number really fast by focusing on lat pull down. Also doing pull ups on flat rod are more easy then doing pull ups on rod with some angle as they target more of inner middle back muscles .The idea of slow negatives also work very well, and I have started incorporating them in most of my exercises.
18,996,141
I have done my OR mapping by using NHibernate in my C# web application. When i want to get all leaf nodes, i use a query statement like this: ``` List<NODE> LeafList =(List<NODE>) Session.CreateQuery("from NODE as node where node.Id not in (select FatherNodeId from NODE)").List<NODE>(); ``` However, i get the count of LeafList equals to 0 after the query. My database is like: ``` Id FatherNodeId 1 NULL 3 1 4 3 5 3 ``` So, my expected result should be nodes whose id is 4 or 5. What’s more confusing, if i change "not in" to "in", the query works well, and return nodes whose id is 1 or 3. So whats wrong with my not in subqueries?
2013/09/25
[ "https://Stackoverflow.com/questions/18996141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813532/" ]
Try with following code ``` // Example #1: Write an array of strings to a file. // Create a string array that consists of three lines. string[] lines = { "First line", "Second line", "Third line" }; // WriteAllLines creates a file, writes a collection of strings to the file, // and then closes the file. System.IO.File.WriteAllLines(@"C:\Users\Mirro\Documents\Visual Studio 2010\Projects\Assessment2\Assessment2\act\actors.txt", lines); ``` **OUTPUT :** ``` // First line // Second line // Third line ```
``` File.WriteAllLines(filePath, ActorArrayList.ToArray()); ```
1,388,578
hi i have written app on vs2008 c# (express edition) on win XP which reads and creates excel files (excel 2003) using microsoft excel 11.0 object library (because that's the only available one through add references in COM section)... now i publish this project, then copy the setup.exe and take it to my friend's win vista machine, setup goes smoothly but bumps it starts to throw exceptions and stops in the middle of the processes (on my win xp it runs fine without any problems)... plz can you tell me the solution to this problem??? thanks
2009/09/07
[ "https://Stackoverflow.com/questions/1388578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Where do you create the excel files? May be your programm has not right to access the directory where you store the files. An other case may be that your friend´s computer does not support the used excel 11.0 object library cause he has an other version of excel (Excel 2007) installed.
Should really say what the exceptions are otherwise it's a random stab in the dark, but... Are the same version excel libraries available on the target machine?
11,251,826
I have a desktop client that sends data to a web server and I can't seem to get through the proxy server. **Update**: I am getting a 407 HTTP error when trying to communicate through the proxy. When downloading information from my web server, everything is fine. Once the user configures the proxy server (using a dialog box I wrote) the download works fine. But uploading data using [org.apache.http.client.HttpClient](http://hc.apache.org/httpcomponents-client-ga/) is not working. I am configuring the proxy server with code like this after gathering the information from a JDialog. ``` System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", "" + portNumber); ``` Now, once we do that, simple downloads work fine. For instance, I have code that reads some xml data from my web server (see below). On the customer's network the error in my catch block was displayed before the proxy settings were configured and then everything worked fine once the correct proxy was set. ``` /** * Loads a collection of exams from the web site. The URL is determined by * configuration or registration since it is State specific. */ public static int importExamsWS(StringBuilder msg) { try { java.net.URL onlineExams = new URL(examURL); //Parse the XML data from InputStream and store it. return importExams(onlineExams.openStream(), msg); } catch (java.net.UnknownHostException noDNS) { showError(noDNS, "Unable to connect to proctinator.com to download the exam file.\n" + "There is probably a problem with your Internet proxy settings."); } catch (MalformedURLException | IOException duh) { showFileError(duh); } return 0; } ``` However, when I try to SEND data to the web server it is as if the proxy settings are being ignored and an IOException gets thrown. Namely: ``` org.apache.http.conn.HttpHostConnectException: Connection to http://proctinator.com:8080 refused ``` Now I know that port 8080 is not blocked by the customer's web filter because we tested the address in a web browser. Here is my code for verifying the registration ID entered by the user: **Update: Now I am also setting the proxy in this method.** ``` //Registered is just an enum with ACTIVE, INACTIVE, NOTFOUND, ERROR public static Registered checkRegistration(int id) throws IOException { httpclient = new DefaultHttpClient(); Config pref = Config.getConfig(); //stores user-entered proxy settings. HttpHost proxy = new HttpHost(pref.getProxyServer(), pref.getProxyPort()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); URIBuilder builder = new URIBuilder(); String path = "/Proctorest/rsc/register/" + id; try { builder.setScheme("http").setHost(server).setPort(8080).setPath(path); URI uri = builder.build(); System.out.println("Connecting to " + uri.toString()); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpclient.execute(httpget); System.out.println(response.getStatusLine().toString()); if(response.getStatusLine().getStatusCode()==200) { String msg = EntityUtils.toString(response.getEntity()); GUI.globalLog.log(Level.INFO, "Server response to checkRegistration(" + id + "): " + msg); return Registered.stringToRegistered(msg); } else { GUI.globalLog.log(Level.INFO, "Server response status code to checkRegistration: " + response.getStatusLine().getStatusCode()); return Registered.ERROR; } } catch(java.net.URISyntaxException bad) { System.out.println("URI construction error: " + bad.toString()); return Registered.ERROR; } } ``` I'm almost positive that the problem is coming from the proxy server configuration, yet the [docs for SystemDefaultHttpClient](http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html) claim that it takes uses System properties for `http.proxyHost` and `http.proxyPort` . I know that the properties have been properly set, but I am still getting this authentication error. Viewing the logs generated from my program showed me this: ``` checkRegistration INFO: Server response status code to checkRegistration: 407 ``` How do I resolve this authentication error?
2012/06/28
[ "https://Stackoverflow.com/questions/11251826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1134211/" ]
Just for completeness, since this question is found searching for JVM http.proxy properties, if using JVM infrastructure proxy username and passwords can be provided using : ``` System.setProperty("http.proxyUser",proxyUserName) System.setProperty("http.proxyPassword",proxyUsePassword). ```
For some reason, setting parameters on client didn't work for me. But worked on http method.
9,543,143
I have a viewController pushed in navigationController. When this viewController pushed, the navigation bar was attached on top(0.0, 0.0), and the viewController's view was attached just under that. (maybe.. 0.0, 44.0) But, I want this view to locate to (0.0, 0.0) with navigation bar. Namely, the top side of the view have to be covered beneath the navigation bar. Thank you for your reading.
2012/03/03
[ "https://Stackoverflow.com/questions/9543143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619267/" ]
Your first try was correct: ``` command_name "$abstract" ``` That executes `command_name` with a single argument, `test1 and "test2"`. For example: ``` :; mkdir empty :; cd empty :; abstract='test1 and "test2"' :; touch "$abstract" :; ls -l total 0 -rw-r--r-- 1 mayoff wheel 0 Mar 2 21:26 test1 and "test2" ``` You can see that `touch` only created one file, and it is named `test1 and "test2"`. EDIT ---- So, based on your comment, you actually want to interpolate a shell variable into a SQL statement to pass on the command line to `sqlite3`. First, you should be aware that using `"` to quote a string in SQLite3 is dangerous. It is allowed as an exception to the normal rules, as described in the [“SQLite Keywords” documentation](http://www.sqlite.org/lang_keywords.html), which also says “Future versions of SQLite might change to raise errors instead of accepting the malformed statements covered by the exceptions above.” So, if we use single quotes as we're supposed to, you want to execute this: ``` sqlite3 test.db "insert into test values('$abstract')" ``` Of course, that works fine with the example value you gave for `$abstract`. Let's change to a more challenging version of `$abstract`: ``` abstract="'test' and \"test2\"" ``` To handle this, we need to quote the single-quotes before SQLite sees them. In a SQLite3 string, two single-quotes in a row represent one single-quote. That is, we want to run this SQLite3 command: ``` insert into test values('''test'' and "test2"') ``` Anyway, bash actually has a handy way of doing this. In bash, you can say `${variable//PATTERN/STRING}`, and bash will expand that to the value of `$variable`, but it will replace every instance of `PATTERN` with `STRING` in the expansion. We can use that to replace each single-quote in `$abstract` with two single-quotes. But the single-quote is magic to bash when it appears in `PATTERN`, so we have to quote the single-quote there with a backslash. But we don't quote the single-quotes in the replacement `STRING`. Wow, this gets confusing, doesn't it? Anyway, the magic incantation you are looking for is this: ``` sqlite3 test.db "insert into test values('${abstract//\'/''}')" ``` We can test this using `touch`: ``` :; mkdir empty :; cd empty :; touch sqlite3 test.db "insert into test values('${abstract//\'/''}')" :; ls -l total 0 -rw-r--r-- 1 mayoff wheel 0 Mar 3 15:01 insert into test values('''test'' and "test2"') -rw-r--r-- 1 mayoff wheel 0 Mar 3 15:01 sqlite3 -rw-r--r-- 1 mayoff wheel 0 Mar 3 15:01 test.db ``` Or of course we can test it with SQLite: ``` :; rm -f test.db :; sqlite3 test.db 'create table test (x)' :; sqlite3 test.db "insert into test values('${abstract//\'/''}')" :; sqlite3 test.db 'select * from test' 'test' and "test2" ```
The differences between `"$abstract"` and `$abstract` and `\"$abstract\"` are: * **`"$abstract"`** expands to **`test1 and "test2"`** as a single word * **`$abstract`** expands to **`test1 and "test2"`**, then split to (**`test1`**, **`and`**, **`"test2"`**) as 3 words * **`\"$abstract\"`** is nothing but string concatenation of 3 items(**`\"`**, **`$abstract`**, **`\"`**), after expand **`$abstract`**, it turns into (**`"test1`**, **`and`**, **`"test""`**) as 3 words
6,731,140
``` (gdb) disas func Dump of assembler code for function func: 0x00000000004004b8 <func+0>: push %rbp 0x00000000004004b9 <func+1>: mov %rsp,%rbp 0x00000000004004bc <func+4>: movl $0x64,0xfffffffffffffff0(%rbp) 0x00000000004004c3 <func+11>: movb $0x61,0xfffffffffffffff4(%rbp) 0x00000000004004c7 <func+15>: mov 0xfffffffffffffff0(%rbp),%rax 0x00000000004004cb <func+19>: leaveq 0x00000000004004cc <func+20>: retq End of assembler dump. t_test func() { t_test t; t.i = 100; t.c = 'a'; return t; } ``` So it seems it's returning the local variable `t`,but is this kind of job guaranteed to work, isn't it supposed not to refer to any local variables when return??
2011/07/18
[ "https://Stackoverflow.com/questions/6731140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/807893/" ]
RAX is big enough to hold the entire structure. At 0x00000000004004c7 you're loading the entire structure (with mov), not its address (you'd use lea instead). The x86-64 System V ABI's calling convention returns C structs up to 16 bytes in RDX:RAX or RAX. [C++ on x86-64: when are structs/classes passed and returned in registers?](https://stackoverflow.com/questions/42411819/c-on-x86-64-when-are-structs-classes-passed-and-returned-in-registers) For larger structs, the there's a "hidden" output pointer arg passed by the caller.
Your original code is returning a copy of the structure created in the function - because you're returning a structure type, not a pointer to a structure. What it looks like is that the entire structure is passed by value with `rax`. Generally speaking, the compiler can produce various assembly codes for this, depending and caller and callee behavior and calling convention. The proper way to handle structure is to use them as out parameters: ``` void func(t_test* t) { t->i = 100; t->c = 'a'; } ```
29,453,615
Is there a way that I can compare an array and an arraylist like ``` if (array[0]==arraylist[0]) ``` I am working on this problem: ``` String[] s= {"a","a","b","b","b","c"}; ArrayList<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); // create a new arraylist that stores the frequency of each character. // For example, "a" appears twice in s, so newArrayList[0]=2; "b" appears // three times, so newArrayList[1]=3, and so on. ``` My idea is using a loop to scan through the string array and every time when a letter in it equals the letter in list, int count++. But I dont know how to compare things in an array and things in an arraylist.
2015/04/05
[ "https://Stackoverflow.com/questions/29453615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593157/" ]
``` import java.util.ArrayList; public class ArrayAndArrayListElementsComparison { public static int compareArrayAndArrayListElements(String[] array, ArrayList<String> arraylist) { int count = 0; for (String s : array) { if (arraylist.contains(s)) { count++; } } return count; } public static void main(String[] args) { String[] array = {"a", "a", "b", "b", "b", "c"}; ArrayList<String> arraylist = new ArrayList<String>(); System.out.println(""); arraylist.add("a"); arraylist.add("b"); arraylist.add("c"); if (!arraylist.isEmpty() && array.length > 0) { if (compareArrayAndArrayListElements(array, arraylist) == array.length) { System.out.println("ArrayList contains all the elements in Array"); } else if (compareArrayAndArrayListElements(array, arraylist) > 0) { System.out.println("ArrayList contains only few elements in Array"); } else { System.out.println("ArrayList contains none of the elements in Array"); } } else { System.out.println("Either ArrayList or Array is Empty."); } } } ```
You try ``` if (array[0].equals(arraylist[0])) ``` As in java comparisons string should use equals(). It's not like javascript.
114,294
I have a server that listens to simple tcp sockets. If connecting to it, it prints a prompt and I can type commands, hit enter, see (and save) results, and then have the prompt again. I'm using telnet right now to connect, but want something more console/shell like. Specifically, I'm looking for a tool that only sends what I've typed when I type (meaning, not every character I type), and so allows me to edit the line in the client side. In telnet, if i write type 'foo' (without quotes) and then hit backspace and type 'o', the server gets 'fooo', which it can't handle. I want the backspace to be handled in the client, so the server sees 'foo'. I also want history handling. I work in Windows and looking for freeware
2010/02/18
[ "https://serverfault.com/questions/114294", "https://serverfault.com", "https://serverfault.com/users/35316/" ]
Did you have a look at netcat ( <http://netcat.sourceforge.net/>)
Try `ncat`, which comes with [nmap](http://nmap.org/) 5.0 and later. I run: ``` C:\>"\Program Files (x86)\Nmap\ncat.exe" www.google.com 80 ``` I type: ``` HEAD / HTTP/1.0 Host: www.google.com <extra return> ``` I get: ``` HTTP/1.0 200 OK Date: Thu, 18 Feb 2010 20:48:34 GMT Expires: -1 Cache-Control: private, max-age=0 Content-Type: text/html; charset=ISO-8859-1 Set-Cookie: PREF=ID=31b99fd75e6e122a:TM=1266526114:LM=1266526114:S=ncRwt4V-M8RC4E_Y; expires=Sat, 18-Feb-2012 20:48:34 GMT; path=/; domain=.google.com Set-Cookie: NID=31=bCeSJHeBgJOQNsQS6tDwRBoEkDHpYuz0LjtF5kCP-AngavYRcJxb56LXzhDJNt8pSPXw-NhQkYhgVn-DC4Qk9pfRs1In-5ZBRH4NAczJabFU9P16_ROz9RnHVwOlB3sj; expires=Fri, 20-Aug-2010 20:48:34 GMT; path=/; domain=.google.com; HttpOnly Server: gws X-XSS-Protection: 0 ```
27,746,614
Let's say I have a cell array containing 1x2 cells. eg. `deck = {{4,'c'},{6,'s'}...{13,'c'}...{6,'d'}}` How can I find the index of a specific cell? E.g I want to find the index of the cell with the values `{13,'c'}`. Thanks!
2015/01/02
[ "https://Stackoverflow.com/questions/27746614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4098307/" ]
Another method I can suggest is to operate on each column separately. We could use logical operators on each column to search for cards in your cell array that contain a specific number in the first column, followed by a specific suit in the second column. To denote a match, we would check to see where these two outputs intersect. We can do this by combining both outputs with a logical `AND` when we're done: ``` deck = {{4,'c'},{6,'s'},{13,'c'},{6,'d'}}; target_card = {13, 'c'}; deck_unroll = vertcat(deck{:}); a1 = cat(1, deck_unroll{:,1}) == target_card{1}; a2 = cat(1, deck_unroll{:,2}) == target_card{2}; found = a1 & a2 found = 0 0 1 0 ``` Because `deck` is a nested cell array, I unrolled it so that it becomes a 2D cell array where each row denotes one card. This is stored in `deck_unroll`. Once I do this, I further unroll the cells so that the first column gets placed into a numeric array and we search for a particular number (13 in your example) and the second column gets placed into a string array where we search for a particular character (`'c'` in your example). This is done with the help of [`cat`](http://www.mathworks.com/help/matlab/ref/cat.html) to extract each element from a particular column and we construct an array out of these elements.
Try [`cellfun`](http://www.mathworks.com/help/matlab/ref/cellfun.html) with [`isequal`](http://www.mathworks.com/help/matlab/ref/isequal.html): ``` >> deck = {{4,'c'},{6,'s'},{13,'c'},{6,'d'}}; >> targetCell = {13,'c'}; >> found = cellfun(@(c) isequal(c,targetCell),deck) found = 0 0 1 0 ``` `cellfun` let's you check anyway you want (not just `isequal`). For example, if you want to check based on the string element in each cell: ``` >> targetLetter = 'c'; >> found = cellfun(@(c) strcmp(c{2},targetLetter),deck) found = 1 0 1 0 ```
4,207,989
I have heared that PHP is not good for large websites althogh I do not know what is the meaning of large websites in this case, is it something like Facebook for example? Any way, is it true that PHP does scale with large websites?
2010/11/17
[ "https://Stackoverflow.com/questions/4207989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/514103/" ]
I'm going to differ with my counterparts here. As a language, nothing about PHP is built for scalability. Any language can be extended for that, and PHP has far more than its fair share of tools to do it, but as far as built-in tools to support that need, it has none. Which is exactly what makes it a great choice. You see, with the lack of built-in high-level web tools, it allows others to built unique solutions to the problems. Just about every major advancement in other languages has been duplicated for PHP. There is not a single tool out there in some other language that isn't matched or beat by something in PHP. And after all that, those built-in limitations help foster good development practices and security-conscious designs. It forces we devs to learn the theory behind the techniques we apply and cuts-down on the misapplication of those principals. Anyway. /lovemaking-with-php
It depends on your application architecture not programming languages. If your architecture and design is optimised your application will perform very well on large scale. And also depends on your servers.
50,641
Good day, I have a sensor which supports serial data output using RS422 which has 4 wires (RX+, RX-, TX+, TX-) my question is how can I connect this sensor to the Arduino. I read that i can use 2 max485 chips to do this but uncertain of the exact procedure. Thanks in advance.
2018/03/11
[ "https://arduino.stackexchange.com/questions/50641", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/35288/" ]
There are pre-made and very inexpensive Arduino RS-485 modules available on Ebay or Amazon. Much simpler than building your own circuit. They look like this: [![RS-485 Module](https://i.stack.imgur.com/kG1OF.jpg)](https://i.stack.imgur.com/kG1OF.jpg)
The MAX490 chip consists of DI (pin 3) and RO (pin 2) pins that connect to the Arduino TX and RX respectively. the rs-422 side of the chip consists of pin 5 (Y / T+), Pin 6 (Z / T-), pin 7 (B / R-) and pin 8 (A / R+) <http://arduinotronics.blogspot.com/2018/09/long-distance-serial-with-rs-422.html>
6,339,287
The following command is working as expected... ``` cp -ur /home/abc/* /mnt/windowsabc/ ``` Does `rsync` has any advantage over it? Is there a better way to keep to backup folder in sync every 24 hours?
2011/06/14
[ "https://Stackoverflow.com/questions/6339287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139150/" ]
Keep in mind that while transferring files internally on a machine i.e not network transfer, using the **-z** flag can have a massive difference in the time taken for the transfer. **Transfer within same machine** ``` Case 1: With -z flag: TAR took: 9.48345208168 Encryption took: 2.79352903366 CP took = 5.07273387909 Rsync took = 30.5113282204 Case 2: Without the -z flag: TAR took: 10.7535531521 Encryption took: 3.0386879921 CP took = 4.85565590858 Rsync took = 4.94515299797 ```
I used rsynk to transfer 330G data from a local HD to a external HD via USB 3.0. It took me three days. The transfer rate went down to 800 Kb/s and rised to 50 M/s for a while only after pausing the job. It is a typical overbuffering issue. Bad experience for local file tranfers: as the name indicates, (R)sync stands for REMOTE-sync (optimized for tranfers via network). As often happens, I discovered the "-z" flag only after I wondered about the issue and looked for an understandment
16,007,880
The Following is my code when i am fetching the value from the GameByGameTypes and Categories but in table called GameByGameTypes have column CategoryId have NULL value. So i want 0 inplace of NULL ``` Category objCategory; var query = (from gametypebygametype in db.GameByGameTypes.Where( x => x.GameTypeId == gametypeid) join category in db.Categories on gametypebygametype.CategoryId equals category.CategoryId into joined from category in joined.DefaultIfEmpty() select new { category.CategoryId , category.CategoryName } ).Distinct(); List<Category> objlistCategory = new List<Category>(); foreach (var item_temp in query) { objCategory = new Category(); objCategory.CategoryId = item_temp.CategoryId; objCategory.CategoryName = item_temp.CategoryName; objlistCategory.Add(objCategory); } ```
2013/04/15
[ "https://Stackoverflow.com/questions/16007880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2049563/" ]
Or you can replace ``` select new { category.CategoryId, category.CategoryName } ``` with ``` select new { CategoryId = category.CategoryId ?? 0, CategoryName = category.CategoryName ?? "", } ``` If you use ReSharper - it will 'complain' that `?? 0` part is not needed. Ignore it. And Linq-code you use is translated to SQL. When you execute it - result is null, but strongly-typed compiler cannot believe in that, and awaits non-nullable value. (this is the process of 'materialization', that fails). So you just 'hint' compiler, that it could be null. [Here is related question](https://stackoverflow.com/questions/4347266/why-would-this-linq-to-sql-query-break-when-i-do-tolist).
You have three ways to work with this: 1. You can set column in database `not null` and set default to column 0. 2. You can set Category property `int? CategoryId`. 3. You can change your query to use DefaultIfEmpty with default value ``` var query = (from gametypebygametype in db.GameByGameTypes.Where( x => x.GameTypeId == gametypeid) join category in db.Categories on gametypebygametype.CategoryId equals category.CategoryId into joined from category in joined.DefaultIfEmpty( new { CategoryId=0, Categoryname="" }) select new ... ```
74,246,337
I have a button that changes an element's style. Can I have this button auto-reset the CSS changed, back to default? Here is the code: ``` <div class="coinboxcontainer"><img id="coin1" src="/wp-content/uploads/2022/10/coin.png" alt="box" width="40" height="40"> <a onclick="tosscoin()"><img src="/wp-content/uploads/2022/10/coinbox.png" alt="box" width="40" height="40"></a> <audio id="audio" src="/wp-content/uploads/2022/10/coinsound.mp3"></audio> <script> function tosscoin() { document.getElementById("coin1").style.transform = "translatey(-70px)"; var audio = document.getElementById("audio"); audio.play(); } </script> </div> ```
2022/10/29
[ "https://Stackoverflow.com/questions/74246337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15846302/" ]
You can't circumvent auto-play from being blocked. There has to be some user interaction before the audio can play. This is the same for both HTML `<audio>` element as well as the web-audio API's `audioContext` There's some reading about this on MDN [Autoplay guide for media and Web Audio's API](https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide)
You can try to play the audio on javascript `onload`. Example: HTML: ``` <audio controls id="horseAudio"> <source src="https://www.w3schools.com/html/horse.ogg" type="audio/ogg"> <source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> ``` JavaScript: ``` window.onload = function (){ document.getElementById("horseAudio").play(); } ```
19,316,285
suppose I have this string: ``` var inputStr="AAAA AAAAAAAA AAA AAAAA"; ``` **(The asumption here is that I don't know the size of each 'A...' sequence in the string.)** I need a simple way to reduce 2 'A' characters from every "A..." sequence in that string somthing like: ``` var result=Regex.Replace(inputStr,...); ``` so that the result for this example will be: `"AA AAAAAA A AAA"`) thanks... **UPDATE:** thanks for all the replies, I want to make this question more general. example 2: `var inputStr="bbbAAAAC1AAAAAAAA AAA AAAAArrr"` and the result should be: `"bbbAAC1AAAAAA A AAArrr"`
2013/10/11
[ "https://Stackoverflow.com/questions/19316285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219182/" ]
If you know that all the 'words' are `A`s, you can use this replace: ``` var result=Regex.Replace(inputStr,@"AA\b",""); ``` [regex101 demo for the regex replace](http://regex101.com/r/jU4dO3) --- As per edit, a more general pattern would be: ``` var result=Regex.Replace(inputStr,@"AA(?!A)",""); ``` [regex101 demo](http://regex101.com/r/wG0xA3)
Although not a regex but it will work ``` String.Join(" ", inputStr.Split().Select(x => x.Substring(0, x.Length - 2)).ToArray()); ```
32,420,956
The scrolling on my UICollectionView is really choppy. As I scroll past half the screen, it gets stuck for a moment and then proceeds. How can I make the scrolling more smooth using SWIFT?
2015/09/06
[ "https://Stackoverflow.com/questions/32420956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5146927/" ]
Use Time Profiler instrument to find out where the bottleneck is. Swift has nothing to do with scroll view's performance.
There are two complementary ways: 1) [Fast way] When choppy effect is large enough for giving you time for pressing pause button on the debugger. And then review what is doing main thread (Thread 1), most probably won't be doing UI tasks. Move those task to background. 2) When doesn't use instruments with core image.
602,237
'`hello, world`' is usually the first example for any programming language. I've always wondered where this sentence came from and where was it first used. I've once been told that it was the first sentence ever to be displayed on a computer screen, but I've not been able to find any reference to this. So my question is: Where does the practice to use '`hello, world`' as the first example for computer languages originate from? Where was it first used? **Update** Although the answers are quite interesting, I should have noted that I had read the Wikipedia article. It does answer the question about the first use in literature, but does not answer when '`hello world`' was first *used*. So I think that it is safe to conclude that it was not the first sentence ever to be displayed on a computer screen and that there is no record about when it was first used?
2009/03/02
[ "https://Stackoverflow.com/questions/602237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22674/" ]
Brian Kernighan actually wrote the first "hello, world" program as part of the documentation for the BCPL programming language developed by Martin Richards. BCPL was used while C was being developed at Bell Labs a few years before the publication of Kernighan and Ritchie's C book in 1972. [![enter image description here](https://i.stack.imgur.com/wU0xv.png)](https://i.stack.imgur.com/wU0xv.png) As part of the research for a book I was writing about the Alice programming environment, I corresponded with both Prof. Kernighan at Princeton and Martin Richards at Cambridge (when I was teaching a seminar there in the 1990’s). They helped me to track the first documented use of code to print the message "Hello, World!” Brian Kernighan remembered writing the code for part of the I/O section of the BCPL manual. Martin Richards -- who seems to have a treasure trove of notes, old documents, etc. -- found the manual and confirmed that this was the original appearance of the program. The code was used for early testing of the C compiler and made its way into Kernighan and Ritchie's book. Later, it was one of the first programs used to test Bjarne Stroustrup's C++ compiler. It became a standard for new programmers after it appeared in Kernighan and Ritchie, which is probably the best selling introduction to programming of all time.
From <http://en.wikipedia.org/wiki/Hello_world_program>: > > The first known instance of the usage > of the words "hello" and "world" > together in computer literature > occurred earlier, in Kernighan's 1972 > Tutorial Introduction to the Language > B[1], with the following code: > > > > ``` > main( ) { > extrn a, b, c; > putchar(a); putchar(b); putchar(c); putchar('!*n'); > } > a 'hell'; > b 'o, w'; > c 'orld'; > > ``` > >
58,046,980
Please run the example below. I'm trying to stretch the left line further to the left to compensate the parent's padding as you can see in the second example, **while** keeping the title centered relative to the parent like in the first example. I can't seem to have both. (For anyone who's familiar, the divider I'm trying to tweak comes from ant-design) ```css #container { height: 100px; width: 400px; background: #EFEFEF; padding: 24px; } /* Normal use case */ .divider { position: relative; line-height: 23px; height: 1px; display: table; margin: 16px 0; color: rgba(0, 0, 0, 0.85); font-weight: 500; font-size: 15px; white-space: nowrap; text-align: center; background: transparent; } .divider::before, .divider::after { position: relative; top: 50%; display: table-cell; width: 50%; border-top: 1px solid #AAA; -webkit-transform: translateY(50%); -ms-transform: translateY(50%); transform: translateY(50%); content: ''; } .divider-text { display: inline-block; padding: 0 24px; } /* Trying to stretch the left line to further to the left without puting the title off-center */ .divider.stretched-left { left: -24px; width: calc(100% + 24px); min-width: calc(100% + 24px); } ``` ```html <div id="container"> <div class="divider"> <span class="divider-text">Title</span> </div> <div class="divider stretched-left"> <span class="divider-text">Title</span> </div> </div> ```
2019/09/22
[ "https://Stackoverflow.com/questions/58046980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11153160/" ]
First, I would use flexbox instead of table layout then adjust the margin/padding: Kept only the relevant code for the demo ```css #container { width: 400px; background: #EFEFEF; padding: 24px; } /* Normal use case */ .divider { display: flex; margin: 16px 0; align-items:center; } .divider::before, .divider::after { flex:1; height: 1px; background:#AAA; content: ''; } .divider::before { margin-right:24px; } .divider::after { margin-left:24px; } .divider.stretched-left:before { margin-left:-24px; padding-left: 24px; } .divider.stretched-right:after { margin-right:-24px; padding-right: 24px; } ``` ```html <div id="container"> <div class="divider"> <span class="divider-text">Title</span> </div> <div class="divider stretched-left"> <span class="divider-text">another Title</span> </div> <div class="divider stretched-right"> <span class="divider-text">Title</span> </div> <div class="divider stretched-right"> <span class="divider-text">another Title</span> </div> <div class="divider stretched-left stretched-right"> <span class="divider-text">another Title</span> </div> </div> ``` With your original code you can try this: ```css #container { height: 100px; width: 400px; background: #EFEFEF; padding: 24px; } /* Normal use case */ .divider { position: relative; line-height: 23px; height: 1px; display: table; margin: 16px 0; color: rgba(0, 0, 0, 0.85); font-weight: 500; font-size: 15px; white-space: nowrap; text-align: center; background: transparent; } .divider::before, .divider::after { position: relative; top: 50%; display: table-cell; width: 50%; border-top: 1px solid #AAA; transform: translateY(50%); content: ''; } .divider-text { display: inline-block; padding: 0 24px; } /* Trying to stretch the left line to further to the left without puting the title off-center */ .divider.stretched-left { left: -24px; width: calc(100% + 48px); /* Updated */ } /* Added */ .divider.stretched-left:after { border-image:linear-gradient(to left,transparent 24px, #aaa 24px) 1; } ``` ```html <div id="container"> <div class="divider"> <span class="divider-text">Title</span> </div> <div class="divider stretched-left"> <span class="divider-text">Title</span> </div> </div> ```
Solution with minimum CSS, without flex, without transform. ```css .divider { position: relative; text-align:center; } .divider:before { content:''; position: absolute; top:50%; height: 1px; width: 100%; background: #000; left: 0; z-index: -1; } .divider span{ padding: 0 24px; z-index: 1; background: #fff; display: inline-block; } ``` ```html <div class="divider"> <span>Title</span> </div> ```
50,512,600
I'm trying to do a shader to curve the world like [Subway Surfer](https://www.youtube.com/watch?v=Muh7QFisCfE&ab_channel=Throneful) does. I have found a [GitHub repo](https://gist.github.com/grimmdev/9e63af5ab00c91d7ad09) where someone pushes an approximation for it that works cool. This is the code: ``` Shader "Custom/Curved" { Properties { _MainTex ("Base (RGB)", 2D) = "white" {} _QOffset ("Offset", Vector) = (0,0,0,0) _Dist ("Distance", Float) = 100.0 } SubShader { Tags { "RenderType"="Opaque" } Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" sampler2D _MainTex; float4 _QOffset; float _Dist; struct v2f { float4 pos : SV_POSITION; float4 uv : TEXCOORD0; }; v2f vert (appdata_base v) { v2f o; float4 vPos = mul (UNITY_MATRIX_MV, v.vertex); float zOff = vPos.z/_Dist; vPos += _QOffset*zOff*zOff; o.pos = mul (UNITY_MATRIX_P, vPos); o.uv = v.texcoord; return o; } half4 frag (v2f i) : COLOR { half4 col = tex2D(_MainTex, i.uv.xy); return col; } ENDCG } } FallBack "Diffuse" } ``` The point is that now I want to send that new vertex positions to the surface shader to be able to have illumination an others. I have read that I have to delete the fragment shader but I still having the problem that I can not send the new information to the surface shader. This is my code: ``` Shader "Custom/Curve" { Properties{ _Color("Color", Color) = (1,1,1,1) _MainTex("Albedo (RGB)", 2D) = "white" {} _Glossiness("Smoothness", Range(0,1)) = 0.5 _Metallic("Metallic", Range(0,1)) = 0.0 _QOffset("Offset", Vector) = (0,0,0,0) _Dist("Distance", Float) = 100.0 } SubShader{ Tags{ "RenderType" = "Opaque" } LOD 200 CGPROGRAM #pragma surface surf Standard fullforwardshadows vertex:vert addshadow #pragma target 3.0 sampler2D _MainTex; struct Input { float2 uv_MainTex; }; half _Glossiness; half _Metallic; fixed4 _Color; float4 _QOffset; float _Dist; void vert(inout appdata_full v) { v.position.x += 10; } void surf(Input IN, inout SurfaceOutputStandard o) { // Albedo comes from a texture tinted by color fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color; o.Albedo = c.rgb; // Metallic and smoothness come from slider variables o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" } ``` As you can see now in the vertex shader I'm just trying to add some units to the X position of the vertex because I think that if I achieve that apply the "curved change" would be trivial but If you think It is not going to be that easy I would appreciate if you warn me.
2018/05/24
[ "https://Stackoverflow.com/questions/50512600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9419887/" ]
edited: Here's an example for unity 2018.1 <https://gist.github.com/bricevdm/caaace3cce9a87e081602ffd08dee1ad> ```c float4 worldPosition = mul(unity_ObjectToWorld, v.vertex); // get world space position of vertex half2 wpToCam = _WorldSpaceCameraPos.xz - worldPosition.xz; // get vector to camera and dismiss vertical component half distance = dot(wpToCam, wpToCam); // distance squared from vertex to the camera, this power gives the curvature worldPosition.y -= distance * _Curvature; // offset vertical position by factor and square of distance. // the default 0.01 would lower the position by 1cm at 1m distance, 1m at 10m and 100m at 100m v.vertex = mul(unity_WorldToObject, worldPosition); // reproject position into object space ``` [![screen capture from unity editor](https://i.stack.imgur.com/ZQu4M.png)](https://i.stack.imgur.com/ZQu4M.png) You are mixing up regular CG shaders and Surface shaders. Your sample from github is the former. `v.vertex` in Surface shaders is expected to be in **object space**, unlike `float4 pos : SV_POSITION` in the CG shader, which is expected to be in its final - **clip/screen space** - position. The solution is to inverse the transformation back to object space. In your case you'd need to expose the inverse projection matrix from the camera. replace `v.vertex = mul (UNITY_MATRIX_P, vPos);` with this matrix: <https://docs.unity3d.com/ScriptReference/Camera-cameraToWorldMatrix.html>. Since you transformed your vertex from object to camera space with UNITY\_MATRIX\_MV you need to reverse to world first, then to object space using unity\_WorldToObject (or better combine both on the cpu). **BUT** it is actually much easier to compute the curvature in **world space** with the matrices already provided: <https://docs.unity3d.com/Manual/SL-UnityShaderVariables.html> > > unity\_ObjectToWorld Current model matrix. > > > unity\_WorldToObject Inverse of current world matrix. > > >
It's because there isn't value as position in `appdata_full` struct: ``` struct appdata_full { float4 vertex : POSITION; float4 tangent : TANGENT; float3 normal : NORMAL; float4 texcoord : TEXCOORD0; float4 texcoord1 : TEXCOORD1; fixed4 color : COLOR; #if defined(SHADER_API_XBOX360) half4 texcoord2 : TEXCOORD2; half4 texcoord3 : TEXCOORD3; half4 texcoord4 : TEXCOORD4; half4 texcoord5 : TEXCOORD5; #endif }; ``` Instead of `v.position` use `v.vertex` like this: ``` void vert (inout appdata_full v, out Input o){ UNITY_INITIALIZE_OUTPUT(Input,o); v.vertex += 10; } ``` And here Is surface version of your curve shader: ``` Shader "Custom/Curve" { Properties{ _Color("Color", Color) = (1,1,1,1) _MainTex("Albedo (RGB)", 2D) = "white" {} _Glossiness("Smoothness", Range(0,1)) = 0.5 _Metallic("Metallic", Range(0,1)) = 0.0 _QOffset("Offset", Vector) = (0,0,0,0) _Dist("Distance", Float) = 100.0 } SubShader{ Tags{ "RenderType" = "Opaque" } LOD 200 CGPROGRAM #pragma surface surf Standard fullforwardshadows vertex:vert addshadow #pragma target 3.0 sampler2D _MainTex; struct Input { float2 uv_MainTex; }; half _Glossiness; half _Metallic; fixed4 _Color; float4 _QOffset; float _Dist; void vert (inout appdata_full v, out Input o){ UNITY_INITIALIZE_OUTPUT(Input,o); float4 vPos = mul (UNITY_MATRIX_MV, v.vertex); float zOff = vPos.z/_Dist; vPos += _QOffset*zOff*zOff; v.vertex = mul (UNITY_MATRIX_P, vPos); v.texcoord = v.texcoord; } void surf(Input IN, inout SurfaceOutputStandard o) { // Albedo comes from a texture tinted by color fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color; o.Albedo = c.rgb; // Metallic and smoothness come from slider variables o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" } ```
464,150
Цитирую отрывок из "Иерусалима" А. Мура в переводе С. Карпова. Стр. 835. > > Я вижу Томаса а Беккета, и вижу смуглую женщину со шрамом, которая > работает в корпусе Святого Петра в две тысячи двадцать пятом году. > > > "Вижу" и "вижу" — это два однородных сказуемых, соединённых союзом "и". В таких случаях запятая не требуется. Есть причины для постановки запятой? **Дополнение** Привожу цитату из оригинального романа. Запятая там тоже есть. > > I see Audrey Vernall on the dance-hall stage, her fingers trickling on > the keys of her accordion, tossing back her hair, with one small blue > shoe keeping time on the worn boards, skirt swinging, “When The Saints > Go Marching In” . Her tight smile falters in the spotlight and her > eyes keeping darting sideways to the wings where her dad Johnny, the > band’s manager, gives her the thumbs-up, nods encouragingly at her, > and then, later on, he’s taking off his loud checked jacket, hanging > it up on the hook for dressing gowns behind her bedroom door. **I see > Thomas Becket, and I see the brown-skinned woman with the scar who > works from the St. Peter’s Annexe up in two thousand and twenty-five.** > I see the saints go marching in. > > >
2021/04/13
[ "https://rus.stackexchange.com/questions/464150", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/4120/" ]
Второй ответ от 20.04.2021 (обсуждение продолжено по просьбе автора вопроса) Да, вопрос непростой. Я уже привела в комментарии ссылку на обсуждение подобной темы на форуме. [https://rus.stackexchange.com/questions/458555/Как-отличить-сложное-предложение-с-односоставными-частями-от-простого-с-однородн](https://rus.stackexchange.com/questions/458555/%D0%9A%D0%B0%D0%BA-%D0%BE%D1%82%D0%BB%D0%B8%D1%87%D0%B8%D1%82%D1%8C-%D1%81%D0%BB%D0%BE%D0%B6%D0%BD%D0%BE%D0%B5-%D0%BF%D1%80%D0%B5%D0%B4%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5-%D1%81-%D0%BE%D0%B4%D0%BD%D0%BE%D1%81%D0%BE%D1%81%D1%82%D0%B0%D0%B2%D0%BD%D1%8B%D0%BC%D0%B8-%D1%87%D0%B0%D1%81%D1%82%D1%8F%D0%BC%D0%B8-%D0%BE%D1%82-%D0%BF%D1%80%D0%BE%D1%81%D1%82%D0%BE%D0%B3%D0%BE-%D1%81-%D0%BE%D0%B4%D0%BD%D0%BE%D1%80%D0%BE%D0%B4%D0%BD) Один из ответов был, вероятно, ориентирован на вузовский учебник Валгиной 2003 года «Современный русский язык» <http://yanko.lib.ru/books/language/ru/yanko.valgina_2003_416p_rasp_sl.htm#_Toc331393984> 1. **О грамматике однородных сказуемых** Вот некоторые цитаты: Таким образом, предложения с несколькими глагольными сказуемыми являют собой **переходный, промежуточный** тип между простым и сложным предложением. При квалификации этого сложного синтаксического явления необходимо учесть его двойственную природу: с одной стороны, объединенность таких сказуемых общим подлежащим, с другой — расчлененность их предикативной основы. Такие предложения являются переходными между простыми и сложными и, естественно, в частных, конкретных своих проявлениях **тяготеют то к одному, то к другому** из этих полярных типов. Кроме того, возможность **вставки подлежащего** «он» характеризует подобные сочетания сказуемых как отдельные предикативные единицы, что возможно в структуре сложного предложения. Например: ...Он не думал, чтобы картина его была лучше всех Рафаэлевых, но он знал, что того, что он хотел передать и передал в этой картине, никто никогда не передавал (Л. Т.). Ср.: Он не думал... но знал. Таким образом, «однородные глагольные сказуемые» — понятие по меньшей мере сомнительное. **2. О пунктуации в предложении с однородными сказуемым** Итак, однородные сказуемые должны занимать **одно синтаксическое место** и входить в единую предикативную основу. Изображенные действия являются однородными, если объединены общей темой. Компактность расположения, одинаковая грамматическая форма, отсутствие собственных распространителей – это классика для однородных сказуемых. Если все это не проявляется в должной мере, то на каком-то этапе появляется **переходность,** а потом мы начинаем вообще считать сказуемые отдельными предикативными единицами, то есть предложение определяется **как сложное.** Но это все грамматика, **а как быть с пунктуацией.** Если двигаться дальше в сторону осложнения, то это должно отражаться и на знаках препинания тоже. **Так отражается или нет?** Лингвисты аккуратно обходят этот вопрос. Вот предложение: ***Подсудимых тоже куда-то выводили и только что ввели назад.*** Это предложение безоговорочно зачисляется в разряд сложных, **но запятой нет**. В других случаях предложение названо сложным, но в нем используется **союз НО,** который нам ни о чем не говорит. *Он приобрел свой прежний человеческий облик, // но был чрезвычайно мрачен и даже, пожалуй, раздражен.* Я же думаю, что качественный **переход** от однородных сказуемых к сложному предложению происходит именно в тот момент, когда появляется **потребность в постановке запятой**, для этого даже не надо знать грамматических тонкостей в классификации сложных и осложненных предложений. Автор осознает необходимость в разграничении **двух ситуаций** – а вот это уже лингвистическое понятие (полиситуативность). Не так важна длина предложения, как именно этот момент – **изображение двух взглядов**, которые можно сопоставить, сравнить, но для этого надо выделить каждый из них в отдельную тему. **3. Практическое решение** Если лингвисты уходят от этого вопроса, то он решается на практике **самим автором.** Как известно, практика письма обгоняет теорию письма. Именно это мы видим в приведенном примере. Делается **пауза**, которую нужно обозначить **запятой**. По грамматическим показателям, названным выше, это сложное предложение, а ссылки на правило нет. Так давайте **честно скажем, что нет ссылки**, что этот вариант будет проходить как **авторская пунктуация.**
**Вместо вступления** Как мне кажется, мы обычно воспринимаем правила как **инструкцию** (руководство) для правильного оформления текстов, но не более того. Писатель должен писать по правилам, потому что это требует редактор издательства, а обычные люди соблюдают правила, чтобы считать себя грамотными и чтобы другие так же считали. Если мы читаем книгу, то попутно интересуемся постановкой знаков в целях своего развития: «Почему это писатель не поставил здесь запятую, а корректор пропустил. Однородные члены, значит, запятая нужна». Но верна ли такая однозначная трактовка правил. Правила – это всё-таки не инструкция для грамотного письма. Процитирую в очередной раз **Розенталя,** просто лучше об этом не скажешь: «Особенности русской пунктуации — в присущей ей многофункциональности знаков препинания и широкой их взаимозаменяемости, в своеобразии индивидуально-авторского использования знаков препинания, в гибкости пунктуационной системы, позволяющей выявлять не только смысловую сторону текста, но и стилистические его оттенки. Все это исключает формальный подход к соблюдению правил». Так давайте **следовать этому указанию**, когда решаем наши задачи и выбираем знаки препинания. **Ответ на вопрос** ***Я вижу Томаса Беккета, и (я) вижу смуглую женщину со шрамом, которая работает в корпусе Святого Петра в две тысячи двадцать пятом году.*** Примечание. **Томас Бекет** - канцлер короля Генриха II, глава английской Церкви, одна из ключевых фигур в истории XII века. Знаменит он тем, что настолько сумел насолить монарху, что был убит прямо у алтаря своей церкви. **Из вузовской грамматики:** [https://www.rsuh.ru/upload/main/media/от%20преподавателей/sintaksis-sovremennogo-russkogo-jazyka\_kustova-g\_i\_-i-dr\_2005-256s.pdf](https://www.rsuh.ru/upload/main/media/%D0%BE%D1%82%20%D0%BF%D1%80%D0%B5%D0%BF%D0%BE%D0%B4%D0%B0%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D0%B5%D0%B9/sintaksis-sovremennogo-russkogo-jazyka_kustova-g_i_-i-dr_2005-256s.pdf) ВОПРОС ОБ ОДНОРОДНЫХ СКАЗУЕМЫХ В предложении может быть несколько сказуемых при одном и том же подлежащем. В связи с этим встает вопрос (не получивший в лингвистике однозначного решения), являются ли они простыми или сложными. Одни из них можно считать **простыми** предложениями с однородными сказуемыми, другие считаются промежуточными структурами между простым и **сложным** предложением. Чем больше **степень спаянности** сказуемых, т. е. чем ближе они к однородному ряду, тем ближе предложение к простому. Наибольшая степень спаянности достигается, если сказуемые имеют одинаковое морфологическое выражение, **не распространены**, контактно расположены, связаны с общим второстепенным членом (дополнением или обстоятельством. **При большей коммуникативной расчлененности** и самостоятельности частей, содержащих сказуемые, особенно при дифференцированных отношениях между сказуемыми, предложение приближается к сложному. Итак, с точки зрения грамматики, мы можем считать данную конструкцию **сложным, а не простым предложением** с однородными членами. В этом случае мы имеем право поставить запятую в ССП. Семантическая **расчлененность** явно чувствуется, а также делается пауза чтении: *я вижу, а также я вижу.* Ну и значительная **распространенность** второй части склоняет нас к тому, чтобы считать предложение сложным. **Комментарий** 1. Разбора подобных решений **нет у Розенталя**, сослаться не на что, можно только рассмотреть грамматику. Но это же не повод требовать от писателя отсутствия запятой, даже если пауза явно слышится и требуется раздельное прочтение двух частей. 2. И вот уж не нужно искать **подходящее под запятую правило** где-то еще, чтобы сослаться хотя бы на что-то. Потому что это не тема «Присоединительные члены предложения, которые содержат дополнительные разъяснения или замечания», нет здесь **значения добавочности.** Два взгляда автора на своих персонажей вполне **равноправны** и даны для сопоставления. Неверное толкование запятой приведет **к искажению смысла.**
56,615,820
I meet a question in Codeignter when I try to get an object return, some of controllers codes are ``` $sql = $this->user_model->userdetail($data); if ($sql) { echo json_encode(array( "status" => "0", "message" => "", "data" => $sql )); exit(); } ``` And the model codes are ``` function userdetail($data) { $id = $data["id"]; $sql = "select email, name from user where id='".$id."'"; $query = $this->db->query($sql); if ($query->num_rows() > 0) { return $query->result_array(); } return $query->num_rows(); } ``` I can get the result ``` { "status": "0", "message": "", "data": [ { "email": "lily@email.com", "name": "lily" } ] } ``` here the `data` is an array, but it should be an object, the above result should like this ``` { "status": "0", "message": "", "data": { "email": "lily@email.com", "name": "lily" } } ``` And I changed `return $query->result_array();` to `return $query->result_object();` in model code, but it doesn't work, what should I do here? Thanks a lot.
2019/06/16
[ "https://Stackoverflow.com/questions/56615820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11493319/" ]
Your **problem** is you are using **result\_array()**. You have to use **row()** instead, *row()* function will give you the object instead of array. The model code: ``` function userdetail($data) { $id = $data["id"]; $sql = "select email, name from user where id='".$id."'"; $query = $this->db->query($sql); return $query->num_rows() > 0 ? $query->row() : 0; } ```
I think I find the reason, in model ``` return $query->result_array(); // also can be changed to return $query->result_object(); or return $query->result(); ``` They can return array or object, and in controller file ``` $sql = $this->user_model->userdetail($data); ``` `$sql` should be array or object, but actually it return a Multidimensional Arrays like this return result() or result\_object() ``` Array ( [0] => stdClass Object ( [email] => lily@email.com [name] => lily ) ) ``` return result\_array() ``` Array ( [0] => Array ( [email] => lily@email.com [name] => lily ) ) ``` it's strange.
642,537
I run CentOS 6.4. After configuring bridge I am unable to connect to internet through PPPoE Bsnl Dsl. I set up the bridge as follows: ``` DEVICE="br0" NM_CONTROLLED="no" ONBOOT=yes TYPE=Bridge BOOTPROTO=dhcp DEFROUTE=yes IPV4_FAILURE_FATAL=yes IPV6INIT=no NAME="br0" ``` I added `BRIDGE= br0` at the end of eth0 file and set `Nm_controlled= no`. After `service network restart` I am unable to connect to DSL service.
2013/09/08
[ "https://superuser.com/questions/642537", "https://superuser.com", "https://superuser.com/users/-1/" ]
If you are doing a search using Active Directory tools, then the `*` character is the one you would use for a wildcard, not `%`. This comes from the LDAP directory search syntax. But it looks to me like the search box available from `dsquery.dll` only works correctly with a wildcard placed at the end of the string. So if you wanted to find groups with names beginning with "ABC" then you could search for them using: ``` ABC* ``` But searching using the following does not return any results: ``` *ABC* ``` This is a limitation of the `dsquery.dll` user interface (the same as what you get to by using "Active Directory Users and Computers"). The underlying LDAP directory search API allows for a wildcard to be placed on either the beginning or the end. If you really need this functionality, then you might want to try using PowerShell. It's a full-featured scripting language from Microsoft and can be hard to learn if you've never done any scripting before. But it will give you all the flexibility you need. It is also fairly easy to get started with if you install the [PowerGUI tool from Quest](http://powergui.org/). For any questions on writing and using PowerShell cmdlets or scripts, you would probably want to post a follow-up question on Stack Overflow.
One Outlook addin you might want to check out is [Company Contacts for Outlook](https://wizardsoft.nl/products/companycontactsoutlook). It provides a full text searchable global address book. Wild cards, search in specific column, sort and rearrange columns, quick actions, etc.
848,415
What is the best way to assemble a dynamic WHERE clause to a LINQ statement? I have several dozen checkboxes on a form and am passing them back as: Dictionary<string, List<string>> (Dictionary<fieldName,List<values>>) to my LINQ query. ``` public IOrderedQueryable<ProductDetail> GetProductList(string productGroupName, string productTypeName, Dictionary<string,List<string>> filterDictionary) { var q = from c in db.ProductDetail where c.ProductGroupName == productGroupName && c.ProductTypeName == productTypeName // insert dynamic filter here orderby c.ProductTypeName select c; return q; } ```
2009/05/11
[ "https://Stackoverflow.com/questions/848415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86555/" ]
I have similar scenario where I need to add filters based on the user input and I chain the where clause. Here is the sample code. ``` var votes = db.Votes.Where(r => r.SurveyID == surveyId); if (fromDate != null) { votes = votes.Where(r => r.VoteDate.Value >= fromDate); } if (toDate != null) { votes = votes.Where(r => r.VoteDate.Value <= toDate); } votes = votes.Take(LimitRows).OrderByDescending(r => r.VoteDate); ```
Just to share my idea for this case. Another approach by solution is: ``` public IOrderedQueryable GetProductList(string productGroupName, string productTypeName, Dictionary> filterDictionary) { return db.ProductDetail .where ( p => ( (String.IsNullOrEmpty(productGroupName) || c.ProductGroupName.Contains(productGroupName)) && (String.IsNullOrEmpty(productTypeName) || c.ProductTypeName.Contains(productTypeName)) // Apply similar logic to filterDictionary parameter here !!! ) ); } ``` This approach is very flexible and allow with any parameter to be nullable.
4,972,810
Hey all, I'm writing an application which records microphone input to a WAV file. Previously, I had written this to fill a buffer of a specified size and that worked fine. Now, I'd like to be able to record to an arbitrary length. Here's what I'm trying to do: * Set up 32 small audio buffers (circular buffering) * Start a WAV file with ofstream -- write the header with PCM length set to 0 * Add a buffer to input * When a buffer completes, append its data to the WAV file and update the header; recycle the buffer * When the user hits "stop", write the remaining buffers to file and close It kind of works in that the files are coming out to the correct length (header and file size and are correct). However, the data is wonky as hell. I can make out a semblance of what I said -- and the timing is correct -- but there's this repetitive block of distortion. It basically sounds like only half the data is getting into the file. Here are some variables the code uses (in header) ``` // File writing ofstream mFile; WAVFILEHEADER mFileHeader; int16_t * mPcmBuffer; int32_t mPcmBufferPosition; int32_t mPcmBufferSize; uint32_t mPcmTotalSize; bool mRecording; ``` Here is the code that prepares the file: ``` // Start recording audio void CaptureApp::startRecording() { // Set flag mRecording = true; // Set size values mPcmBufferPosition = 0; mPcmTotalSize = 0; // Open file for streaming mFile.open("c:\my.wav", ios::binary|ios::trunc); } ``` Here's the code that receives the buffer. This assumes the incoming data is correct -- it *should* be, but I haven't ruled out that it isn't. ``` // Append file buffer to output WAV void CaptureApp::writeData() { // Update header with new PCM length mPcmBufferPosition *= sizeof(int16_t); mPcmTotalSize += mPcmBufferPosition; mFileHeader.bytes = mPcmTotalSize + sizeof(WAVFILEHEADER); mFileHeader.pcmbytes = mPcmTotalSize; mFile.seekp(0); mFile.write(reinterpret_cast<char *>(&mFileHeader), sizeof(mFileHeader)); // Append PCM data if (mPcmBufferPosition > 0) { mFile.seekp(mPcmTotalSize - mPcmBufferPosition + sizeof(WAVFILEHEADER)); mFile.write(reinterpret_cast<char *>(&mPcmBuffer), mPcmBufferPosition); } // Reset file buffer position mPcmBufferPosition = 0; } ``` And this is the code that closes the file: ``` // Stop recording void CaptureApp::stopRecording() { // Save remaining data if (mPcmBufferSize > 0) writeData(); // Close file if (mFile.is_open()) { mFile.flush(); mFile.close(); } // Turn off recording flag mRecording = false; } ``` If there's anything here that looks like it would result in bad data getting appended to the file, please let me know. If not, I'll triple check the input data (in the callback). This data *should* be good, because it works if I copy it to a larger buffer (eg, two minutes) and then save that out.
2011/02/11
[ "https://Stackoverflow.com/questions/4972810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/537002/" ]
The most likely reason is you're writing from the address of the pointer to your buffer, not from the buffer itself. Ditch the "&" in the final mFile.write. (It may have some good data in it if your buffer is allocated nearby and you happen to grab a chunk of it, but that's just luck that your write hapens to overlap your buffer) In general, if you find yourself in this sort of situation, you could try to think how you can test this code in isolation from the recording code: Set up a buffer that has the values 0..255 in it, and then set your "chunk size" to 16 and see if it writes out a continuous sequence of 0..255 across 16 separate write operations. That will quickly verify if your buffering code is working or not.
Shoot, sorry -- had a late night of work and am a bit off today. I forgot to show y'all the actual callback. This is it: ``` // Called when buffer is full void CaptureApp::onData(float * data, int32_t & size) { // Check recording flag and buffer size if (mRecording && size <= BUFFER_LENGTH) { // Save the PCM data to file and reset the array if we // don't have room for this buffer if (mPcmBufferPosition + size >= mPcmBufferSize) writeData(); // Copy PCM data to file buffer copy(mAudioInput.getData(), mAudioInput.getData() + size, mPcmBuffer + mPcmBufferPosition); // Update PCM position mPcmBufferPosition += size; } } ``` Will try y'alls advice and report.
460,952
I saw a practice SAT question on Khan Academy: > > Certified Executive Chef Hilary DeMane has prepared confections for **celebrities, governors, and even** Ronald Reagan. > > > The correct answer is filled in and in boldface. While I find this correct answer most natural, I wonder when it is permissible to add a comma between the adverb and the noun of the last member of the series. I understand that the following is incorrect: > > ... governors, **and even,** Ronald Reagan. > > > But this, with a comma between the adverb "importantly" and "interest rates", seems natural to me: > > Factors that affect bond prices include inflation, credit ratings, **and most importantly, interest rates**. > > > Or is the above not correct either? Should there be a comma before between "and" and "most importantly" as well in order to make it grammatical? > > Factors that affect bond prices include inflation, credit ratings, **and, most importantly, interest rates**. > > > Thanks!
2018/08/20
[ "https://english.stackexchange.com/questions/460952", "https://english.stackexchange.com", "https://english.stackexchange.com/users/241797/" ]
What you're talking about is adding parenthetical nonessential information as denoted by a pair of commas. It's also something that's quite acceptable. However, you do need to make sure that there are *two* commas used. > > ... governors, and even, Ronald Reagan. > > > In this example, the usage is wrong because there is no initial comma. It should be rephrased: > >  . . . governors, and, **even**, Ronald Reagan. > > > Here, **even** is nonessential and could be removed from the sentence without affecting it: > >  . . . governors, and Ronald Reagan. > > > So, **even** needs to have a comma both before it and after it. (Or be used without any commas at all.) Using only a single comma for this purpose is ungrammatical. --- Your last example does this well and is quite correct: > > Factors that affect bond prices include inflation, credit ratings, and, **most importantly**, interest rates. > > > All you need to do is ask yourself if you could remove the word or words between the two commas (along with those two commas) and have the sentence remain grammatical.
The first is a case of an Oxford comma used for emphasizing the end clause. It's not one of a parenthetical as in the other. HTH.
60,665,435
When `MyFgment` appear in screen, I want to set cursor focus on `EditText` in `MyFragment` automatically. I've tried `EditText.requestFocus()`, but it doesn't focus on `EditText`. How can I do??
2020/03/13
[ "https://Stackoverflow.com/questions/60665435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12350049/" ]
set this in your xml ``` android:focusable="true" android:focusableInTouchMode="true" ``` and you can set this on onViewCreated program `editText.isFocusableInTouchMode(); editText.setFocusable(true);`
Add this kotlin extension function ``` fun EditText.focus() { text?.let { setSelection(it.length) } postDelayed({ requestFocus() val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) }, 200) } ``` and call it on your EditText in `onViewCreated`.
42,002,826
I have a page where the user want to add new category to the database, I want to check if the category is already added before in the database or not,if it is new one add it to the database, it is working fine but it adds it many times(equal to the data in the table) i know it is because of `foreach`,how can it be done?and also how to alert to the user that it is already exists? Php code: ``` <?php include_once "connect.php"; $stmt ="SELECT distinct Category_Name FROM Categories"; foreach ($conn->query($stmt) as $row) { if ($row['Category_Name'] != $_POST["CatName"]) { $sql ="INSERT INTO Categories (Category_Name) VALUES (:CatName)"; $result=$conn->prepare($sql); $result->bindparam(':CatName', $_POST["CatName"], PDO::PARAM_INT); $result->execute(); } else { return false; } } ?> ``` Javascript Code: ``` function AddNewCategory() { var CatName=document.getElementById("CatNametxt").value; $.ajax({ type:"POST", url:"add_category.php", data:'CatName=' + CatName, success: function(data) { alert("Category Added Successfully!"); } }) } ``` **Edit1** I changed it to the following and it worked fine,but how to alert to the user that this category is inserted before? ``` $stmt ="SELECT * FROM Categories WHERE Category_Name='".$_POST["CatName"]."'"; $queryresult = $conn->query($stmt)->fetchAll(PDO::FETCH_ASSOC); if (count($queryresult) == 0) { $sql ="INSERT INTO Categories (Category_Name) VALUES (:CatName)"; $result=$conn->prepare($sql); $result->bindparam(':CatName', $_POST["CatName"], PDO::PARAM_INT); $result->execute(); } ```
2017/02/02
[ "https://Stackoverflow.com/questions/42002826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7115432/" ]
Try this: ``` <?php include_once "connect.php"; $stmt ="SELECT distinct Category_Name FROM Categories"; $exists = false; foreach ($conn->query($stmt) as $row) { if ($row['Category_Name'] == $_POST["CatName"]) { $exists = true; } } if(!$exists) { // The category doesn't exist. $sql ="INSERT INTO Categories (Category_Name) VALUES (:CatName)"; $result=$conn->prepare($sql); $result->bindparam(':CatName', $_POST["CatName"], PDO::PARAM_INT); $result->execute(); } return $exists; ?> ``` The idea is to go through all the categories in order to determine if the one defined by the user exists or not. As it is now. Your code inserts the new category each time a category from the database doesn't have the same name. You can also do something like this: ``` $result=$conn->prepare("SELECT COUNT(Category_Name) as total FROM Categories WHERE Category_Name = (:CatName)"); $result->bindparam(':CatName', $_POST["CatName"], PDO::PARAM_STR); while ($row = $result->fetch(PDO::FETCH_ASSOC)) { $exists = $row["total"] > 0; } ``` I don't know `PHP` that well, there my be some syntax errors in this code.
You can make Category\_Name in your data base As index unique So the database can't inserte a duplicated mane. and in your inerte SQl add ON DUPLICATE KEY [Exemple](https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html)
26,514
Is it possible to do the following? Input would be to generate a new AES key, encrypt the private data with that key, encrypt the AES key with the FHE key, and send the FHE-encrypted AES key along with the AES encrypted data to the compute node.
2015/06/25
[ "https://crypto.stackexchange.com/questions/26514", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/25204/" ]
In the first section of this answer I'll assume that through better hardware or/and algorithmic improvements, it has become routinely feasible to exhibit a collision for SHA-1 by a method similar to that of [Xiaoyun Wang, Yiqun Lisa Yin, and Hongbo Yu's attack](https://www.c4i.org/erehwon/shanote.pdf), or [Marc Stevens's attack](https://2012.sharcs.org/slides/stevens.pdf). This has been [achieved publicly](https://shattered.io/) in early 2017, and had been clearly feasible (the effort represents mere hours of the [hashing effort spent on bitcoin mining](https://www.blockchain.com/explorer/charts/hash-rate); but the hardware used for that can't be re-purposed for the attack on SHA-1). Contrary to what is considered in the question, that would *not* allow an attacker *not kowing the HMAC-SHA-1 key* to make an undetected change in a document; that's including if the attacker is able to prepare the document s/he's willing to later alter. One explanation is that the collision attacks on SHA-1 we are considering require knowledge of the state of the SHA-1 chaining variable, and the attacker of HMAC not knowing the key is deprived from that knowledge by the key entering on both extremities of the iteration of rounds in which the message stands in HMAC. A much deeper break of SHA-1's round function would be needed to break HMAC. Not coincidentally, M. Bellare's [*New Proofs for NMAC and HMAC: Security without Collision-Resistance*](https://cseweb.ucsd.edu/%7Emihir/papers/hmac-new.html) shows that security of HMAC holds assuming only weaker properties on its round function than needed for collision resistance of the corresponding hash. What would be possible is for an attacker *knowing the HMAC key* to prepare a document that s/he willing to later alter, that can be altered without changing the MAC. But since the attacker is holding the HMAC key, that's not considered a break of HMAC. --- A [comment](https://crypto.stackexchange.com/q/26510/555#comment61538_26518) asks *when should SHA-1 not be used?* **Original advise, 2015:** It is advisable to quickly phase out SHA-1 in applications requiring collision-resistance (as an image: quickly walk away, as you exit a building which fire alarm rings when there's no smoke). That includes hashing for integrity check or digital signature of documents prepared by others even in part (which is, most documents). If continuing to use SHA-1 has strong operational benefits, it can safely be made an exception by inserting something unpredictable by adversaries before any portion of the message that an adversary can influence. For example, by enforcing an unpredictable certificate serial number at time of request of a certificate, a certification authority could still safely issue certificates using SHA-1 for their internal signature. As explained in the first section of this answer, as long as the key of HMAC-SHA-1 is assumed secret, there is no indication that HMAC-SHA-1 is insecure because it uses SHA-1. If the key is assumed public, or its leak is considered an operational possibility where it is still wanted collision-resistance for HMAC including for message prepared after disclosure of the key, then the precautions discussed in the previous paragraph apply. --- **Update, 2022:** As the saying [attributed to the NSA by Bruce Schneier](https://www.schneier.com/blog/archives/2011/08/new_attack_on_a_1.html) goes: *Attacks only get better; they never get worse*. The current [state of the art](https://www.usenix.org/system/files/sec20-leurent.pdf) finds a new collision in SHA-1 at cost comparable to $2^{61.2}$ hashes (comparing to $2^{69}$ for the [first theoretical attack](https://doi.org/10.1007/11535218_2) and $2^{63}$ for the [first practical attack](https://shattered.io/)). More importantly in practice, a chosen-prefix collision (one with colliding files starting differently and arbitrarily) has become possible, with cost comparable to $2^{63.4}$ hashes, which is entirely practical. Such chosen-prefix collision attack (resp. variations) make it difficult (resp. essentially impossible) for even an expert to detect a planned-in-advance substitution of a document signed with SHA-1, or integrity-protected by HMAC-SHA-1 using a key known to the perpetrator. Still, every piece of advise given in this answer remains valid as far as we know.
When people say HMAC-MD5 or HMAC-SHA1 are still secure, they mean that they're still secure as PRF and MAC. The key assumption here is that the key is unknown to the attacker. $$\mathrm{HMAC} = \mathrm{hash}(k\_2 | \mathrm{hash}(k\_1 | m)) $$ * Potential attack 1: Find a universal collision, that's valid for many keys: Using HMAC the message doesn't get hashed directly, but it has $k\_1$ as prefix. This means that the attacker doesn't know the internal state of the hash when the message starts. Finding a message that collides for most choices is $k\_1$ is extremely hard1. * Potential attack 2: Recover the key For this to succeed the hash function needs much bigger breaks than merely collisions. It's similar to a first pre-image attack, a property that's still going strong for both MD5 and SHA1. On the other hand, if you used a key known to the attacker and the attacker has the ability to find collisions in the underlying hash (for arbitrary IVs), these turn into collisions of HMAC. So if you need security in an unkeyed scenario, use a collision resistant hash, like SHA2 and consider not using HMAC at all. --- 1 I suspects it's not possible (for realistic message sizes) even for computationally unbounded attackers, but proving that is difficult.
2,584,055
The information given in the task: \*X and Y are independent random variables. $\ X$~$R(0,1)$ $\ Y$~$R(0,1)$\* I am then told to calculate: $P(X>1/4)$, expected values and so on. The last problem is the one I am struggling with: *Calculate $P(X+Y>1|Y>1/2)$, (The solution is 3/4)* Somehow I'm unable to solve this. My idea is: Given that both X and Y are uniformly distributed I know that their PDF's are: $\ f\_Y(y)=\frac{1}{b-a}, x \in [a,b]$ $\ f\_X(x)=\frac{1}{b-a}, x \in [a,b]$ Since; $\ X$~$R(0,1)$ $\ Y$~$R(0,1)$ we get: $\ f\_Y(y)=\frac{1}{1-0}, x \in [0,1]$ $\ f\_X(x)=\frac{1}{1-0}, x \in [0,1]$ Since this problem is dealing with conditional I thought I would use the formula $\ f\_{X|Y}(x|y)=\frac{f\_{XY}(x,y)}{f\_Y(y)}$ Since $f\_Y(y)$ is already calculated I need $f\_{XY}(x,y)$ Since X and Y are independent the definition of this independence gives me: $f\_Y(y)·f\_X(x)=f\_{XY}(x,y)$ So: $f\_{XY}(x,y)=\frac{1}{1-0}·\frac{1}{1-0}=1$ This means: $\ f\_{X|Y}(x|y)=\frac{f\_{XY}(x,y)}{f\_Y(y)}=\frac{1}{1}=1$ My idea is then to use the formula $P(A|B)=\frac{P(A \cap B)}{P(B)}$ $P(B)=\int\_{1/2}^{1}\frac{1}{1-0}dy=\frac{1}{2}$ But how do I proceed from here when neither of the pdf's have any variables in them? Given that the integrals that I need to solve has to depend on X or Y I keep getting the wrong solutions when trying to solve it. In other words, im stuck.
2017/12/29
[ "https://math.stackexchange.com/questions/2584055", "https://math.stackexchange.com", "https://math.stackexchange.com/users/516638/" ]
The denominator $(x+1)^2$ is always non-negative. When $x$ tends to $-1$, since the denomiator is slightly larger than zero, while the numerator is negative, the limit diverges to negative infinity.
To decide the sign of the $\infty$ consider e.g. $$\lim \_{x \to 0^+} \quad \frac{1}{x}$$ i.e. $x$ tends to zero via positive values. Everything is positive and the value of $\frac{1}{x}$ simply increases. i.e. $\frac{1}{x} \to \infty$ Consider $$\lim \_{x \to 0^-} \quad \frac{1}{x}$$ i.e. $x$ tends to zero via negative values. Now $\frac{1}{x}$ is negative but gets more and more negative i.e. $\frac{1}{x} \to -\infty$ Your case is essentially $-5/x^2$ and $x^2$ is never negative.
182,116
I'm right before Anor Londo bosses and I need to soul farm to level 69 so I can use soul spear. I would also like to upgrade my pyromancy glove and buy the remaining spells that I can. At the moment I'm level 59. The dragon bridge isn't enough anymore, even with the update. Right now, I'm farming Valley of the Drakes. I kill 2 drakes per run, which gets me 2000 souls in 2 minutes. There has to be a better way. Are there any better places where I can soul farm?
2014/08/25
[ "https://gaming.stackexchange.com/questions/182116", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/86087/" ]
I take it that you're building an Int build then. I myself have a dex build and have been farming in **anor londo** myself a lot by parrying silver knights. After a few tries you get their patterns down and they yield a lot of souls. Because of the crit damage from the parry/riposte you get 20% extra souls. * Silver Knight (spear/sword) : 1000 souls * Silver Knight (dragonslayer bow) : 1300 souls * Silver Knight (spear/sword) Crit : 1200 souls * Silver Knight (dragonslayer bow) Crit : 1560 souls I am not sure how well an int build can exploit this, but they are my primary source of souls.
Since you're in Anor Londo, you can go to the first bonfire and farm the sentinels. They go down fast with a bleeding weapon. This area is also not open to invasion if I remember correctly.
18,949,978
I've been trying to generate a pattern of circles using a for loop. However, when it runs everything looks fine except for the 9th ring of circles which is ever so slightly. Having looked at a print out of numbers for that circle everything looks fine, so I can't work out what is going wrong. However, when I add one to the angle value of that ring. i.e. j (the commented out code) it pretty much corrects. Any idea why this might happen. having looked at all the numbers I can only think it is some math error that I haven't factored in or am I missing something obvious. Thanks! ![ocd trigger warning](https://i.stack.imgur.com/JjRMF.png) ``` ellipse(325,325,15,15); float div = 1; for (int i = i; i < 25; i++) { div = i*6 float segment = 360/div; float radius = (i*20); for (int j = 0; j < 360; j+=segment) { //if (i==8) //{ //println("before " + j); //j+=1; //println("after " + j); //} float x = 325 + (radius*cos(radians(j))); float y = 325 + (radius*sin(radians(j))); ellipse(x, y, 15, 15); } } ```
2013/09/22
[ "https://Stackoverflow.com/questions/18949978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457072/" ]
You get the `segment` as a `float`, but then you use an `int` to calculate the degrees. ``` for (int j=0; j < 360; j+=segment) ``` and ``` float x = 325 + (radius*cos(radians(j))); ``` This is what is causing the rounding errors. And if you make `i` to get a value bigger than `60` the program will never end.
Use `double` instead of float to minimise representation error. Change the for loop to reduce error. ``` for (int k = 0; k < div; k++) { int j = k * 360 / div; ``` This will give you different values for `j` which are likely to be more correct.
3,995,529
I completed the square as to get $(x+1010.5)^2-102110.25 = k^2$ but I don't know where to go from here. Please help, thank you I then got $(2x+2021)^2-4084441=4k^2$ then $(2k-2x-2021)(2k+2x+2021)=43^2\*47^2$
2021/01/22
[ "https://math.stackexchange.com/questions/3995529", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
$$\begin{align}x^2+2021x-a^2&=0, a\in\mathbb Z^{+}&\end{align}$$ $$\begin{align} &\Delta =2021^2+(2a)^2=T^2, T\in\mathbb Z^{+} \\ &\implies (T-2a)(T+2a)=2021^2\\ &\implies \begin {cases} T+2a =\dfrac {2021^2}{m} \\ T-2a=m \end {cases} \\ &\implies a=\dfrac {2021^2-m^2}{4m}\end{align}$$ Then, note that $2021^2=43^2×47^2$ , $a \in\mathbb {Z^{+}}$ ($a \in\mathbb {Z^{+}}$ implies $T \in\mathbb {Z^{+}}$) and $m=1,43,47,47×43, 43×47^2, 47×43^2$ . You can check all cases.
For $x(x+2021)$ to be a square there has to be integers $a,b,c$ such that $$x=ab^2,x+2021=ac^2.$$ Subtracting these two equations we obtain $a(c-b)(c+b)=2021=43\times 47$. Since $43$ and $47$ are primes the only possibilities for $a, c-b$ and $c+b$ are $$(1,43,47),(1,1,2021),(43,1,47),(47,1,43).$$ These give, in turn, $x=ab^2\in \{ 4,1020100,22747,20727\} .$
33,500
How can you indict somebody for a crime that they didn't commit? But they might do. I find that a baffling concept. How is it justified?
2018/11/14
[ "https://law.stackexchange.com/questions/33500", "https://law.stackexchange.com", "https://law.stackexchange.com/users/12479/" ]
> > What is the legal status of predictive policing? > > > You mean [this](https://en.wikipedia.org/wiki/Predictive_policing)? First, "predictive policing" is a very wide concept. When police send officers to a sporting event or a protest rally they are practicing "predictive policing". If we are specifically considering the use of algorithms in making the predictions then that is perfectly legal although there is a moral hazard in perpetuating unfair biases. > > How can you indict somebody for a crime that they didn't commit? > > > Theoretically, you can't - indictments have to follow the offence and they are leveled at the alleged perpetrator of that offence. Practically, it happens all the time - innocent people get indicted for crimes due to all sorts of innocent mistakes, inadvertent biases and sometimes outright maliciousness. I don't see what this has to do with "predictive policing" however.
The determination of whether a person did a thing is made at trial, so actual guilt logically has to be follow the accusation. Whether or not that formal accusation is in the form of a grand jury indictment (as must be the case in US federal crimes, pursuant to the 5th Amendment), or by a prosecutor filing a charging document with the court, this has to be done before the accused is legally proven to have committed the act. There is a legal rule to the effect that if there is not probable cause to say that that the accused committed the alleged act, the charge must be dismissed. So not only do you have to have good-enough reason to think that the accused did the act, you also have to have good enough reason to think that the act too place. A runaway grand jury could indict a person on the belief that he may commit a criminal act, but such an indictment would be dismissed in court because no actual crime had occurred.
58,406,976
Can anyone is facing issue in Manage release in Google play store? When I try to upload an app in production track. It's not opening. I am getting this error. ``` An unexpected error occurred. Please try again later. (3200000) ``` [![enter image description here](https://i.stack.imgur.com/IhIF9.png)](https://i.stack.imgur.com/IhIF9.png)
2019/10/16
[ "https://Stackoverflow.com/questions/58406976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136023/" ]
[An unexpected error occurred. Please try again later. (3200000](https://i.stack.imgur.com/Q3LaV.png) I got this error just now , this error occurs while i need to manage my apk release All App release has same error while i need to manage it , i do not know what happened I do clear browser cache and close all my logged in user This error still came out of my browser , need some one to help .. please EDIT : Hi There who are facing these issue , i just post a question , because i am having this issue as well , but , after i do clear my browser cache , logout all to my google account , close browser windows , and try to clearing all my local cache in from my laptop , wait for at least an hours , Now i am able to manage my app on google play store Hope this will help others Thank you
I used USA proxy and now this error is not coming, everything is working fine. Maybe Google has pushed some bug in certain countries rollout.
62,812,741
``` SQL*Plus: Release 12.2.0.1.0 Production on Thu Jul 9 15:06:37 2020 Copyright (c) 1982, 2016, Oracle. All rights reserved. SQL> conn sys@Databasename as sysdba Enter password: Connected to an idle instance. SQL> shutdown abort; ORACLE instance shut down. SQL> startup nomount; ORA-01078: failure in processing system parameters LRM-00109: could not open parameter file 'C:\APP\ADMINISTRATOR\VIRTUAL\PRODUCT\12.2.0\DBHOME_1\DATABASE\INITdatabasename.ORA' SQL> ``` If I go to `C:\APP\ADMINISTRATOR\VIRTUAL\PRODUCT\12.2.0\DBHOME_1\DATABASE\` There is no file with this name `INITdatabasename.ORA` After search I found that I should create a `pfile` from `spfile`. ``` SQL> create pfile from spfile; create pfile from spfile * ERROR at line 1: ORA-01565: error in identifying file '?=\DATABASE\SPFILE%ORACLE_SID%.ORA' ORA-27041: unable to open file OSD-04002: unable to open file O/S-Error: (OS 5) Access is denied. ``` `SPfile` is available in database folder. But is unable to open. Please help.
2020/07/09
[ "https://Stackoverflow.com/questions/62812741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12240124/" ]
our "fields" are object with text,top and left. So, you can create a function ``` changePosition(event:CdkDragEnd<any>,field) { console.log(field) field.top=+field.top.replace('px','')+event.distance.y+'px' field.left=+field.left.replace('px','')+event.distance.x+'px' } ``` And you call in the .html ``` <div *ngFor="let field of fields;" cdkDrag (cdkDragEnded)="changePosition($event,field)" style="position:absolute;z-index:10" [style.top]="field.top" [style.left]="field.left"> {{field.text}} </div> ``` **Updated** the problem, as Ananthakrishna let me know is that you can drag out of the "dop-zone" one element in drop zone We need use the event `cdkDragDropped` ``` <div *ngFor="let field of fields;" cdkDrag (cdkDragDropped)="changePosition($event,field)" style="position:absolute;z-index:10" [style.top]="field.top" [style.left]="field.left"> {{field.text}} </div> ``` And, in our function changePosition "check" if is droppend inside. I use getBoundingClientRect of the elements relateds: ``` changePosition(event:CdkDragDrop<any>,field) { const rectZone=this.dropZone.nativeElement.getBoundingClientRect() const rectElement=event.item.element.nativeElement.getBoundingClientRect() let top=+field.top.replace('px','')+event.distance.y let left=+field.left.replace('px','')+event.distance.x const out=top<0 || left<0 || (top>(rectZone.height-rectElement.height)) || (left>(rectZone.width-rectElement.width)) if (!out) //If is inside { field.top=top+'px' field.left=left+'px' } else{ //we can do nothing this.fields=this.fields.filter(x=>x!=field) //or eliminate the object } } ``` See the forked [stackblitz](https://stackblitz.com/edit/angular-d6xsgx?file=src%2Fapp%2Fexample%2Fexample.component.html)
It's very easy to achieve your goal with [ng-dnd](https://github.com/ng-dnd/ng-dnd). You can check the [examples](https://ng-dnd.github.io/ng-dnd/examples/index.html#/html5/drop-effects) and have a try. Making a DOM element draggable ------------------------------ ```html <div [dragSource]="source"> drag me </div> ``` ``` constructor(private dnd: DndService) { } source = this.dnd.dragSource("DRAGME", { beginDrag: () => ({ name: 'Jones McFly' }), // other DragSourceSpec methods }); ``` Making a DOM element into a drop target --------------------------------------- ```html <div [dropTarget]="target"> drop on me </div> ``` ``` constructor(private dnd: DndService) { } target = this.dnd.dropTarget("DRAGME", { drop: monitor => { console.log('dropped an item:', monitor.getItem()); // => { name: 'Jones McFly' } } }) ```
57,594,142
I'm getting the same error and cant seem to understand where it comes from. tried messing with the constraints but im keep coming back to this specific problem. Error: ``` E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.rapp, PID: 11288 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rapp/com.example.rapp.ui.CheckListActivity}: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class ConstraintLayout at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class ConstraintLayout Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class ConstraintLayout Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.ConstraintLayout" on path: DexPathList[[zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/base.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_resources_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/lib/x86, /system/lib, /vendor/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125) at java.lang.ClassLoader.loadClass(ClassLoader.java:379) at java.lang.ClassLoader.loadClass(ClassLoader.java:312) at android.view.LayoutInflater.createView(LayoutInflater.java:606) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:703) at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:68) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:720) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:788) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) at android.view.LayoutInflater.rInflate(LayoutInflater.java:863) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.rInflate(LayoutInflater.java:866) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at android.view.LayoutInflater.inflate(LayoutInflater.java:374) at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) at com.example.rapp.ui.CheckListActivity.onCreate(CheckListActivity.java:62) E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:7009) at android.app.Activity.performCreate(Activity.java:7000) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Suppressed: java.io.IOException: No original dex files found for dex location /data/app/com.example.rapp-re4jZb52NhxBq505zHulTA==/split_lib_resources_apk.apk at dalvik.system.DexFile.openDexFileNative(Native Method) at dalvik.system.DexFile.openDexFile(DexFile.java:353) at dalvik.system.DexFile.<init>(DexFile.java:100) at dalvik.system.DexFile.<init>(DexFile.java:74) at dalvik.system.DexPathList.loadDexFile(DexPathList.java:374) at dalvik.system.DexPathList.makeDexElements(DexPathList.java:337) at dalvik.system.DexPathList.<init>(DexPathList.java:157) at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65) at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64) at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:73) at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:88) at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:69) at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:35) at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:693) at android.app.LoadedApk.getClassLoader(LoadedApk.java:727) at android.app.LoadedApk.getResources(LoadedApk.java:954) at android.app.ContextImpl.createAppContext(ContextImpl.java:2270) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5639) at android.app.ActivityThread.-wrap1(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656) ... 6 more Application terminated. ``` The XML file activity\_check\_list.xml: ``` <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/constraintLayout1" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ui.CheckListActivity"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.constraint.ConstraintLayout android:id="@+id/view_container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </ScrollView> </android.support.constraint.ConstraintLayout> ``` And the class that showed up in the error CheckListActivity.java: ```java package com.example.rapp.ui; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AppCompatActivity; import com.example.rapp.R; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; public class CheckListActivity extends AppCompatActivity implements CheckListView { // states for buttons. public static final int ADD_NEW_ITEM = 1; public static final int REMOVE_LAST_ITEM = 2; public static final int GOT_FOCUS = 3; public static final int REMOVE_ITEM = 4; ArrayList<String> ingredientNames = new ArrayList<>(); // list of ingredients. private ConstraintLayout container; private CheckListPresenter presenter; private String jsonArrayStr; // method to read json from assets folder. public String loadJSONFromAsset(Context context) { String json = null; try { InputStream is = context.getAssets().open("foods.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { json = new String(buffer, StandardCharsets.UTF_8); } } catch (IOException ex) { ex.printStackTrace(); return null; } System.out.println("success!"); return json; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { jsonArrayStr = savedInstanceState.getString("json_array", ""); } //**error is happening here. ** setContentView(R.layout.activity_check_list); container = findViewById(R.id.view_container); presenter = new CheckListPresenterImpl(this, getApplicationContext()); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putString("json_array", presenter.getCheckListData()); } @Override public ConstraintLayout getContainer() { return container; } @Override public String getSavedData() { return jsonArrayStr; } } ``` I tried adding compile 'com.android.support.constraint:constraint-layout:1.0.2' to the xml but with no success. EDIT: here is the gradle.build file (tried constraint-layout 1.1.2): ``` apply plugin: 'com.android.application' android { compileSdkVersion 28 buildToolsVersion "29.0.1" defaultConfig { applicationId "com.example.rapp" minSdkVersion 15 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } ```
2019/08/21
[ "https://Stackoverflow.com/questions/57594142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5352085/" ]
used the answer given here: <https://stackoverflow.com/a/53061877/5357676> unchecked "Enable Instant Run to hot swap code/resource changes on deploy" in Setting > Build, Execution, Deployment > Instant run
You can reference here to import constraint layout into the project [Add ConstraintLayout to your project](https://developer.android.com/training/constraint-layout#add-constraintlayout-to-your-project) Add this in you app -> build.gradle file ``` dependencies { implementation 'com.android.support.constraint:constraint-layout:1.1.2' } ``` In the toolbar or sync notification, click Sync Project with Gradle Files.
27,827,234
How can I make the `onKeyPress` event work in ReactJS? It should alert when **`enter (keyCode=13)`** is pressed. ``` var Test = React.createClass({ add: function(event){ if(event.keyCode == 13){ alert('Adding....'); } }, render: function(){ return( <div> <input type="text" id="one" onKeyPress={this.add} /> </div> ); } }); React.render(<Test />, document.body); ```
2015/01/07
[ "https://Stackoverflow.com/questions/27827234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544079/" ]
For me `onKeyPress` the `e.keyCode` is always `0`, but `e.charCode` has correct value. If used `onKeyDown` the correct code in `e.charCode`. ``` var Title = React.createClass({ handleTest: function(e) { if (e.charCode == 13) { alert('Enter... (KeyPress, use charCode)'); } if (e.keyCode == 13) { alert('Enter... (KeyDown, use keyCode)'); } }, render: function() { return( <div> <textarea onKeyPress={this.handleTest} /> </div> ); } }); ``` [React Keyboard Events](https://facebook.github.io/react/docs/events.html#keyboard-events).
Keypress event is deprecated, You should use Keydown event instead. <https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event> ``` handleKeyDown(event) { if(event.keyCode === 13) { console.log('Enter key pressed') } } render() { return <input type="text" onKeyDown={this.handleKeyDown} /> } ```
31,684,372
My table view is divided in two sections : completed tasks and to do. When I hit delete I want the to do task in the completed task and vice versa. This is my viewDidAppear: ``` override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } ``` and this my commit: ``` func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { let thisTask = fetchedResultsController.objectAtIndexPath(indexPath) as! TaskModel if indexPath.section == 0 { thisTask.completed = true } else { thisTask.completed = false } (UIApplication.sharedApplication().delegate as! AppDelegate).saveContext() } ``` this the controllerDidChange: ``` func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.reloadData() } ```
2015/07/28
[ "https://Stackoverflow.com/questions/31684372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3686341/" ]
I solved this problem by using following code in settings.gradle ``` include ‘:project2', ‘dev:project1' project(':project1').projectDir = new File(settingsDir, ‘../../../project1’) ``` build.gradle ``` dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile project(':project1') } ```
Assuming that you have the `settings.gradle` file placed at root folder: `include ':dev:project1', ':dev:android:apps:project2'`
14,543,363
I have a c++ library that provides an object with complicated logic. During data processing, this object outputs lots of things to std::cout (this is hardcoded now). I would like the processing output not to go to standard output but to a custm widget (some text displaying). I tried to create a `std::ostream` class member, set it with a parameter (std::cout for console application and some other ostream handled inside GUI application). But the compiler throws me following errors: ``` [ 14%] Building CXX object src/core/CMakeFiles/PietCore.dir/pvirtualmachine.cpp.o /usr/include/c++/4.6/ostream: In constructor ‘PVirtualMachine::PVirtualMachine(QString)’: /usr/include/c++/4.6/ostream:363:7: error: ‘std::basic_ostream::basic_ostream() [with _CharT = char, _Traits = std::char_traits]’ is protected /home/tomasz/Development/C++/piet/src/core/pvirtualmachine.cpp:33:50: error: within this context In file included from /usr/include/c++/4.6/ios:45:0, from /usr/include/c++/4.6/ostream:40, from /usr/include/c++/4.6/iterator:64, from /usr/include/qt4/QtCore/qlist.h:50, from /usr/include/qt4/QtCore/qvector.h:48, from /usr/include/qt4/QtGui/qpolygon.h:45, from /usr/include/qt4/QtGui/qmatrix.h:45, from /usr/include/qt4/QtGui/qtransform.h:44, from /usr/include/qt4/QtGui/qimage.h:45, from /usr/include/qt4/QtGui/QImage:1, from /home/tomasz/Development/C++/piet/src/core/pcodepointer.h:17, from /home/tomasz/Development/C++/piet/src/core/pblockmanager.h:9, from /home/tomasz/Development/C++/piet/src/core/pvirtualmachine.h:10, from /home/tomasz/Development/C++/piet/src/core/pvirtualmachine.cpp:4: /usr/include/c++/4.6/bits/ios_base.h: In member function ‘std::basic_ios& std::basic_ios::operator=(const std::basic_ios&)’: /usr/include/c++/4.6/bits/ios_base.h:791:5: error: ‘std::ios_base& std::ios_base::operator=(const std::ios_base&)’ is private /usr/include/c++/4.6/bits/basic_ios.h:64:11: error: within this context In file included from /usr/include/c++/4.6/iterator:64:0, from /usr/include/qt4/QtCore/qlist.h:50, from /usr/include/qt4/QtCore/qvector.h:48, from /usr/include/qt4/QtGui/qpolygon.h:45, from /usr/include/qt4/QtGui/qmatrix.h:45, from /usr/include/qt4/QtGui/qtransform.h:44, from /usr/include/qt4/QtGui/qimage.h:45, from /usr/include/qt4/QtGui/QImage:1, from /home/tomasz/Development/C++/piet/src/core/pcodepointer.h:17, from /home/tomasz/Development/C++/piet/src/core/pblockmanager.h:9, from /home/tomasz/Development/C++/piet/src/core/pvirtualmachine.h:10, from /home/tomasz/Development/C++/piet/src/core/pvirtualmachine.cpp:4: /usr/include/c++/4.6/ostream: In member function ‘std::basic_ostream& std::basic_ostream::operator=(const std::basic_ostream&)’: /usr/include/c++/4.6/ostream:57:11: note: synthesized method ‘std::basic_ios& std::basic_ios::operator=(const std::basic_ios&)’ first required here /home/tomasz/Development/C++/piet/src/core/pvirtualmachine.cpp: In member function ‘void PVirtualMachine::setOutput(std::ostream)’: /home/tomasz/Development/C++/piet/src/core/pvirtualmachine.cpp:216:11: note: synthesized method ‘std::basic_ostream& std::basic_ostream::operator=(const std::basic_ostream&)’ first required here ``` I'd be glad if someone pointed me out what is wrong, because I've got no idea... My code looks like this: * .h file ``` class PVirtualMachine { private: std::ostream output; [...] public: void setOutput(std::ostream); [...] }; ``` * .cpp file ``` void PVirtualMachine::setOutput(std::ostream os) { output = os; } ```
2013/01/27
[ "https://Stackoverflow.com/questions/14543363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769384/" ]
You've got two options here: * Use references, or * Use pointers You can't use normal instances because `ostream` is non-copyable. **Using references (direct reference to an already-instantiated `ostream`)** ``` class PVirtualMachine { private: std::ostream & output; [...] public: PVirtualMachine(std::ostream &); // Reference must be initialized on construction. [...] }; ``` *Advantages:* * No pointer syntax. * *Should* always refer to a valid instance of `std::ostream`, as long as the original variable is not deleted. *Disadvantages:* * The `PVirtualMachine` class must be constructed with the output reference in the initialization list, otherwise it will not compile. * Cannot change the reference once it has been initialized. * Cannot work with move-assignment operators (i.e. `operator=(PVirtualMachine &&)`) **Using pointers (optional reference to object)** ``` class PVirtualMachine { private: std::ostream * output; [...] public: void setOutput(std::ostream *); [...] }; ``` *Advantages:* * Can be instantiated as a null pointer. * Can be passed around easily. * Can be updated to point to a new `std::ostream` instance. * Can be created internally or externally to the PVirtualMachine instance. * Works with move-assignment operator. *Disadvantages:* * Pointer syntax. * Must check for null references when accessing the ostream and/or in the constructor.
I would actually use an ostream instance in the module I might want to debug. Note that there is no default constructor for this type, you have to pass a pointer to a streambuffer, but that pointer can be null. Now, when/if you want to capture the module's output, you just attach a streambuffer to it using `rdbuf()`. This streambuffer can be std::cout's streambuffer, but it can also be a `std::stringbuf` or `std::filebuf` or some self-written one that automatically redirects the output to some window. One caveat: Output without streambuffer will set the failbit (or even badbit?) so you have to call `clear()` on the output stream after changing the streambuffer. Also note that you must manually manage the lifetime of this streambuffer and the streams referencing it, there is no ownership transfer and automatic cleanup involved.
19,734
Today I was investigating an issue with a Microsoft DLL, `mscordacwks.dll`, which is part of the .NET framework. I've seen it many times before and it always was a regular PE file, meaning that it started with the magic `MZ`. However, the file today starts with `DCD` in ASCII. I could only find a reference to ELF binaries that use `DCD` in the disassembled code. However, this is about `DCD` as the first three bytes of the file. Here's the start of the DLL: ``` Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00000000 44 43 44 01 38 01 EE 42 00 00 0A 00 50 41 33 30 DCD.8.îB....PA30 00000010 80 16 D7 D5 DE B1 9D 01 B0 4E 10 D0 C7 04 0C C4 €.×ÕÞ±..°N.ÐÇ..Ä 00000020 84 D6 08 01 42 01 04 00 88 FB 17 32 00 00 00 00 „Ö..B...ˆû.2.... 00000030 00 00 08 7D DE D3 AA 02 A0 2C AA AA AA AA AA AA ...}ÞÓª. ,ªªªªªª 00000040 AA AA AA AA AA 1A AA AA AA 1A AA AA AA AA A1 01 ªªªªª.ªªª.ªªªª¡. 00000050 20 D2 A1 AA AA AA AA AA AA AA AA AA 22 2A AA AA Ò¡ªªªªªªªªª"*ªª 00000060 AA AA A1 8D 09 00 FF 3F 00 1C F4 3F 00 F0 FF 51 ªª¡...ÿ?..ô?.ðÿQ 00000070 00 F0 04 00 FF 01 74 50 66 80 88 D0 1A 00 68 68 .ð..ÿ.tPf€ˆÐ..hh 00000080 44 33 33 00 00 00 00 00 30 65 97 00 50 67 64 96 D33.....0e—.Pgd– 00000090 28 6E 66 90 71 23 8E E3 B8 26 E2 54 1A 62 12 23 (nf.q#Žã¸&âT.b.# 000000A0 12 8B C5 20 63 92 18 44 C4 71 1A 44 E2 C4 48 48 .‹Å c’.DÄq.DâÄHH 000000B0 1D CB 63 C7 6D EC 36 96 D8 21 26 91 10 93 88 EB .ËcÇmì6–Ø!&‘.“ˆë 000000C0 9A C4 B1 3C 76 0C 2A 31 22 B5 E3 C4 24 4E 24 A4 šÄ±<v.*1"µãÄ$N$¤ 000000D0 31 00 88 53 23 71 EC 38 91 39 76 10 93 D8 42 E2 1.ˆS#qì8‘9v.“ØBâ 000000E0 98 D4 6E 6A 22 69 52 8B 91 04 47 3E BC 36 2D CD ˜Ônj"iR‹‘.G>¼6-Í 000000F0 E8 4A AB 6F 99 12 6D C3 B2 61 5E 86 8E 0E 43 A7 èJ«o™.mòa^†Ž.C§ ``` Usually, these DLLs are ~1.7MB in size. However, this one is only 3kB. I found it in the folder `C:\Windows\WinSxS\amd64_netfx-mscordacwks_b03f5f7f11d50a3a_10.0.17134.1_none_a06aa12b896d6ba9` **What file format is that? And, if it's simple to answer, how is Windows able to load it?** I found more files of this kind with up to 51kB in size and it seems that the `PA30` part is also common. Some background information on why I'm working with the file: `mscordacwks.dll` is `MS` for Microsoft, `COR` for the .NET framework, `DAC` for data access control and `WKS` for workstation. When debugging a .NET application, it's that DLL that can give information about the memory layout of .NET objects etc. Usually it's used along with the SOS extension for WinDbg. Sometimes, developers have a wrong version of mscordacwks.dll, which makes SOS complain about the wrong version. So I was looking on my PC whether I could find a version that matches.
2018/10/26
[ "https://reverseengineering.stackexchange.com/questions/19734", "https://reverseengineering.stackexchange.com", "https://reverseengineering.stackexchange.com/users/3355/" ]
Looks like these files use a variation of the delta compression format ([MSDelta](https://msdn.microsoft.com/en-us/library/bb417345.aspx)) used previously for the Windows Update packages. I found [a project](https://github.com/hfiref0x/SXSEXP) which claims to decompress such files: > > Supported file types > ==================== > > > * DCN v1 > * DCM v1 > * DCS v1 > * DCD v1 > > > Type descriptions > ================= > > > * Header Sign: 0x44 0x43 0x4E 0x01, DCN 01 (packed IPD PA30) > * Header Sign: 0x44 0x43 0x4D 0x01, DCM 01 (packed IPD PA30, source manifest required, wcp) > * Header Sign: 0x44 0x43 0x53 0x01, DCS 01 (packed LZMS, can have multiple blocks) > * Header Sign: 0x44 0x43 0x44 0x01, DCD 01 (packed IPD PA30, delta, source file required) > * Header Sign: 0x44 0x43 0x48 0x01, DCH 01 (not packed, header only) > * Header Sign: 0x44 0x43 0x58 0x01, DCX 01 (unknown, only supported by Windows 10) > > > ...but could not get it working so far.
These file are created using PatchAPI and MSDelta API: [Link to MSDN article on subject](https://docs.microsoft.com/en-us/windows/win32/devnotes/msdelta)
38,100
I understand that some people who speak Inuktitut self-designate as "Inuit" which allegedly means "people", or "human beings" or something similar. I've heard the same about people who are described with the exonym "Shoshone" calling themselves "newe" (or a similar term), which is supposed to mean "humans" or "people". Similar translations of endonyms as "people" or "human" seem to exist elsewhere. But I don't understand how this works. Let's say in Inuktitut, is Inuit only used to self-refer to a more ore less defined group of people? But then the translation of "people" sounds highly misleading. Let's assume the etymology of Pусский ("Russian") became obscured, but people in the area of today's Russia still referred to themselves as "Pусский". Then it certainly would be misleading to say "many people in Eastern Europe and northern Asia call themselves 'Pусский', which in their language simply means 'humans' ". Or are endonyms such as newe or Inuit used as an endonym in one context, but in other contexts used to describe other people in general as well? Thus would it be, depending on context, be correct to say in Shoshoni "there are about 1000 newe, most of them in Idaho", and "there are currently living 8 billion newe on Earth"? I've asked this question in the linguistics subreddit, and the answers that came up stated either: 1. newe and Inuit can mean people in general or people of the specific group, depending on context 2. newe and Inuit can mean only people of the specific group, in which case translating both to "people" or "humans" is misleading 3. newe and Inuit meant people in general in the past and later became an endonym after intense context to other groups outside. I find option 3 believable for Inuit, who may have had little contact to culturally and linguistically different groups, but not so plausible for newe/Shoshones. I understand that there may not be a single answer for all groups in which this phenomenon exists, but I would be very grateful for some input.
2021/01/19
[ "https://linguistics.stackexchange.com/questions/38100", "https://linguistics.stackexchange.com", "https://linguistics.stackexchange.com/users/31554/" ]
From the perspective of linguistics, the question is meaningless though well-intentioned. "Word" is not a well-defined technical concept in linguistics (or, some people may have concocted a definition of "word" for their purposes, but there isn't even a widely-believed definition). The best definition is "a maximal string of letters not containing spaces", and that's really not very good (not all writing systems use spaces, plus that means that unwritten languages don't have words). One approach has been to equate "word" with "syntactic terminal", which simply swaps the question to "what is a syntactic terminal?". In contemporary Minimalist syntax, verbs especially are composed of many many nodes which still are realized as "a word" in a language like Latin (with tense, aspect, person and number agreements each of which contributes a syntactic node). There are also phonological accounts which appeal (circularly) to some property of assumed words (stress on the penultimate syllable of the word; a requirement to have at least 2 syllables in the word). It seems to be true that anything that a naive speaker of a language can utter alone is *at least* a word, therefore an English speaker can't say "gira" which is a sub-part of "giraffe" and a Saami speaker can't say "beatna" which is a sub-part of [beatnag-a] "dog (acc. sg)". Clearly, not every utterance is a word. If you define "word" as a *minimal* utterance, then you would exclude the German and Turkish examples as "not words" (they are not minimal). But then "oxen" and "cats" are not words, because then contain words – "ox, cat". And that just seems wrong. There *does* appear to be a phonological object, a grouping of many syllables into a thing, where rules apply within that thing, or with reference to the thing ("no obstruents at the end of the \_\_\_"), which we call the phonological word, or ω. This thing isn't "defined", it is or may be constructed, with language-specific rules. When you find that a large sub-part of an "utterance" has a certain kind of coherence w.r.t. phonological rules, you can call that unit a "(P-)word". But it turns out that this ω thing is not always coherent in a language, and clitics can present contradictory evidence where they partially act like they are "in the word" and partially act like they are outside. Hence, most linguists have abandoned the concept of "word" as a coherent technical concept.
There are double leş-tir suffix in muvaffakiyetsizleştiricileştir- so it is non-sense. If you want you may add more suffixes like this to any word and you may reach a gibberish string sounds like Turkish.
57,529,346
I have a 3 box Solr cloud setup with ZooKeeper, each server has a Solr and ZK install (not perfect I know). Everything was working fine until a network outage this morning. Post outage boxes A and C came back as expected. Box B did not, a restart of the Solr service revealed an error which states `A previous ephemeral live node still exists. Solr cannot continue.` Upon looking in the B node ZooKeeper `Live_Nodes` path the Solr install is already showing as an active live node even though Solr is off. This node is not shown on boxes A and B within the `Live_nodes` path. I'm also unable to `delete` or `rmr` this node because ZooKeeper is telling that it doesn't exist. I have attempted `Solr stop -all` in case there was a hidden process that I wasn't seeing but Solr states that there are no instances running. Next move was installing a fresh ZooKeeper instance on B. After that was up a `ls /live_nodes` continues showing this solr instance that doesn't exist. Any help is appreciated. Thank you.
2019/08/16
[ "https://Stackoverflow.com/questions/57529346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10287010/" ]
My guess is that you might want to design an expression, maybe similar to: ``` :\s*(?:[^;\r\n]*;)?\s*(.*)$ ``` ### [Demo](https://regex101.com/r/zPO6FW/1/)
One option is to use an [alternation](https://www.regular-expressions.info/alternation.html) to first check if the string has no `;` If there is none, then match until the first `:` and capture the rest in group 1. In the case that there a `;` match until the first semicolon and capture the rest in group 1. For the logic stated in the question: * If the string has a semicolon, I want to match anything after the first one. * If it has no semicolon, I want to match everything after the first colon You could use: ``` ^(?:(?!.*;)[^\r\n:]*:|[^;\r\n]*;)[ \t]*(.*)$ ``` **Explanation** * `^` Start of string * `(?:` Non capturing group + `(?!.*;)` [Negative lookahead](https://www.postgresql.org/docs/11/functions-matching.html) (supported by Postgresql), assert string does not contain `;` + `[^\r\n:]*:` If that is the case, match 0+ times not `:` or a newline, then match `:` + `|` Or + `[^;\r\n]*;` Match 0+ times not `;` or newline, then match `;` * `)` Close non capturing group * `[ \t]*` Match 0+ spaces or tabs * `(.*)` Capturing group 1, match any char 0+ times * `$` End of string [Regex demo](https://regex101.com/r/MDbunf/1) | [Postgresql demo](https://rextester.com/UZXK25350)
41,716,125
How to set minimum date in **bootstrap datetimepicker 2.0**. In 4.0 we can use `minDate` is there any way to set this in version 2.0
2017/01/18
[ "https://Stackoverflow.com/questions/41716125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5434280/" ]
Because the OP said it was an AngularJS datepicker and I never had any contact with Angular, myself not being a front-end guy, I wanted to learn something and now I am sharing it with you, for whatever it is worth. Here is a Geb test which does not use any JS, but gathers information from and interacts with the Angular datepicker purely by means of Geb or Selenium. The test shows how to 1. get the currently selected date from the datepicker's text field via `myNavigator.singleElement().getAttribute("value")` (also works for inactive controls), 2. get the currently selected date by opening the datepicker and finding the highlighted date in the calendar (only works for active controls, of course), 3. rather tediously interact with the datepicker, selecting the current year's Xmas Day (Dec-25) by * opening the datepicker, * clicking on the current month in order to open the month of year selector, * clicking on December, effectively closing the month selector again, * clicking on day 25, effectively closing the datepicker again, * finally checking whether the right date was set by reading the text label just like in example #1. **Page:** ```java package de.scrum_master.stackoverflow import geb.Page import geb.navigator.Navigator import java.time.Month import java.time.format.TextStyle import static java.util.Calendar.* class DatePickerPage extends Page { static url = "https://material.angularjs.org/1.1.2/demo/datepicker" static at = { heading == "Datepicker" } static now = new GregorianCalendar() static content = { heading { $("h2 > span.md-breadcrumb-page.ng-binding").text() } datePickerButtons { $("md-datepicker > button") } datePickerInputFields { $(".md-datepicker-input") } activeDatePicker(required: false) { $(".md-datepicker-calendar-pane.md-pane-open") } selectedDate { activeDatePicker.$(".md-calendar-selected-date") } currentMonthLabel { activeDatePicker .$("td.md-calendar-month-label", text: "${getMonthShort(now)} ${now.get(YEAR)}") } selectedMonth(required: false) { $("td.md-calendar-selected-date") } } String getDatePickerValue(Navigator datePickerInputField) { datePickerInputField.singleElement().getAttribute("value") } Navigator getMonthLabel(Calendar calendar) { $(".md-calendar-month-label", text: "${calendar.get(YEAR)}").closest("tbody") .$("span", text: getMonthShort(calendar)).closest("td") } Navigator getDayOfMonthLabel(Calendar calendar) { activeDatePicker .$(".md-calendar-month-label", text: "${getMonthShort(calendar)} ${calendar.get(YEAR)}") .closest("tbody") .$("span", text: "${calendar.get(DAY_OF_MONTH)}") .closest("td") } String getMonthShort(Calendar calendar) { Month .of(calendar.get(MONTH) + 1) .getDisplayName(TextStyle.FULL, new Locale("en")) .substring(0, 3) } } ``` **Test:** ```java package de.scrum_master.stackoverflow import geb.module.FormElement import geb.spock.GebReportingSpec import spock.lang.Unroll import static java.util.Calendar.* class DatePickerIT extends GebReportingSpec { def now = new GregorianCalendar() def xmas = new GregorianCalendar(now.get(YEAR), 12 - 1, 25) @Unroll def "Get selected date from Angular date label"() { when: "a date picker on the Angular demo page is chosen" DatePickerPage page = to DatePickerPage def datePickerInputField = page.datePickerInputFields[datePickerIndex] then: "that date picker instance is (in-)active as expected" datePickerInputField.module(FormElement).enabled == isEnabled when: "the active date is read from the date picker's text input field" String activeDateString = page.getDatePickerValue(datePickerInputField) String todayString = "${now.get(MONTH) + 1}/${now.get(DAY_OF_MONTH)}/${now.get(YEAR)}" then: "it is today" todayString == activeDateString where: datePickerIndex << [0, 1, 2, 3, 4, 5, 6, 7, 8] isEnabled << [true, false, true, true, true, true, true, true, true] } @Unroll def "Get selected date from opened Angular date picker"() { when: "a date picker on the Angular demo page is chosen" DatePickerPage page = to DatePickerPage def datePickerButton = page.datePickerButtons[datePickerIndex] then: "that date picker instance is active (not greyed out)" datePickerButton.module(FormElement).enabled when: "the calendar button for the date picker is clicked" datePickerButton.click() then: "the date picker pop-up opens, displaying the current month" waitFor 3, { page.activeDatePicker.displayed } when: "the active date's timestamp is read from the highlighted day in the calendar" def selectedDateMillis = page.selectedDate.attr("data-timestamp") as long def sinceMidnightMillis = now.getTimeInMillis() - selectedDateMillis then: "it is today" sinceMidnightMillis >= 0 sinceMidnightMillis < 24 * 60 * 60 * 1000 where: datePickerIndex << [0, 2, 4, 5, 6, 7, 8] } def "Set date in Angular date picker"() { when: "the first date picker's calendar button on the Angular demo page is clicked" DatePickerPage page = to DatePickerPage page.datePickerButtons[0].click() then: "the date picker pop-up opens, displaying the current month" waitFor 3, { page.activeDatePicker.displayed } when: "the current month label is clicked" page.currentMonthLabel.click() then: "the month selection page opens" waitFor 3, { page.selectedMonth.displayed } page.selectedMonth.text() == page.getMonthShort(now) when: "December for the current year is selected" page.getMonthLabel(xmas).click() then: "the month selection page closes again" waitFor 3, { !page.selectedMonth.displayed } when: "Xmas Day (25) is selected on the month calendar" page.getDayOfMonthLabel(xmas).click() then: "the date picker pop-up closes again" waitFor 3, { !page.activeDatePicker.displayed } when: "the active date is read from the date picker's text input field" String activeDateString = page.getDatePickerValue(page.datePickerInputFields[0]) String xmasDayString = "${xmas.get(MONTH) + 1}/${xmas.get(DAY_OF_MONTH)}/${xmas.get(YEAR)}" then: "it is Xmas Day of the current year" xmasDayString == activeDateString } } ``` The advantage of this approach is obvious: You only interact with the page in a way the user would/could also do, thus avoiding to manipulate the page in a way impossible for a user (which would result in a bad test). **Update:** I refactored the code into using a page object.
Use following code to resolve the issue: ```java js.exec( "document.getElementsByClassName('ui-form-control ng-isolate-scope')[0]" + ".removeAttribute('readonly')" ) ```
705,435
I'm trying to look for something that I'm not used to. My search is related to Tidal forces and the purpose is: making a qualitative explanation (@ High School level) of this phenomenon, using daily life situations to "build the model in my students' mind". One idea one could come across is: fishing schedules at different moon phases... To do so, I explained this to my 80 years old grandmother and she made an excellent explanation from the questions I did to her. In summary: * Could you imagine you are in a space without gravity? Could you tell me what do you see when we pour water? What shape do you see? (Expected: a sphere. She invoked gravity) * What do you think about the sphere, in this experiment in which you are now, eyes closed no gravity, if now I add a mass near to the bubble? (Expected: a deformation. She said: I'd see a "tear"/"eggplant" shape, pointing to the mass object) * And what do you imagine it would happen if now you add a solid ball inside the deformed tear bubble you see? (Expected: a change in the shape towards the center. She said: what I expected! "the deformation would be less perceptible because the solid ball is pulling water to its center). * Why does it points to the external mass? (Expected and answered: gravity is pulling towards it. She said: it would be important to consider each mass to describe what would happen) * Now I asked what would happen if the water bubble was now made of another material: I mentioned oil. She said the deformation would be modified. Now I asked her to move the external mass, orbiting around the deformed bubble with the solid ball inside it. She said that the "bulge" (can't translate the exact word she used because we didn't talk in english...) would be moving, following the orbit of this object. She didn't mention a lag angle or time, and I find it OK. because she only studied physics @ school when she was in middle school... * I tried to ratify the position of the solid ball inside the deformed bubble, and she said again it'd be @ the center. I asked her if she can relate it to any phenomenon she knows and she explained me about tides on the sea, telling me that there are 4 each day: two high and two low tides. This was very surprising. Having this in consideration, I'm convinced that 16 year old students can do great at this, so I'm doing a video. I thought that a good idea would be to bring a daily example of this "water bubble" concept, floating in space. The only resource I find is this kind of experiment: ![Bubble](https://static.businessinsider.com/image/561919c29dd7cc04308b5811/image.gif) but, obviously, it won't show what happen when a mass object is near to the bubble. **Question**: Can you think about an example, analogy or metaphore to illustrate what is happening as it's understood? for instance: using ferromagnetic fluids to explain the effects of a force on a fluid?
2022/04/25
[ "https://physics.stackexchange.com/questions/705435", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/240433/" ]
I like the second diagram. The downward force is the weight of the car (from gravity). (That can be broken into components; one backwards and one perpendicular to the road. The normal force (up and to the left is from the road reacting to the perpendicular component of gravity. The backward force (from friction with the air and deformation of the tires) would work the backward component of gravity. Finally, the forward force is a static friction force from the road acting on the bottom of the tires (resulting from wheels being turned by the engine). At a constant speed, the vector sum of these forces will be zero.
At the level you are asking about the system that you are considering (the car) should be treated as a point mass at the centre of mass of the car. After all in a real car there are two (four) normal forces, all not necessarily equal, and the same number of frictional forces which are not shown separately. So the first or second diagram might be acceptable but certainly not the third one. Although the length of the vectors are often an indication of the relative magnitudes of the forces this is not always the case. However, given that you have stated that your scheme of requires free body diagrams to show the relative magnitudes then the second diagram does follow the convention used at your school although for year 7 students I would be pleased if they had drawn the first diagram (with perhaps a bonus for the second diagram). Even then you would have to check that the lines of action of all the forces went though the same point (which is not true for diagrams one and two) and check the relative lengths of the normal and gravitational force vectors! MIT have produced a booklet about [Free Body Diagrams](https://ocw.aprende.org/resources/res-tll-004-stem-concept-videos-fall-2013/videos/representations/free-body-diagrams/MITRES_TLL-004F13_FBD_IG.pdf) which you may find of use?
355,833
I have been searching for a simple way to convert a dataset from a [PostgreSQL](http://en.wikipedia.org/wiki/PostgreSQL) database to JSON for use in a project that I am building. This is my first time using JSON, and I have found it really tricky to find a simple way of doing this. I have been using a StringBuilder at the moment to create a JSON string from the information in the dataset, but I have heard that it is possible to do this very simply with [.NET](http://en.wikipedia.org/wiki/.NET_Framework) 3.5 using the `System.Runtime.Serialization` namespace, though I have yet to find a simple article or blog on how this is done! What is the easiest way to do this?
2008/12/10
[ "https://Stackoverflow.com/questions/355833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
For others looking at this topic: Here is the simplest way to convert a dataset to a JSON array as `json_encode` ([PHP](http://php.net/manual/en/function.json-encode.php)) does with ASP.Net: ``` using Newtonsoft.Json; public static string ds2json(DataSet ds) { return JsonConvert.SerializeObject(ds, Formatting.Indented); } ```
Maybe you've heard about the [system.runtime.serialization.json](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.aspx) namespace in the newly announced [*.NET Framework 4.0*](http://www.microsoft.com/net/dublin.aspx).
2,570,131
I'm kind of lost as to how to do this: I have some chained select boxes, with one select box per view. Each choice should be saved so that a query is built up. At the end, the query should be run. But how do you share state in django? I can pass from view to template, but not template to view and not view to view. Or I'm truly not sure how to do this. Please help!
2010/04/03
[ "https://Stackoverflow.com/questions/2570131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/283857/" ]
There's a couple ways you could go about this, the first has already been mentioned by spudd86 (except you need to use `GL_PIXEL_PACK_BUFFER`, that's the one that's written to by `glReadPixels`). The other is to use a framebuffer object and then read from its texture in your vertex shader, mapping from a vertex id (that you would have to manage) to a texture location. If this is a one-time operation though I'd go with copying it over to a PBO and then binding into `GL_ARRAY_BUFFER` and then just using it as a VBO.
The specification for [GL\_pixel\_buffer\_object](http://www.opengl.org/registry/specs/ARB/pixel_buffer_object.txt) gives an example demonstrating how to render to a vertex array under "Usage Examples". The following extensions are helpful for solving this problem: [GL\_texture\_float](http://www.opengl.org/registry/specs/ARB/texture_float.txt) - floating point internal formats to use for the color buffer attachment [GL\_color\_buffer\_float](http://www.opengl.org/registry/specs/ARB/color_buffer_float.txt) - disable automatic clamping for fragment colors and glReadPixels [GL\_pixel\_buffer\_object](http://www.opengl.org/registry/specs/ARB/pixel_buffer_object.txt) - operations for transferring pixel data to buffer objects
3,770,927
When I run the conversion in the browser it simply shows the white blank space. Only after the conversion process page will load. Please suggest how to implement a progress bar which shows the progress to the user when the video conversion takes place. I have this in my php script ``` exec("ffmpeg -i filename.flv -sameq -ab 128 -s 640x480 filename.mp4"); ``` so how should I change this script to get the progress details even to a file or directly as ouput in the page. Please can anyone give me a complete script/code to explain it in detail. Because I think I cant get the complete answers and so I am confused on what to do with this
2010/09/22
[ "https://Stackoverflow.com/questions/3770927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434111/" ]
If you're using PHP-FFMpeg, they've added an on function that you can listen for progress and execute a call back with. You set it up on your video format container like so: ``` $format = new Format\Video\X264(); $format->on('progress', function ($video, $format, $percentage) { echo "$percentage % transcoded"; }); ``` More info found in the docs <https://github.com/PHP-FFMpeg/PHP-FFMpeg>
I don't believe this is possible. The problem is that you need your `PHP` script to be aware of the current `ffmpeg` processing status. If you do an `ffmpeg` conversion via the command line, it displays the progress to the user, but you don't have access to that output stream when you spawn `ffmpeg` using commands in PHP like `exec`. Rather than try to show the user a true "progress indicator", I suggest that you just lightbox a waiting indicator on the page instead. You can find many images to suit this purpose or generate one via tools like <http://ajaxload.info/> .
1,705,530
We have to show that $$ n^4 -n^2 $$ is divisible by 3 and 4 by mathematical induction Proving the first case is easy however I do not know how what to do in the inductive step. Thank you.
2016/03/20
[ "https://math.stackexchange.com/questions/1705530", "https://math.stackexchange.com", "https://math.stackexchange.com/users/315166/" ]
Since $a\_n=n^4-n^2=n^2(n-1)(n+1)$, we can also write $$ a\_{n+1}=(n+1)^4-(n+1)^2=(n+1)^2n(n+2) $$ Suppose $a\_n=n^4-n^2$ is divisible by $3$; then $3$ divides one among $n$, $n-1$ and $n+1$. Since $n$ and $n+1$ appear in the decomposition of $a\_{n+1}$. The only remaining case is when $3$ divides $n-1$; but in this case we can use $n+2=(n-1)+3$ and we are done. Suppose $4$ divides $a\_n$. Then either $2\mid n$ or $2\mid(n+1)$ (and also $n-1$). In the case $2\mid(n+1)$, we have $4\mid(n+1)^2$. In the case $2\mid n$, we have $2\mid(n+2)$, so $4\mid n(n+2)$. --- Using Fermat's little theorem is of course easier; since $n^3\equiv n\pmod{3}$, $$ n^4-n^2\equiv n\cdot n^3-n^2\equiv n^2-n^2\equiv0\pmod{3} $$ Since $n^2\equiv n\pmod{2}$, we have \begin{align} n^2-n&\equiv n-n\equiv0\pmod{2}\\[4px] n^2+n&\equiv n+n\equiv2n\equiv0\pmod{2} \end{align} Is this a proof by induction? Well, yes! One uses induction for proving Fermat's little theorem. `;-)`
Let's prove that if $n^4-n^2$ is a multiple of both $3$ and $4$, then so is $(n+1)^4-(n+1)^2$. Consider $ ((n+1)^4-(n+1)^2)-(n^4-n^2)=4 n^3+6 n^2+2 n $. Ignoring $6n^2$, we have $4 n^3+2 n=3n^3+3n+n^3-n=3n^3+3n+6\binom{n+1}{3}$, which is always a multiple of $3$. Ignoring $4n^3$, we have $6 n^2+2 n=4n^2+2n(n+1)=4n^2+4\binom{n+1}{2}$, which is always a multiple of $4$. We're done. This problem is definitely one which is much easier *not* by induction but instead simply by arguing that $n^{4} - n^{2} = n^{2} (n + 1) (n - 1)$, as @eltonjohn suggested.
1,947,031
The year 2009 is coming to an end, and with the economy and all, we'll save our money and instead of buying expensive fireworks, we'll celebrate in ASCII art this year. The challenge ------------- Given a set of fireworks and a time, take a picture of the firework at that very time and draw it to the console. The best solution entered before midnight on New Year's Eve (UTC) will receive a bounty of 500 rep. This is code golf, so the number of characters counts heavily; however so do community votes, and I reserve the ultimate decision as to what is best/coolest/most creative/etc. Input Data ---------- Note that our coordinate system is left-to-right, bottom-to-top, so all fireworks are launched at a `y`-coordinate of 0 (zero). The input data consists of fireworks of the form ``` (x, speed_x, speed_y, launch_time, detonation_time) ``` where * `x` is the position (column) where the firework is launched, * `speed_x` and `speed_y` are the horizontal and vertical velocity of the firework at launch time, * `launch_time` is the point in time that this firework is launched, * `detonation_time` is the point in time that this firework will detonate. The firework data may be hardcoded in your program as a list of 5-tuples (or the equivalent in your language), not counting towards your character count. It must, however, be easy to change this data. You may make the following assumptions: * there is a reasonable amount of fireworks (say, fewer then a hundred) * for each firework, all five numbers are integers within a reasonable range (say, 16 bits would suffice for each), * `-20 <= x <= 820` * `-20 <= speed_x <= 20` * `0 < speed_y <= 20` * `launch_time >= 0` * `launch_time < detonation_time < launch_time + 50` The single additional piece of input data is the point of time which is supposed to be rendered. This is a non-negative integer that is given to you via standard input or command line argument (whichever you choose). The idea is that (assuming your program is a python script called `firework.py`) this bash script gives you a nice firework animation: ``` #!/bin/bash I=0 while (( 1 )) ; do python firework.py $I I=$(( $I + 1 )) done ``` (feel free to put the equivalent .BAT file here). Life of a firework ------------------ The life of a firework is as follows: * Before the launch time, it can be ignored. * At launch time, the rocket has the position `(x, 0)` and the speed vector `(speed_x, speed_y)`. * For each time step, the speed vector is added to the position. With a little stretch applied to Newton's laws, we assume that the speed stays constant. * At detonation time, the rocket explodes into nine sparks. All nine sparks have the same position at this point in time (which is the position that the rocket would have, hadn't it exploded), but their speeds differ. Each speed is based on the rocket's speed, with -20, 0, or 20 added to `speed_x` and -10, 0, or 10 added to `speed_y`. That's nine possible combinations. * After detonation time, gravity starts to pull: With each time step, the gravitational constant, which happens to be 2 (two), is subtracted from every spark's `speed_y`. The horizontal `speed_x` stays constant. * For each time step after the detonation time, you **first** add the speed vector to the position, **then** subtract 2 from `speed_y`. * When a spark's `y` position drops below zero, you may forget about it. Output ------ What we want is a picture of the firework the way it looks at the given point in time. We only look at the frame `0 <= x <= 789` and `0 <= y <= 239`, mapping it to a 79x24 character output. So if a rocket or spark has the position (247, 130), we draw a character in column 24 (zero-based, so it's the 25th column), row 13 (zero-based and counting from the bottom, so it's line 23 - 13 = 10, the 11th line of the output). Which character gets drawn depends on the current speed of the rocket / spark: * If the movement is horizontal\*, i.e. `speed_y == 0 or abs(speed_x) / abs(speed_y) > 2`, the character is "`-`". * If the movement is vertical\*, i.e. `speed_x == 0 or abs(speed_y) / abs(speed_x) > 2`, the character is "`|`". * Otherwise the movement is diagonal, and the character is "`\`" or "`/`" (you'll guess the right one). * If the same position gets drawn to more than once (even if it's the same character), we put "`X`" instead. So assuming you have a spark at `(536, 119)` and one at `(531, 115)`, you draw an "`X`", regardless of their speeds. \* update: these are integer divisions, so the slope has to be at least 3, or at most 1/3, respectively The output (written to standard output) is 24 lines, each terminated by a newline character. Trailing spaces are ignored, so you may, but don't need to, pad to a width of 79. The lines may not be longer than 79 characters (excluding the newline). All interior spacing must be space characters (ASCII 32). Sample Data ----------- Fireworks: ``` fireworks = [(628, 6, 6, 3, 33), (586, 7, 11, 11, 23), (185, -1, 17, 24, 28), (189, 14, 10, 50, 83), (180, 7, 5, 70, 77), (538, -7, 7, 70, 105), (510, -11, 19, 71, 106), (220, -9, 7, 77, 100), (136, 4, 14, 80, 91), (337, -13, 20, 106, 128)] ``` Output at time 33: ``` \ | / / \ - | / - | - / \ ``` Output at time 77: ``` \ \ X \ ``` Output at time 93: ``` \ | / \ / / - - - \ \ / \ \ ``` **Update:** I have uploaded the expected output at the times 0 thru 99 to [firework.ü-wie-geek.de/NUMBER.html](http://firework.%C3%BC-wie-geek.de/0.html), where NUMBER is the time. It includes debug information; click on a particle to see its current position, speed, etc. And yes, it's an umlaut domain. If your browser can't handle that (as obviously neither can Stack Overflow), try [firework.xn---wie-geek-p9a.de](http://firework.xn---wie-geek-p9a.de/0.html). **Another update:** As hinted at in the comments below, a longer firework is now available on [YouTube](http://www.youtube.com/watch?v=HRYg6ixAnPg). It was created with a modified version of [MizardX' entry](https://stackoverflow.com/questions/1947031/code-golf-new-years-fireworks/1953608#1953608), with a total fireworks count of 170 (yes, that's more than the spec asked for, but the program handled it gracefully). Except for the color, the music, and the end screen, the animation can be recreated by any entry to this code golf. So, if you're geeky enough to enjoy an ASCII art firework (you know you are): Have fun, and a happy new year to all!
2009/12/22
[ "https://Stackoverflow.com/questions/1947031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115866/" ]
Heres my solution in Python: ``` c = [(628, 6, 6, 3, 33), (586, 7, 11, 11, 23), (185, -1, 17, 24, 28), (189, 14, 10, 50, 83), (180, 7, 5, 70, 77), (538, -7, 7, 70, 105), (510, -11, 19, 71, 106), (220, -9, 7, 77, 100), (136, 4, 14, 80, 91), (337, -13, 20, 106, 128)] t=input() z=' ' s=([z]*79+['\n'])*23+[z]*79 def p(x,y,i,j): if 0<=x<790 and 0<=y<240:p=x/10+(23-y/10)*80;I=abs(i);J=abs(j);s[p]='X-|\\/'[[s[p]!=z,I>=3*J,J>=3*I,i*j<0,1].index(1)] for x,i,j,l,d in c: T=t-l;x+=i*T if t>=d:e=t-d;[p(x+X*e,j*T+e*(Y-e+1),i+X,j+Y-2*e)for X in -20,0,20 for Y in -10,0,10] elif t>=l:p(x,j*T,i,j) print ''.join(s) ``` Takes the time from the stdin and it has the nice number of 342 characters. I'm still trying to imagine how the OP got 320 :P Edit: This is the best I could get, 322 chars acording to wc ``` t=input() s=([' ']*79+['\n'])*24 def p(x,y,i,j): if 790>x>-1<y<240:p=x/10+(23-y/10)*80;I=abs(i);J=abs(j);s[p]='X-|\\/'[[s[p]>' ',I>=3*J,J>=3*I,i*j<0,1].index(1)] for x,i,j,l,d in c: T=t-l;x+=i*T;e=t-d if t>=d:[p(x+X*e,j*T+e*(Y-e+1),i+X,j+Y-2*e)for X in-20,0,20for Y in-10,0,10] elif t>=l:p(x,j*T,i,j) print''.join(s), ```
**C:** With all unnecessary whitespace removed (632 bytes excluding the fireworks declaration): ``` #define N 10 int F[][5]={628,6,6,3,33,586,7,11,11,23,185,-1,17,24,28,189,14,10,50,83,180,7,5,70,77,538,-7,7,70,105,510,-11,19,71,106,220,-9,7,77,100,136,4,14,80,91,337,-13,20,106,128}; #define G F[i] #define R P[p] g(x,y){if(y==0||abs(x)/abs(y)>2)return 45;if(x==0||abs(y)/abs(x)>2)return'|';if(x*y<0)return 92;return 47;}main(int A,char**B){int a,b,c,C[24][79]={},d,i,j,p=0,P[N*9][3],Q,t=atoi(B[1]),x,y;for(i=0;i<N;i++){if(t>=G[3]){a=t-G[3];x=G[0]+G[1]*a;y=G[2]*a;if(t<G[4]){R[0]=x;R[1]=y;R[2]=g(G[1],G[2]);p++;}else{b=t-G[4];y-=b*(b-1);for(c=-20;c<=20;c+=20){for(d=-10;d<=10;d+=10){R[0]=x+c*b;R[1]=y+d*b;R[2]=g(G[1]+c,G[2]+d-2*b);p++;}}}}}Q=p;for(p=0;p<Q;p++){x=R[0]/10;y=R[1]/10;if(R[0]>=0&&x<79&&R[1]>=0&&y<24)C[y][x]=C[y][x]?88:R[2];}for(i=23;i>=0;i--){for(j=0;j<79;j++)putchar(C[i][j]?C[i][j]:32);putchar(10);}} ``` And here's the exact same code with whitespace added for readability: ``` #define N 10 int F[][5] = { 628, 6, 6, 3, 33, 586, 7, 11, 11, 23, 185, -1, 17, 24, 28, 189, 14, 10, 50, 83, 180, 7, 5, 70, 77, 538, -7, 7, 70, 105, 510, -11, 19, 71, 106, 220, -9, 7, 77, 100, 136, 4, 14, 80, 91, 337, -13, 20, 106, 128 }; #define G F[i] #define R P[p] g(x, y) { if(y == 0 || abs(x)/abs(y) > 2) return 45; if(x == 0 || abs(y)/abs(x) > 2) return '|'; if(x*y < 0) return 92; return 47; } main(int A, char**B){ int a, b, c, C[24][79] = {}, d, i, j, p = 0, P[N*9][3], Q, t = atoi(B[1]), x, y; for(i = 0; i < N; i++) { if(t >= G[3]) { a = t - G[3]; x = G[0] + G[1]*a; y = G[2]*a; if(t < G[4]) { R[0] = x; R[1] = y; R[2] = g(G[1], G[2]); p++; } else { b = t - G[4]; y -= b*(b-1); for(c = -20; c <= 20; c += 20) { for(d =- 10; d <= 10; d += 10) { R[0] = x + c*b; R[1] = y + d*b; R[2] = g(G[1] + c, G[2] + d - 2*b); p++; } } } } } Q = p; for(p = 0; p < Q; p++) { x = R[0]/10; y = R[1]/10; if(R[0] >= 0 && x < 79 && R[1] >= 0 && y < 24) C[y][x] = C[y][x] ? 88 : R[2]; } for(i = 23; i >= 0; i--) { for(j = 0; j < 79; j++) putchar(C[i][j] ? C[i][j] : 32); putchar(10); } } ```
33,359,694
I have following html ``` <p contenteditable>The greatest p tag of all p tags all the time</p> ``` and this js ``` var p = document.querySelector('p'); p.addEventListner('keypress', function (e) { if (e.which === 13) { //this.focusout() ??; } }); ``` **[DEMO](https://jsfiddle.net/sameerachathuranga/ben86foo/1/)** But this thing doesn't work. How do i focusout the p tag with enter hit. No jquery Please. Thanks :-)
2015/10/27
[ "https://Stackoverflow.com/questions/33359694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2094106/" ]
I think the correct method for this is `.blur()` So the following should suffice: ``` var p = document.querySelector('p'); p.addEventListener('keypress', function (e) { // you spelt addEventListener wrongly if (e.which === 13) { e.preventDefault();// to prevent the default enter functionality this.blur(); } }); ```
You can use the `onblur` or `onfocusout` event: ``` <p onblur="myFunction()" contenteditable> The greatest p tag of all p tags all the time </p> ``` or ``` <p onfocusout="myFunction()" contenteditable> The greatest p tag of all p tags all the time </p> ```
60,918,029
I need help resolving a problem with my code. I want to get the score that's in the score id, and use it in an if condition wherein I will determine their grade rank. I shouldn't be typing a value in p tag Below is the code specific to the problem - All the ones that are needed should be below. Thank you for the help guysss i added some more code ``` <button id = "submit" name = "submit" value = "submit" > SUBMIT </button> <div id="myModal" class="modal"> <div class="modal-content"> <h3> Are you sure you want to submit? </h3> <button id = "yes" name = "yes" class = "yes" value = "submit" > YES </button> <button id = "no" name = "no" class = "no"> NO </button> </div> </div> <div id="myModalLast" class="modalLast"> <div class="modal-contentLast"> <a href = "personal.php"> <span class="close">&times;</span> </a> <div class = "pic"> <img src="Logo.png" width = "150" height = "150"> </div> <h3> Full name: Cathleen Joyce Imperial Almeda </h3> <h3> Total items:20 <p id = "scoree" name = "realscores"></p> </h3> <h1> <br><p id = "scorees" name = "realscores"></p> Rank:<p id = "rank"></p></h1> </div> </div> </div> <script> var scoress = document.getElementById('scorees'); if (scoress == 20){ document.getElementById("rank").innerHTML = "A+"; }else if(scoress ==19){ document.getElementById("rank").innerHTML = "A"; }else if(scoress ==18){ document.getElementById("rank").innerHTML =" A-"; }else if(scoress ==17){ document.getElementById("rank").innerHTML = "B+"; }else if(scoress ==16){ document.getElementById("rank").innerHTML = "B"; }else if(scoress ==15){ document.getElementById("rank").innerHTML = "B-"; }else if(scoress ==14){ document.getElementById("rank").innerHTML = "C+"; }else if(scoress ==13){ document.getElementById("rank").innerHTML = "C"; }else if(scoress ==12){ document.getElementById("rank").innerHTML = "C-"; }else if(scoress ==11){ document.getElementById("rank").innerHTML = "D+"; } else if(scoress ==10){ document.getElementById("rank").innerHTML = "D"; }else{ document.getElementById("rank").innerHTML = "F"; } <script>document.getElementById("yes").addEventListener("click", function() { let numberOfCorrectAnswers = document.querySelectorAll("input[type=radio].correct:checked").length; document.getElementById("scoree").innerHTML = "Correct Answers: " + numberOfCorrectAnswers; }); </script> <script>document.getElementById("yes").addEventListener("click", function() { let numberOfCorrectAnswers = document.querySelectorAll("input[type=radio].correct:checked").length; document.getElementById("scorees").innerHTML = "Your Score: " + numberOfCorrectAnswers; }); </script> <script>document.getElementById("yes").addEventListener("click", function() { let numberOfCorrectAnswers = document.querySelectorAll("input[type=radio].correct:checked").length; document.getElementById("scoree").innerHTML = "Correct Answers: " + numberOfCorrectAnswers; }); </script> <script>document.getElementById("yes").addEventListener("click", function() { let numberOfCorrectAnswers = document.querySelectorAll("input[type=radio].correct:checked").length; document.getElementById("scorees").innerHTML = "Your Score: " + numberOfCorrectAnswers; }); </script> ```
2020/03/29
[ "https://Stackoverflow.com/questions/60918029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13082803/" ]
SafeArgs don't support cross-module navigation <https://developer.android.com/guide/navigation/navigation-multi-module> --- **Update:** You need to use the [deep link](https://developer.android.com/guide/navigation/navigation-navigate#uri) instead: <https://developer.android.com/guide/navigation/navigation-multi-module#across>
you must add ``` id "kotlin-kapt" id "androidx.navigation.safeargs.kotlin" ``` into your `plugins { ... }` body of your modules or, with old approache ``` apply plugin "kotlin-kapt" apply plugin "androidx.navigation.safeargs.kotlin" ``` Don't forget to make `Rebuild Project` after `Gradle Sync`