qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
27,123,304
I have come across some unit tests written by another developer that regularly use an overloaded version of `Assert.AreEqual` like so: ``` Assert.AreEqual(stringparamX, stringParamY, true, CultureInfo.InvariantCulture); ``` `stringParamX` is set within the unit test and `stringparamY` will be the result from the system under test. It is possible hat this code may be ported to other countries and these tests may be executed. However, on having a look at the [MSDN docs for Culture](http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.invariantculture.aspx), I can't help thinking that passing in `CultureInfo.InvariantCulture` is adding some unnecessary complexity here. I'm not sure what kind of impact removing it would have on the tests if executed in other cultures. In the context of unit testing in my situation, why should I (or not) write asserts like this?
2014/11/25
[ "https://Stackoverflow.com/questions/27123304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402421/" ]
There is no reason to use that overload if you are specifying the culture as `InvariantCulture`, because that is the default. From [the documentation here](http://msdn.microsoft.com/en-us/library/ms243448.aspx): > > The invariant culture is used for the comparison. > > > Note that there ARE some cases where it would make a difference if you weren't using the `InvariantCulture`, the most notorious being ["The Turkish I problem"](http://haacked.com/archive/2012/07/05/turkish-i-problem-and-why-you-should-care.aspx/). The following code illustrates the issue: ``` Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR"); Assert.AreEqual("i", "I", true, CultureInfo.CurrentCulture); // This throws. Assert.AreEqual("i", "I", true, CultureInfo.InvariantCulture); // This doesn't throw. Assert.AreEqual("i", "I", true); // This doesn't throw. ``` However, note that you will not be affected by that because you are using the invariant culture.
The [MSDN documentation](http://msdn.microsoft.com/en-us/library/ms243448.aspx) for Assert.AreEqual that *doesn't* take the CultureInfo states in the "Remarks" section: > > The invariant culture is used for the comparison > > > If true, then specifying it explicitly is technically unnecessary. It's then a moot point about whether being explicit is better. That being said, it depends on what's being tested whether culture should be considered for a case-insensitive string comparison.
10,353,275
I'm building out a decommissioning application that will allow an individual to provide an computer name and the utility will go out and purge the computer record from various locations. I'm running into a problem when attempting to delete a computer account from Active Directory. I'm impersonating a service account that only has rights to "Delete All Child Objects" within a particular OU structure. The code below works if I run it with my domain admin account; however fails with an "Access Denied" when I run it with the impersonated service account. I have verified that the permissions are correct within AD as I can launch Active Directory Users and Computers using a "runas" and providing the service account credentials and I can delete computer objects perfectly fine. Wondering if anyone has run into this before or has a different way to code this while still utilizing my current OU permissions. My gut tells me the "DeleteTree" method is doing more then just deleting the object. Any assistance would be appreciated. ``` Sub Main() Dim strAsset As String = "computer9002" Dim strADUsername As String = "[email protected]" Dim strADPassword As String = "password" Dim strADDomainController As String = "domaincontroller.domain.com" Dim objDirectoryEntry As New System.DirectoryServices.DirectoryEntry Dim objDirectorySearcher As New System.DirectoryServices.DirectorySearcher(objDirectoryEntry) Dim Result As System.DirectoryServices.SearchResult Dim strLDAPPath As String = "" Try objDirectoryEntry.Path = "LDAP://" & strADDomainController objDirectoryEntry.Username = strADUsername objDirectoryEntry.Password = strADPassword objDirectorySearcher.SearchScope = DirectoryServices.SearchScope.Subtree objDirectorySearcher.Filter = "(&(ObjectClass=Computer)(CN=" & strAsset & "))" Dim intRecords As Integer = 0 For Each Result In objDirectorySearcher.FindAll Console.WriteLine(Result.Path) Diagnostics.Debug.WriteLine("DN: " & Result.Path) Dim objComputer As System.DirectoryServices.DirectoryEntry = Result.GetDirectoryEntry() objComputer.DeleteTree() objComputer.CommitChanges() intRecords += 1 Next If intRecords = 0 Then Console.WriteLine("No Hosts Found") End If Catch e As System.Exception Console.WriteLine("RESULT: " & e.Message) End Try End Sub ```
2012/04/27
[ "https://Stackoverflow.com/questions/10353275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1361341/" ]
If you're on .NET 3.5 and up, you should check out the `System.DirectoryServices.AccountManagement` (S.DS.AM) namespace. Read all about it here: * [Managing Directory Security Principals in the .NET Framework 3.5](http://msdn.microsoft.com/en-us/magazine/cc135979.aspx) * [MSDN docs on System.DirectoryServices.AccountManagement](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx) Basically, you can define a domain context and easily find users and/or groups in AD: ``` ' set up domain context Dim ctx As New PrincipalContext(ContextType.Domain, "DOMAIN", strADUsername, strADPassword) ' find a computer Dim computerToDelete As ComputerPrincipal = ComputerPrincipal.FindByIdentity(ctx, strAsset) If computerToDelete IsNot Nothing Then ' delete the computer, if found computerToDelete.Delete() End If ``` The new S.DS.AM makes it really easy to play around with users and groups in AD!
Delete Tree is different from delete. You're going to need the Delete Subtree permission on the child computer objects for this to work.
21,841,551
I have to show all products that contain the word "Transducer" in them. I CANNOT use LIKE. I have tried using contain and I get a invalid relational operator error. I've tried everything I can think of and nothing is working. I'm using SQL Developer 4. Code: ``` SELECT product_name, name FROM a_product p JOIN a_item i ON p.product_id=i.product_id JOIN a_sales_order so ON i.order_id=so.order_id JOIN a_customer c ON so.customer_id=c.customer_id ``` Output: ``` PRODUCT_NAME NAME ------------------------------ --------------------------------------------- Aft Transducer Just Electronics 75 Gauge Wire Line Timelines Aft Transducer Vollyrite Nts Transducer Every Mountain Snyder Lock Switch Shape Up Nts Transducer Shape Up Sft Transducer 55 Vollyrite 75 Gauge Wire Line Shape Up ``` I also as I mentioned tried to use contains, but it gave me the error. This is what I used: ``` WHERE contains(product_name, 'Transducer') ``` Which I added after the join statements. The desired output would look like this: ``` PRODUCT_NAME NAME ------------------------------ --------------------------------------------- Aft Transducer Just Electronics Aft Transducer Vollyrite Nts Transducer Every Mountain Nts Transducer Shape Up Sft Transducer 55 Vollyrite ```
2014/02/17
[ "https://Stackoverflow.com/questions/21841551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2250600/" ]
If you can't use LIKE because it's a problem for school, an alternative is REGEXP\_LIKE: ``` SELECT product_name, name FROM a_product p JOIN a_item i ON p.product_id = i.product_id JOIN a_sales_order so ON i.order_id = so.order_id JOIN a_customer c ON so.customer_id = c.customer_id where regexp_like(product_name, 'Transducer') ```
<https://dev.mysql.com/doc/refman/5.1/en/regexp.html> ``` "SELECT * FROM `foo` WHERE `name` REGEXP *Transducer* ``` Or something like that?
74,271,442
Is it easy for people to find "public" google sheets/docs? Context: Storing some semi-sensitive data (individual user info, of non-sensitive nature) for an app beta-test in google sheets. Planning to migrate to some DB in the future, but for now, just using JavaScript to pull the data directly from the google sheets (since there are visualizations being dynamically updated by the sheets).
2022/11/01
[ "https://Stackoverflow.com/questions/74271442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12634149/" ]
Yes, it's easy to get information. Search engines may index and cache the information. Then, there are bots, crawlers and scrapers. Do NOT put (semi)sensitive information in public. Implement [google-oauth](/questions/tagged/google-oauth "show questions tagged 'google-oauth'") properly with [google-sheets-api](/questions/tagged/google-sheets-api "show questions tagged 'google-sheets-api'") to get information. You can also use [service-accounts](/questions/tagged/service-accounts "show questions tagged 'service-accounts'")
Don’t make it public unless you want the public to see it. Use oauth to access.
74,271,442
Is it easy for people to find "public" google sheets/docs? Context: Storing some semi-sensitive data (individual user info, of non-sensitive nature) for an app beta-test in google sheets. Planning to migrate to some DB in the future, but for now, just using JavaScript to pull the data directly from the google sheets (since there are visualizations being dynamically updated by the sheets).
2022/11/01
[ "https://Stackoverflow.com/questions/74271442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12634149/" ]
Yes, it can be easily accessed. ------------------------------- According to the official Google article [Share files from Google Drive](https://support.google.com/docs/answer/2494822): when you set your file's `General Access` setting to `public`: > > Anyone can `search on Google` and get access to your file, `without signing in` to their Google account. > > > What you can do: ---------------- In the case of your `app beta-test in google sheets` data, you may want to reconsider to change your file's `General Access` setting to one of the following (in descending order of security): * `Restricted` - Only people that you manually give access to can view or edit your files. When you click the `share` button, a prompt will show and you may manually add the users who can view or edit your files: [![enter image description here](https://i.stack.imgur.com/sE2hr.png)](https://i.stack.imgur.com/sE2hr.png) Afterwards, you may select a role for those users and then they can be notified afterwards through email. [![enter image description here](https://i.stack.imgur.com/zDB4k.png)](https://i.stack.imgur.com/zDB4k.png) On the other hand, you can share the link to others. A prompt will show like the one below if you send the url through Google Chat: [![PopUp1](https://i.stack.imgur.com/Dyml2.png)](https://i.stack.imgur.com/Dyml2.png) You may opt to select `Don't give access` which will result in the following view on the other user's end: [![NeedAccessScreen](https://i.stack.imgur.com/w3Jk6.png)](https://i.stack.imgur.com/w3Jk6.png) This would mean that if unauthorized users get hold of the file URL, they will still need to send an access request. If other users submit the request, an email notification will be sent to your mail inbox. Other users who also own the file will also be notified by mail. * `Your Organization` - If you use a Google Account through work or school, anyone signed in to an account in your organization can open the file. If you are an administrator in a work or school workspace, you may set how members can [share content within the organization](https://support.google.com/a/users/answer/167101). The administrator can prevent the sharing of content with group members outside your organization. If external sharing is prohibited, only group members who are in your organization can access the group's shared content. * `Anyone with the link` - Anyone who has the link can use your file, without signing in to their Google Account. This option is `least recommended` because if the URL is leaked to unauthorized users, they can easily access the file. References: ----------- * [Share files from Google Drive](https://support.google.com/docs/answer/2494822) * [Share content with a group](https://support.google.com/a/users/answer/167101)
Don’t make it public unless you want the public to see it. Use oauth to access.
74,271,442
Is it easy for people to find "public" google sheets/docs? Context: Storing some semi-sensitive data (individual user info, of non-sensitive nature) for an app beta-test in google sheets. Planning to migrate to some DB in the future, but for now, just using JavaScript to pull the data directly from the google sheets (since there are visualizations being dynamically updated by the sheets).
2022/11/01
[ "https://Stackoverflow.com/questions/74271442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12634149/" ]
Yes, it's easy to get information. Search engines may index and cache the information. Then, there are bots, crawlers and scrapers. Do NOT put (semi)sensitive information in public. Implement [google-oauth](/questions/tagged/google-oauth "show questions tagged 'google-oauth'") properly with [google-sheets-api](/questions/tagged/google-sheets-api "show questions tagged 'google-sheets-api'") to get information. You can also use [service-accounts](/questions/tagged/service-accounts "show questions tagged 'service-accounts'")
Yes, it can be easily accessed. ------------------------------- According to the official Google article [Share files from Google Drive](https://support.google.com/docs/answer/2494822): when you set your file's `General Access` setting to `public`: > > Anyone can `search on Google` and get access to your file, `without signing in` to their Google account. > > > What you can do: ---------------- In the case of your `app beta-test in google sheets` data, you may want to reconsider to change your file's `General Access` setting to one of the following (in descending order of security): * `Restricted` - Only people that you manually give access to can view or edit your files. When you click the `share` button, a prompt will show and you may manually add the users who can view or edit your files: [![enter image description here](https://i.stack.imgur.com/sE2hr.png)](https://i.stack.imgur.com/sE2hr.png) Afterwards, you may select a role for those users and then they can be notified afterwards through email. [![enter image description here](https://i.stack.imgur.com/zDB4k.png)](https://i.stack.imgur.com/zDB4k.png) On the other hand, you can share the link to others. A prompt will show like the one below if you send the url through Google Chat: [![PopUp1](https://i.stack.imgur.com/Dyml2.png)](https://i.stack.imgur.com/Dyml2.png) You may opt to select `Don't give access` which will result in the following view on the other user's end: [![NeedAccessScreen](https://i.stack.imgur.com/w3Jk6.png)](https://i.stack.imgur.com/w3Jk6.png) This would mean that if unauthorized users get hold of the file URL, they will still need to send an access request. If other users submit the request, an email notification will be sent to your mail inbox. Other users who also own the file will also be notified by mail. * `Your Organization` - If you use a Google Account through work or school, anyone signed in to an account in your organization can open the file. If you are an administrator in a work or school workspace, you may set how members can [share content within the organization](https://support.google.com/a/users/answer/167101). The administrator can prevent the sharing of content with group members outside your organization. If external sharing is prohibited, only group members who are in your organization can access the group's shared content. * `Anyone with the link` - Anyone who has the link can use your file, without signing in to their Google Account. This option is `least recommended` because if the URL is leaked to unauthorized users, they can easily access the file. References: ----------- * [Share files from Google Drive](https://support.google.com/docs/answer/2494822) * [Share content with a group](https://support.google.com/a/users/answer/167101)
22,407,326
I have a subclass of NSManagedObject on which there's a "currency" attribute. This attribute is a 3 letters string. When I change it from "USD" to "CAD", and then call `changedValues` on the object, changedValues returns an empty dictionary. Is that the normal behaviour? I save the managedObjectContext first, then change the attribute, then call changedValues. This attribute is: not transient, optional, not indexed, no default value. EDIT: Thx for the help guys I found a bug in my code. Now it works just fine.
2014/03/14
[ "https://Stackoverflow.com/questions/22407326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3250560/" ]
I found a bug in my code. Now it works just fine. ;) I was using a delegate method to update the object from another viewController. When coming back from that viewController I saved the managedObjectContext in `viewWillAppear` which basically erased the changedValues.
Do it before you save the context. [NSManagedObject Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObject_Class/Reference/NSManagedObject.html#//apple_ref/occ/instm/NSManagedObject/changedValues) > > changedValues > > > Returns a dictionary containing the keys and (new) values of > persistent properties that have been changed since last fetching or > ***saving*** the receiver. > > >
32,896,020
this is my first question on here so ill try and be as detailed as possible! I am currently creating a HTML form with a select option with options 1 - 4. My aim is to use a Javascript function to create a certain amount of div's depending on which value the user has selected from the form. For example, if the user has selected option 2, i want to auto generate 2 div containers. Then, if the user chooses to select another option after... the correct amount of divs will then be created. My select HTML currently looks like this; ``` <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> ``` I have created a script which will create a div on button click but this isn't my aim; ``` var number = 2; document.getElementById('add').addEventListener('click', function( ) { var newDiv = document.createElement('div'); newDiv.id = 'container'; newDiv.innerHTML = "<label>Episode " + number + " name</label> <input type='text' name='episode'" + number +" /> <label>Episode " + number + " embed</label> <input type='text' /> "; document.getElementById('contain_form').appendChild(newDiv); number++; }); ``` I would appreciate it if somebody was to help me with the JS i will need to make this functionality and i hope i've explained myself clearly enough in this post! Feel free to comment and ask for me details if required. Thanks in advance, Sam
2015/10/01
[ "https://Stackoverflow.com/questions/32896020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5397172/" ]
You need to bind the `change` event on your `select` element. Something like this: ```js var divs = []; document.getElementById('select_seasons').addEventListener('change', function(e) { var n = +this.value; for (var i = 0; i < divs.length; i++) { divs[i].remove(); } divs = []; for (var i = 0; i < n; i++) { var d = document.createElement("div"); d.className = "new"; document.body.appendChild(d); divs.push(d); } }); ``` ```css .new { background-color: red; width: 100px; height: 20px; margin: 1px; } ``` ```html <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> ```
You could use the selected value of the `select` element: ``` var number = select.options[select.selectedIndex].value; ``` For example: ```js var select = document.getElementById("select_seasons"); var button = document.getElementById("add"); var container = document.getElementById("container"); button.addEventListener("click", function () { // uncomment the following line if you want the remove the previously generated divs: //container.innerHTML = ""; var number = select.options[select.selectedIndex].value; for (var i = 1; i <= number; i++) { var div = document.createElement("div"); div.innerHTML = "div #" + i; container.appendChild(div); } }); ``` ```html <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <button id="add">Add</button> <div id="container"></div> ```
32,896,020
this is my first question on here so ill try and be as detailed as possible! I am currently creating a HTML form with a select option with options 1 - 4. My aim is to use a Javascript function to create a certain amount of div's depending on which value the user has selected from the form. For example, if the user has selected option 2, i want to auto generate 2 div containers. Then, if the user chooses to select another option after... the correct amount of divs will then be created. My select HTML currently looks like this; ``` <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> ``` I have created a script which will create a div on button click but this isn't my aim; ``` var number = 2; document.getElementById('add').addEventListener('click', function( ) { var newDiv = document.createElement('div'); newDiv.id = 'container'; newDiv.innerHTML = "<label>Episode " + number + " name</label> <input type='text' name='episode'" + number +" /> <label>Episode " + number + " embed</label> <input type='text' /> "; document.getElementById('contain_form').appendChild(newDiv); number++; }); ``` I would appreciate it if somebody was to help me with the JS i will need to make this functionality and i hope i've explained myself clearly enough in this post! Feel free to comment and ask for me details if required. Thanks in advance, Sam
2015/10/01
[ "https://Stackoverflow.com/questions/32896020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5397172/" ]
You need to bind the `change` event on your `select` element. Something like this: ```js var divs = []; document.getElementById('select_seasons').addEventListener('change', function(e) { var n = +this.value; for (var i = 0; i < divs.length; i++) { divs[i].remove(); } divs = []; for (var i = 0; i < n; i++) { var d = document.createElement("div"); d.className = "new"; document.body.appendChild(d); divs.push(d); } }); ``` ```css .new { background-color: red; width: 100px; height: 20px; margin: 1px; } ``` ```html <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> ```
If I understood the question correctly, the seasons form should update and auto-fill with the `select`'s number. Use the `change` event and refresh the form with the selected value. ```js var selectSeasons = document.getElementById("select_seasons"); selectSeasons.addEventListener('change', function() { populateForm(parseInt(this.value)); }); function populateForm(numberOfSeasons) { // first, remove all existing fields var containForm = document.getElementById("contain_form"); while (containForm.firstChild) { containForm.removeChild(containForm.firstChild); } for (var i = 1; i <= numberOfSeasons; i++) { addDiv(i); } } function addDiv(number) { var newDiv = document.createElement('div'); newDiv.id = 'container'; newDiv.innerHTML = "<label>Episode " + number + " name</label> <input type='text' name='episode'" + number + " /> <label>Episode " + number + " embed</label> <input type='text' /> "; document.getElementById('contain_form').appendChild(newDiv); number++; } ``` ```html Number of seasons: <select id="select_seasons"> <option value="0">Please make a selection</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <div id="contain_form"></div> ```
32,896,020
this is my first question on here so ill try and be as detailed as possible! I am currently creating a HTML form with a select option with options 1 - 4. My aim is to use a Javascript function to create a certain amount of div's depending on which value the user has selected from the form. For example, if the user has selected option 2, i want to auto generate 2 div containers. Then, if the user chooses to select another option after... the correct amount of divs will then be created. My select HTML currently looks like this; ``` <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> ``` I have created a script which will create a div on button click but this isn't my aim; ``` var number = 2; document.getElementById('add').addEventListener('click', function( ) { var newDiv = document.createElement('div'); newDiv.id = 'container'; newDiv.innerHTML = "<label>Episode " + number + " name</label> <input type='text' name='episode'" + number +" /> <label>Episode " + number + " embed</label> <input type='text' /> "; document.getElementById('contain_form').appendChild(newDiv); number++; }); ``` I would appreciate it if somebody was to help me with the JS i will need to make this functionality and i hope i've explained myself clearly enough in this post! Feel free to comment and ask for me details if required. Thanks in advance, Sam
2015/10/01
[ "https://Stackoverflow.com/questions/32896020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5397172/" ]
You need to bind the `change` event on your `select` element. Something like this: ```js var divs = []; document.getElementById('select_seasons').addEventListener('change', function(e) { var n = +this.value; for (var i = 0; i < divs.length; i++) { divs[i].remove(); } divs = []; for (var i = 0; i < n; i++) { var d = document.createElement("div"); d.className = "new"; document.body.appendChild(d); divs.push(d); } }); ``` ```css .new { background-color: red; width: 100px; height: 20px; margin: 1px; } ``` ```html <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> ```
Solution for your problem: <http://jsfiddle.net/43ggkkg7/> ``` document.getElementById('select_seasons').addEventListener('change', function(){ var container = document.getElementById('container'); container.innerHTML = ''; //clear //Find selected option var n = 1; for(var i = 0; i < this.options.length; ++i){ if(this.options[i].selected){ n = ~~this.options[i].value; //Cast to int break; } } for(var i = 1; i <= n; ++i){ //Because we want to count from 1 not 0 var newDiv = document.createElement('div'); newDiv.id = 'element-' + i; newDiv.innerHTML = "<label>Episode " + i + " name</label> <input type='text' name='episode[" + i +"]' /> <label>Episode " + i + " embed</label> <input type='text' /> "; container.appendChild(newDiv); } }); //Emit event on page init document.getElementById('select_seasons').dispatchEvent(new Event('change')); ```
32,896,020
this is my first question on here so ill try and be as detailed as possible! I am currently creating a HTML form with a select option with options 1 - 4. My aim is to use a Javascript function to create a certain amount of div's depending on which value the user has selected from the form. For example, if the user has selected option 2, i want to auto generate 2 div containers. Then, if the user chooses to select another option after... the correct amount of divs will then be created. My select HTML currently looks like this; ``` <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> ``` I have created a script which will create a div on button click but this isn't my aim; ``` var number = 2; document.getElementById('add').addEventListener('click', function( ) { var newDiv = document.createElement('div'); newDiv.id = 'container'; newDiv.innerHTML = "<label>Episode " + number + " name</label> <input type='text' name='episode'" + number +" /> <label>Episode " + number + " embed</label> <input type='text' /> "; document.getElementById('contain_form').appendChild(newDiv); number++; }); ``` I would appreciate it if somebody was to help me with the JS i will need to make this functionality and i hope i've explained myself clearly enough in this post! Feel free to comment and ask for me details if required. Thanks in advance, Sam
2015/10/01
[ "https://Stackoverflow.com/questions/32896020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5397172/" ]
You need to bind the `change` event on your `select` element. Something like this: ```js var divs = []; document.getElementById('select_seasons').addEventListener('change', function(e) { var n = +this.value; for (var i = 0; i < divs.length; i++) { divs[i].remove(); } divs = []; for (var i = 0; i < n; i++) { var d = document.createElement("div"); d.className = "new"; document.body.appendChild(d); divs.push(d); } }); ``` ```css .new { background-color: red; width: 100px; height: 20px; margin: 1px; } ``` ```html <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> ```
I will help you to read [this](https://stackoverflow.com/questions/14094697/javascript-how-to-create-new-div-dynamically-change-it-move-it-modify-it-in) now, I don't need another loop to remove the old divs in the container, you can use `innedHTML` and set it to empty. ``` <select id="select_seasons"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> ``` ``` document.getElementById('select_seasons').addEventListener('change', function() { var self = this, exisiting = document.getElementById('contain_form'); //remove existing divs exisiting.innerHTML = ''; for(i=1; i<= self.value; i++) { var newDiv = document.createElement('div'); newDiv.id = 'container'; newDiv.innerHTML = "<label>Episode " + i + " name</label> <input type='text' name='episode'" + i +" /> <label>Episode " + number + " embed</label> <input type='text' /> "; exisiting.appendChild(newDiv); } }); ``` Check this [fiddle](http://jsfiddle.net/a1vuabx5/)
1,590,901
Prove the inequality: $$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right)\ge 3+2\sqrt{2}; \text{ for } a\in\left]0,\frac{\pi}{2}\right[$$
2015/12/27
[ "https://math.stackexchange.com/questions/1590901", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296768/" ]
By the AM-GM inequality, $$\dfrac{1}{\cos a}+\dfrac{1}{\sin a} \geq 2 \sqrt{\dfrac{1}{\sin a\cos a}}$$ Since $\sin a \cos a = \frac12 \sin(2a) \leq \frac12$, we have $\dfrac{1}{\sin a\cos a}\geq 2$. Hence $$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right) = 1+\dfrac{1}{\cos a}+\dfrac{1}{\sin a}+\dfrac{1}{\sin a\cos a} \\\geq 1+2\sqrt{\dfrac{1}{\sin a\cos a}}+\dfrac{1}{\sin a\cos a}\geq 1+2\sqrt{2} + 2 = 3+ 2\sqrt{2}$$
I think it should be $(0,\frac{\pi}{2})$, so that both $\sin a$ and $\cos a$ are positive and well defined. $$\bigg (1+\frac{1}{\sin a} \bigg)\bigg (1+\frac{1}{\cos a} \bigg) = 1+ \frac{1}{\sin a} + \frac{1}{\cos a} + \frac{1}{\sin a\cos a}$$ $$\frac{1}{\sin a} + \frac{1}{\cos a} \geq \frac{4}{\sin a + \cos a} \geq \frac{4}{\sqrt{2(\sin^2 a + \cos^2 a)}} = 2\sqrt 2$$ $$\frac{1}{\sin a\cos a} \geq \frac{2}{\sin^2 a + \cos^2 a} = 2$$ So, $$\bigg (1+\frac{1}{\sin a} \bigg)\bigg (1+\frac{1}{\cos a} \bigg) = 1+ \frac{1}{\sin a} + \frac{1}{\cos a} + \frac{1}{\sin a\cos a} \geq 3+ 2\sqrt 2$$ Equality occurs when $a = \frac{\pi}{4}$
1,590,901
Prove the inequality: $$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right)\ge 3+2\sqrt{2}; \text{ for } a\in\left]0,\frac{\pi}{2}\right[$$
2015/12/27
[ "https://math.stackexchange.com/questions/1590901", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296768/" ]
I think it should be $(0,\frac{\pi}{2})$, so that both $\sin a$ and $\cos a$ are positive and well defined. $$\bigg (1+\frac{1}{\sin a} \bigg)\bigg (1+\frac{1}{\cos a} \bigg) = 1+ \frac{1}{\sin a} + \frac{1}{\cos a} + \frac{1}{\sin a\cos a}$$ $$\frac{1}{\sin a} + \frac{1}{\cos a} \geq \frac{4}{\sin a + \cos a} \geq \frac{4}{\sqrt{2(\sin^2 a + \cos^2 a)}} = 2\sqrt 2$$ $$\frac{1}{\sin a\cos a} \geq \frac{2}{\sin^2 a + \cos^2 a} = 2$$ So, $$\bigg (1+\frac{1}{\sin a} \bigg)\bigg (1+\frac{1}{\cos a} \bigg) = 1+ \frac{1}{\sin a} + \frac{1}{\cos a} + \frac{1}{\sin a\cos a} \geq 3+ 2\sqrt 2$$ Equality occurs when $a = \frac{\pi}{4}$
Differentiate to find the minimum of the LHS : $$\frac{\mathrm{d}}{\mathrm{d}a}\left(\,\left(1+\frac{1}{\sin\,a}\right)\left(1+\frac{1}{\cos\,a}\right)\,\right)=0$$ $$\left(-\frac{1}{\sin^2 a}\right)\cos a\left(1+\frac{1}{\cos a}\right)+\left(1+\frac{1}{\sin a}\right)(-\sin a)\left(-\frac{1}{\cos^2 a}\right)=0$$ $$\left(\sin\,a+1\right)\left(-\frac{1}{\cos^2 a}\right)=\left(\cos\,a+1\right)\left(\frac{1}{\sin^2 a}\right)$$ $$(1+\sin a)(\sin^2a)=(1+\cos a)(\cos^2a)=(1+\cos a)(1-\sin^2a)$$ $$(1+\sin\,a)(\sin^2a)=(1+\cos\,a)(1+\sin\,a)(1-\sin\,a)$$ $$\sin^2a=1-\cos^2a=(1-\cos\,a)(1+\cos\,a)=(1+\cos\,a)(1-\sin\,a)$$ $$1-\cos\,a=1-\sin\,a$$ $$\cos\,a=\sin\,a$$ This only happens at $a=\frac{\pi}{4}$ in the given range. And here $\sin\,a=\cos\,a=\frac{1}{\sqrt{2}}$. So the minimum of the LHS is $(1+\sqrt{2})^2=1+2+2\sqrt{2}=3+2\sqrt{2}$
1,590,901
Prove the inequality: $$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right)\ge 3+2\sqrt{2}; \text{ for } a\in\left]0,\frac{\pi}{2}\right[$$
2015/12/27
[ "https://math.stackexchange.com/questions/1590901", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296768/" ]
By the AM-GM inequality, $$\dfrac{1}{\cos a}+\dfrac{1}{\sin a} \geq 2 \sqrt{\dfrac{1}{\sin a\cos a}}$$ Since $\sin a \cos a = \frac12 \sin(2a) \leq \frac12$, we have $\dfrac{1}{\sin a\cos a}\geq 2$. Hence $$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right) = 1+\dfrac{1}{\cos a}+\dfrac{1}{\sin a}+\dfrac{1}{\sin a\cos a} \\\geq 1+2\sqrt{\dfrac{1}{\sin a\cos a}}+\dfrac{1}{\sin a\cos a}\geq 1+2\sqrt{2} + 2 = 3+ 2\sqrt{2}$$
Here is another proof: Assume $x^2+y^2=1$ then $(x+y)^2=1+2xy$ and $$\left(1+\frac{1}{x}\right)\left(1+\frac{1}{y}\right)=\frac{xy+x+y+1}{xy}=\frac{(x+y+1)^2}{(x+y)^2-1}=\frac{x+y+1}{x+y-1}$$ Now rearranging the inequality becomes $x+y\leq \sqrt{2}$. And it can be seen simply that this is the maximum value of $x+y$ given $x^2+y^2=1$, for example $z=x+y$ is a plane and its intersection with the cylinder $x^2+y^2=1$has a maximum at $x=y$.
1,590,901
Prove the inequality: $$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right)\ge 3+2\sqrt{2}; \text{ for } a\in\left]0,\frac{\pi}{2}\right[$$
2015/12/27
[ "https://math.stackexchange.com/questions/1590901", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296768/" ]
By the AM-GM inequality, $$\dfrac{1}{\cos a}+\dfrac{1}{\sin a} \geq 2 \sqrt{\dfrac{1}{\sin a\cos a}}$$ Since $\sin a \cos a = \frac12 \sin(2a) \leq \frac12$, we have $\dfrac{1}{\sin a\cos a}\geq 2$. Hence $$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right) = 1+\dfrac{1}{\cos a}+\dfrac{1}{\sin a}+\dfrac{1}{\sin a\cos a} \\\geq 1+2\sqrt{\dfrac{1}{\sin a\cos a}}+\dfrac{1}{\sin a\cos a}\geq 1+2\sqrt{2} + 2 = 3+ 2\sqrt{2}$$
Differentiate to find the minimum of the LHS : $$\frac{\mathrm{d}}{\mathrm{d}a}\left(\,\left(1+\frac{1}{\sin\,a}\right)\left(1+\frac{1}{\cos\,a}\right)\,\right)=0$$ $$\left(-\frac{1}{\sin^2 a}\right)\cos a\left(1+\frac{1}{\cos a}\right)+\left(1+\frac{1}{\sin a}\right)(-\sin a)\left(-\frac{1}{\cos^2 a}\right)=0$$ $$\left(\sin\,a+1\right)\left(-\frac{1}{\cos^2 a}\right)=\left(\cos\,a+1\right)\left(\frac{1}{\sin^2 a}\right)$$ $$(1+\sin a)(\sin^2a)=(1+\cos a)(\cos^2a)=(1+\cos a)(1-\sin^2a)$$ $$(1+\sin\,a)(\sin^2a)=(1+\cos\,a)(1+\sin\,a)(1-\sin\,a)$$ $$\sin^2a=1-\cos^2a=(1-\cos\,a)(1+\cos\,a)=(1+\cos\,a)(1-\sin\,a)$$ $$1-\cos\,a=1-\sin\,a$$ $$\cos\,a=\sin\,a$$ This only happens at $a=\frac{\pi}{4}$ in the given range. And here $\sin\,a=\cos\,a=\frac{1}{\sqrt{2}}$. So the minimum of the LHS is $(1+\sqrt{2})^2=1+2+2\sqrt{2}=3+2\sqrt{2}$
1,590,901
Prove the inequality: $$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right)\ge 3+2\sqrt{2}; \text{ for } a\in\left]0,\frac{\pi}{2}\right[$$
2015/12/27
[ "https://math.stackexchange.com/questions/1590901", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296768/" ]
Here is another proof: Assume $x^2+y^2=1$ then $(x+y)^2=1+2xy$ and $$\left(1+\frac{1}{x}\right)\left(1+\frac{1}{y}\right)=\frac{xy+x+y+1}{xy}=\frac{(x+y+1)^2}{(x+y)^2-1}=\frac{x+y+1}{x+y-1}$$ Now rearranging the inequality becomes $x+y\leq \sqrt{2}$. And it can be seen simply that this is the maximum value of $x+y$ given $x^2+y^2=1$, for example $z=x+y$ is a plane and its intersection with the cylinder $x^2+y^2=1$has a maximum at $x=y$.
Differentiate to find the minimum of the LHS : $$\frac{\mathrm{d}}{\mathrm{d}a}\left(\,\left(1+\frac{1}{\sin\,a}\right)\left(1+\frac{1}{\cos\,a}\right)\,\right)=0$$ $$\left(-\frac{1}{\sin^2 a}\right)\cos a\left(1+\frac{1}{\cos a}\right)+\left(1+\frac{1}{\sin a}\right)(-\sin a)\left(-\frac{1}{\cos^2 a}\right)=0$$ $$\left(\sin\,a+1\right)\left(-\frac{1}{\cos^2 a}\right)=\left(\cos\,a+1\right)\left(\frac{1}{\sin^2 a}\right)$$ $$(1+\sin a)(\sin^2a)=(1+\cos a)(\cos^2a)=(1+\cos a)(1-\sin^2a)$$ $$(1+\sin\,a)(\sin^2a)=(1+\cos\,a)(1+\sin\,a)(1-\sin\,a)$$ $$\sin^2a=1-\cos^2a=(1-\cos\,a)(1+\cos\,a)=(1+\cos\,a)(1-\sin\,a)$$ $$1-\cos\,a=1-\sin\,a$$ $$\cos\,a=\sin\,a$$ This only happens at $a=\frac{\pi}{4}$ in the given range. And here $\sin\,a=\cos\,a=\frac{1}{\sqrt{2}}$. So the minimum of the LHS is $(1+\sqrt{2})^2=1+2+2\sqrt{2}=3+2\sqrt{2}$
542,428
Can anyone identify this connector? Female part: [![enter image description here](https://i.stack.imgur.com/iTFuz.jpg)](https://i.stack.imgur.com/iTFuz.jpg) [![enter image description here](https://i.stack.imgur.com/gnLI1.jpg)](https://i.stack.imgur.com/gnLI1.jpg) [![enter image description here](https://i.stack.imgur.com/TLYcc.jpg)](https://i.stack.imgur.com/TLYcc.jpg) [![enter image description here](https://i.stack.imgur.com/7mL0m.jpg)](https://i.stack.imgur.com/7mL0m.jpg) The crimp parts look like this: [![enter image description here](https://i.stack.imgur.com/ZYDU8.jpg)](https://i.stack.imgur.com/ZYDU8.jpg) And the male part looks like this: [![enter image description here](https://i.stack.imgur.com/SYFKi.jpg)](https://i.stack.imgur.com/SYFKi.jpg) Context: These came with a Smoothieboard v1.1. I keep messing up the crimp connections, so I want to order some spare connectors. The documentation does not seems to identify them. If there's any sort of site that has a directory of connector types, that would be good to know too.
2021/01/13
[ "https://electronics.stackexchange.com/questions/542428", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/200654/" ]
It looks like a “Molex” 4-position connector. It seems to be part connector series “2695” (if you look up ‘Molex 2695’, you get plenty of results). If you go to Molex’s page directly for that part, they even provide a nice “Mates with/use with” section detailing the corresponding headers / crimps / pre-crimped leads). Here is a link for what I think you want: [Molex 4-Position female connector](https://www.molex.com/molex/products/part-detail/crimp_housings/0022012041)
Molex "KK" series, I believe -- [link](https://www.molex.com/molex/products/family/kk_254_rpc_connector_system)
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
The simplest version control system I am aware of is a **Revision Control System RCS**. It is a command line utility that is available out of the box on Linux systems. It's usage is quite simple. **First.** Inside current directory, create a directory where RCS's information will be stored: ``` $ mkdir RCS ``` **Second.** Store (check-in) a file into RCS: ``` $ ci -t-"My notes" notes.txt ``` Original file gets deleted. **Third.** Restore (check-out) original file from RCS: ``` $ co -u notes.txt ``` **Fourth.** Edit file as needed, now it can be restored any time: ``` $ vim notes.txt ``` RCS is also working with binary files, and supports many subsequent changes to a file.
Lots of recommendations for SVN, but I'm not sure I'd call that "simplest" from an admin point of view. You still need to set up a server, IIRC. In comparison, a DVCS like Mercurial makes no distinction between "repository" and "working copy". To put something on a server (which can be any folder you have file-sharing access to), you can just "push" it there. You also mention working on the road. DVCS are particularly good at this. Your laptop will have the whole history, so you only need to touch the server if you want to push or pull, not just to do a diff or check the history.
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
Try [Subversion (svn)](http://subversion.tigris.org/). Edit: Rich beat me to it =D. And yes, as he points out sharing is better than locking. Sounds like you're a SourceSafe user. Those were the same set of problems I was trying to address when moving out from SourceSafe =)
Lots of recommendations for SVN, but I'm not sure I'd call that "simplest" from an admin point of view. You still need to set up a server, IIRC. In comparison, a DVCS like Mercurial makes no distinction between "repository" and "working copy". To put something on a server (which can be any folder you have file-sharing access to), you can just "push" it there. You also mention working on the road. DVCS are particularly good at this. Your laptop will have the whole history, so you only need to touch the server if you want to push or pull, not just to do a diff or check the history.
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
[SVN](http://subversion.tigris.org/) covers all of these, and is quite easy to set up. Wrt point 2, sharing tends to be better than locking, as a file that is locked by someone who then goes on holiday/dies/etc. needs to be unlocked by someone before it can be worked on by another developer. SVN supports sharing 'out of the box'.
I recommend [Tortoise SVN](https://tortoisesvn.net/). SVN is a source control environment that's easy to set up and use on Windows, and Tortoise is an add on that integrates with windows explorer. Despite being simple to use, it allows different people to work on the same file and merge their changes. Even though that "can't happen" I predict at some point you'll be happy that it works that way.
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
the *SIMPLEST* system is what we here call the "Hey Chris" system. We have a networked drive that everyone can mount, and if you want to edit something you shoud "Hey, Chris, are you working on blahblah.cpp?" and Chris says "Nope." and then you edit blahblah.cpp, and stick it back on the shared drive... If you want versions, just back up the networked drive every night. I never said it was the BEST system, just the simplest.
Try [Subversion (svn)](http://subversion.tigris.org/). Edit: Rich beat me to it =D. And yes, as he points out sharing is better than locking. Sounds like you're a SourceSafe user. Those were the same set of problems I was trying to address when moving out from SourceSafe =)
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
[SVN](http://subversion.tigris.org/) covers all of these, and is quite easy to set up. Wrt point 2, sharing tends to be better than locking, as a file that is locked by someone who then goes on holiday/dies/etc. needs to be unlocked by someone before it can be worked on by another developer. SVN supports sharing 'out of the box'.
[Darcs](http://darcs.net) provides all this and a lot more. It's a distributed version contoll system, which would make it easier to access the data on the road. You can send/receive patches (similar to revisions) through email or ssh. The thing about darcs that I like the most is that it's really verbose. It really tries to help you.
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
the *SIMPLEST* system is what we here call the "Hey Chris" system. We have a networked drive that everyone can mount, and if you want to edit something you shoud "Hey, Chris, are you working on blahblah.cpp?" and Chris says "Nope." and then you edit blahblah.cpp, and stick it back on the shared drive... If you want versions, just back up the networked drive every night. I never said it was the BEST system, just the simplest.
Lots of recommendations for SVN, but I'm not sure I'd call that "simplest" from an admin point of view. You still need to set up a server, IIRC. In comparison, a DVCS like Mercurial makes no distinction between "repository" and "working copy". To put something on a server (which can be any folder you have file-sharing access to), you can just "push" it there. You also mention working on the road. DVCS are particularly good at this. Your laptop will have the whole history, so you only need to touch the server if you want to push or pull, not just to do a diff or check the history.
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
[SVN](http://subversion.tigris.org/) covers all of these, and is quite easy to set up. Wrt point 2, sharing tends to be better than locking, as a file that is locked by someone who then goes on holiday/dies/etc. needs to be unlocked by someone before it can be worked on by another developer. SVN supports sharing 'out of the box'.
Try [Subversion (svn)](http://subversion.tigris.org/). Edit: Rich beat me to it =D. And yes, as he points out sharing is better than locking. Sounds like you're a SourceSafe user. Those were the same set of problems I was trying to address when moving out from SourceSafe =)
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
Try [Subversion (svn)](http://subversion.tigris.org/). Edit: Rich beat me to it =D. And yes, as he points out sharing is better than locking. Sounds like you're a SourceSafe user. Those were the same set of problems I was trying to address when moving out from SourceSafe =)
[Darcs](http://darcs.net) provides all this and a lot more. It's a distributed version contoll system, which would make it easier to access the data on the road. You can send/receive patches (similar to revisions) through email or ssh. The thing about darcs that I like the most is that it's really verbose. It really tries to help you.
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
the *SIMPLEST* system is what we here call the "Hey Chris" system. We have a networked drive that everyone can mount, and if you want to edit something you shoud "Hey, Chris, are you working on blahblah.cpp?" and Chris says "Nope." and then you edit blahblah.cpp, and stick it back on the shared drive... If you want versions, just back up the networked drive every night. I never said it was the BEST system, just the simplest.
I recommend [Tortoise SVN](https://tortoisesvn.net/). SVN is a source control environment that's easy to set up and use on Windows, and Tortoise is an add on that integrates with windows explorer. Despite being simple to use, it allows different people to work on the same file and merge their changes. Even though that "can't happen" I predict at some point you'll be happy that it works that way.
697,526
I want to set up a source code control system that: 1. is networked, so users can access it at work or on the road 2. does not need to provide sharing, lock mode is sufficient 3. there will be only three users and they will never be working with the same code 4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple. 5. will be installed on a Windows server 6. open source or free Suggestions please.
2009/03/30
[ "https://Stackoverflow.com/questions/697526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24989/" ]
[Mercurial](http://www.selenic.com/mercurial) or [Git](http://git-scm.com/)
Lots of recommendations for SVN, but I'm not sure I'd call that "simplest" from an admin point of view. You still need to set up a server, IIRC. In comparison, a DVCS like Mercurial makes no distinction between "repository" and "working copy". To put something on a server (which can be any folder you have file-sharing access to), you can just "push" it there. You also mention working on the road. DVCS are particularly good at this. Your laptop will have the whole history, so you only need to touch the server if you want to push or pull, not just to do a diff or check the history.
25,049,968
In my localhost (with xammp) CakePHP works fine. After I completed my project and uploaded to my host, it gives me this error: ``` cakephp: Fatal error: Class 'appModel' not found in .../app/Model/Slider.php ``` Model class was called in AppController and AppModel.php (App::uses('appModel', 'Model')) & all is fine in my localhost! When I am trying to change php version, it gives me the same error, but in php 5.2 doesn't show anything but error, in php5.3, php5.4 and php5.5 it give me the error in the layout (call menus, footer... etc all but data !! My CakePHP version 2.5.2 I don't do any change or coding inside AppModel and I think that I don't do any change in lib files or something like that. what is the problem exactly?
2014/07/31
[ "https://Stackoverflow.com/questions/25049968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829518/" ]
For Python2.7, Use `io.open()` in both locations. ``` import io import shutil with io.open('/etc/passwd', encoding='latin-1', errors='ignore') as source: with io.open('/tmp/goof', mode='w', encoding='utf-8') as target: shutil.copyfileobj(source, target) ``` The above program runs without errors on my PC.
This is how you can convert ansi to utf-8 in Python 2 (you just use normal file objects): ``` with open(file_path_ansi, "r") as source: with open(file_path_utf8, "w") as target: target.write(source.read().decode("latin1").encode("utf8")) ```
25,049,968
In my localhost (with xammp) CakePHP works fine. After I completed my project and uploaded to my host, it gives me this error: ``` cakephp: Fatal error: Class 'appModel' not found in .../app/Model/Slider.php ``` Model class was called in AppController and AppModel.php (App::uses('appModel', 'Model')) & all is fine in my localhost! When I am trying to change php version, it gives me the same error, but in php 5.2 doesn't show anything but error, in php5.3, php5.4 and php5.5 it give me the error in the layout (call menus, footer... etc all but data !! My CakePHP version 2.5.2 I don't do any change or coding inside AppModel and I think that I don't do any change in lib files or something like that. what is the problem exactly?
2014/07/31
[ "https://Stackoverflow.com/questions/25049968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829518/" ]
This is how you can convert ansi to utf-8 in Python 2 (you just use normal file objects): ``` with open(file_path_ansi, "r") as source: with open(file_path_utf8, "w") as target: target.write(source.read().decode("latin1").encode("utf8")) ```
I had the same issue when I did try to write bytes to file. So my point is, bytes are already encoded. So when you use encoding keyword this leads to an error.
25,049,968
In my localhost (with xammp) CakePHP works fine. After I completed my project and uploaded to my host, it gives me this error: ``` cakephp: Fatal error: Class 'appModel' not found in .../app/Model/Slider.php ``` Model class was called in AppController and AppModel.php (App::uses('appModel', 'Model')) & all is fine in my localhost! When I am trying to change php version, it gives me the same error, but in php 5.2 doesn't show anything but error, in php5.3, php5.4 and php5.5 it give me the error in the layout (call menus, footer... etc all but data !! My CakePHP version 2.5.2 I don't do any change or coding inside AppModel and I think that I don't do any change in lib files or something like that. what is the problem exactly?
2014/07/31
[ "https://Stackoverflow.com/questions/25049968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829518/" ]
This is how you can convert ansi to utf-8 in Python 2 (you just use normal file objects): ``` with open(file_path_ansi, "r") as source: with open(file_path_utf8, "w") as target: target.write(source.read().decode("latin1").encode("utf8")) ```
> > TypeError: 'encoding' is an invalid keyword argument for this function > > > ``` open('textfile.txt', encoding='utf-16') ``` Use io, it will work in both 2.7 and 3.6 python version ``` import io io.open('textfile.txt', encoding='utf-16') ```
25,049,968
In my localhost (with xammp) CakePHP works fine. After I completed my project and uploaded to my host, it gives me this error: ``` cakephp: Fatal error: Class 'appModel' not found in .../app/Model/Slider.php ``` Model class was called in AppController and AppModel.php (App::uses('appModel', 'Model')) & all is fine in my localhost! When I am trying to change php version, it gives me the same error, but in php 5.2 doesn't show anything but error, in php5.3, php5.4 and php5.5 it give me the error in the layout (call menus, footer... etc all but data !! My CakePHP version 2.5.2 I don't do any change or coding inside AppModel and I think that I don't do any change in lib files or something like that. what is the problem exactly?
2014/07/31
[ "https://Stackoverflow.com/questions/25049968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829518/" ]
For Python2.7, Use `io.open()` in both locations. ``` import io import shutil with io.open('/etc/passwd', encoding='latin-1', errors='ignore') as source: with io.open('/tmp/goof', mode='w', encoding='utf-8') as target: shutil.copyfileobj(source, target) ``` The above program runs without errors on my PC.
I had the same issue when I did try to write bytes to file. So my point is, bytes are already encoded. So when you use encoding keyword this leads to an error.
25,049,968
In my localhost (with xammp) CakePHP works fine. After I completed my project and uploaded to my host, it gives me this error: ``` cakephp: Fatal error: Class 'appModel' not found in .../app/Model/Slider.php ``` Model class was called in AppController and AppModel.php (App::uses('appModel', 'Model')) & all is fine in my localhost! When I am trying to change php version, it gives me the same error, but in php 5.2 doesn't show anything but error, in php5.3, php5.4 and php5.5 it give me the error in the layout (call menus, footer... etc all but data !! My CakePHP version 2.5.2 I don't do any change or coding inside AppModel and I think that I don't do any change in lib files or something like that. what is the problem exactly?
2014/07/31
[ "https://Stackoverflow.com/questions/25049968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829518/" ]
For Python2.7, Use `io.open()` in both locations. ``` import io import shutil with io.open('/etc/passwd', encoding='latin-1', errors='ignore') as source: with io.open('/tmp/goof', mode='w', encoding='utf-8') as target: shutil.copyfileobj(source, target) ``` The above program runs without errors on my PC.
> > TypeError: 'encoding' is an invalid keyword argument for this function > > > ``` open('textfile.txt', encoding='utf-16') ``` Use io, it will work in both 2.7 and 3.6 python version ``` import io io.open('textfile.txt', encoding='utf-16') ```
25,049,968
In my localhost (with xammp) CakePHP works fine. After I completed my project and uploaded to my host, it gives me this error: ``` cakephp: Fatal error: Class 'appModel' not found in .../app/Model/Slider.php ``` Model class was called in AppController and AppModel.php (App::uses('appModel', 'Model')) & all is fine in my localhost! When I am trying to change php version, it gives me the same error, but in php 5.2 doesn't show anything but error, in php5.3, php5.4 and php5.5 it give me the error in the layout (call menus, footer... etc all but data !! My CakePHP version 2.5.2 I don't do any change or coding inside AppModel and I think that I don't do any change in lib files or something like that. what is the problem exactly?
2014/07/31
[ "https://Stackoverflow.com/questions/25049968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829518/" ]
> > TypeError: 'encoding' is an invalid keyword argument for this function > > > ``` open('textfile.txt', encoding='utf-16') ``` Use io, it will work in both 2.7 and 3.6 python version ``` import io io.open('textfile.txt', encoding='utf-16') ```
I had the same issue when I did try to write bytes to file. So my point is, bytes are already encoded. So when you use encoding keyword this leads to an error.
9,999,500
I am writing a simple game in XNA where you move a sprite around using WSAD. The problem is if two keys of the same direction are pressed at the same time, the movement cancels out and the character does not move. Is it possible to manually set a key to released to avoid this? Here is the key movement code: ``` if (newKeyState.IsKeyDown(Keys.W)) { position.Y -= vel; } if (newKeyState.IsKeyDown(Keys.S)) { position.Y += vel; } if (newKeyState.IsKeyDown(Keys.A)) { position.X -= vel; } if (newKeyState.IsKeyDown(Keys.D)) { position.X += vel; } ```
2012/04/03
[ "https://Stackoverflow.com/questions/9999500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1150769/" ]
I had a similar issue a little while back and was able to solve it by changing my IE9 settings. The main things I find that tend to break WatiN are compatibility mode and protected mode. Turn these off. For Protected mode you have to turn it off for each security level. Not sure if this is the issue but thought I should mention it just in case!
I've got no idea since I've got the same configuration and everything is working ok here, but what happens when you put a System.Threading.Thread.Sleep(5000); between the two lines? Is there any difference if you run the test through NUnit? What happens when you start the browser with IE ie = new IE("http://google.com"); Can you load the example from [here](https://github.com/richardlawrence/Cuke4Nuke/downloads) and try to run the included example - \example\watin?
32,105,834
I want to add an "Always-On-Top"-menuentry to the system menu of all windows (the menu which opens when you right click the titlebar or click the icon). I'd prefer C# or C++, but if worst comes to worst I'll also use VB... I know there are some applications like Dexpot which do this, but I was unable to find useful source code or free applications which do this for all windows and not just their own. I also know that there are other ways to achieve this functionality (AutoHotkeys or small programs which live in the system tray and let you select windows which should stay on top), but I'm looking for a more fluent and intuitive way. Ideally I'd add a small pin button to the titlebar, but my guess is that that's much more involved, so I'll stick with the menu variant for now. Ideas? Thanks!
2015/08/19
[ "https://Stackoverflow.com/questions/32105834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2061551/" ]
Use the `AddMenuItems()` method and test using MS-Paint. One thing I noticed is that after the program is closed, the modified system menu becomes wonky. Possibly this is because the events are not coming from the process' UI thread. A possible work-around is in the `ApplicationExit` event to call `GetMenu(hMainWindowHandle, true)`, where true means revert the menu. ``` public static class AlwaysOnTop { static AlwaysOnTop() { Application.ApplicationExit += delegate { try { foreach (DictionaryEntry de in htThreads) { Hook h = (Hook) de.Value; RemoveMenu(h.hMenu, h.uniqueId, 0); //DeleteMenu(h.hMenu, h.uniqueId, 0); UnhookWinEvent(h.hWinEventHook); } } catch { } }; } private const int EVENT_OBJECT_INVOKED = 0x8013; private const int OBJID_SYSMENU = -1; private const int WINEVENT_OUTOFCONTEXT = 0; private const int MF_STRING = 0x00000000; private const int HWND_TOPMOST = -1; private const int HWND_NOTOPMOST = -2; private const int SWP_NOMOVE = 0x0002; private const int SWP_NOSIZE = 0x0001; private const uint MF_UNCHECKED = 0x00000000; private const uint MF_CHECKED = 0x00000008; [DllImport("user32.dll")] private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); [DllImport("user32.dll")] private static extern bool AppendMenu(IntPtr hMenu, uint uFlags, uint uIDNewItem, String lpNewItem); [DllImport("user32.dll", SetLastError = true)] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); [DllImport("user32.dll",SetLastError=true)] private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventProc lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags); [DllImport("user32.dll", SetLastError = true)] internal static extern int UnhookWinEvent(IntPtr hWinEventHook); [DllImport("user32.dll", SetLastError=true)] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); [DllImport("user32.dll")] private static extern bool CheckMenuItem(IntPtr hMenu, uint uIDCheckItem, uint uCheck); [DllImport("user32.dll")] private static extern bool RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags); //[DllImport("user32.dll")] //private static extern bool DeleteMenu(IntPtr hMenu, uint uPosition, uint uFlags); private static Hashtable htThreads = new Hashtable(); private static WinEventProc CallWinEventProc = new WinEventProc(EventCallback); private delegate void WinEventProc(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime); private static void EventCallback(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime) { //callback function, called when message is intercepted if (iEvent == EVENT_OBJECT_INVOKED) { if (idObject == OBJID_SYSMENU) { Hook h = (Hook) htThreads[(uint) dwEventThread]; if (h != null && h.uniqueId == idChild) { bool b = !h.Checked; if (b) SetWindowPos(h.hMainWindowHandle, (IntPtr) HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); else SetWindowPos(h.hMainWindowHandle, (IntPtr) HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); CheckMenuItem(h.hMenu, h.uniqueId, (b ? MF_CHECKED : MF_UNCHECKED)); h.Checked = b; } } } } private class Hook { public uint uniqueId = 1001; public IntPtr hWinEventHook; public IntPtr hMenu; public IntPtr hMainWindowHandle; public bool Checked; } public static void AddMenuItems() { Process[] arr = Process.GetProcesses(); foreach (Process p in arr) { if (p.MainWindowHandle == IntPtr.Zero) continue; if (p.ProcessName != "mspaint") // <-- remove or change this line continue; IntPtr hMenu = GetSystemMenu(p.MainWindowHandle, false); if (hMenu == IntPtr.Zero) continue; bool b = AppendMenu(hMenu, MF_STRING, 1001, "Always On Top"); uint pid = 0; uint tid = GetWindowThreadProcessId(p.MainWindowHandle, out pid); Hook h = (Hook) htThreads[tid]; if (h == null) { h = new Hook(); h.hMenu = hMenu; h.hWinEventHook = SetWinEventHook(EVENT_OBJECT_INVOKED, EVENT_OBJECT_INVOKED, IntPtr.Zero, CallWinEventProc, pid, tid, WINEVENT_OUTOFCONTEXT); h.hMainWindowHandle = p.MainWindowHandle; htThreads[tid] = h; } } } } ```
Here is an example of using a `ToolStripDropDown` instead of the default window menu. It can be made to look more like the default window menu by setting the background color, font and adding some icons if needed. It was surprisingly more difficult to hide the default window menu. Maybe there is a better way. The failed attempts at hiding the menu are left in the code below. The default menu is still displayed when right clicking on the caption bar. ``` public class FormCustomMenu : Form { WindowMenu WindowMenu = new WindowMenu(); public FormCustomMenu() { //this.ShowIcon = false; } private const int WM_INITMENU = 0x116; private const int WM_INITMENUPOPUP = 0x117; private const int WM_SYSCOMMAND = 0x112; protected override void WndProc(ref Message m) { if (m.Msg == WM_SYSCOMMAND) { //WM_INITMENU || m.Msg == WM_INITMENUPOPUP) {} Point pt = Cursor.Position; int h = SystemInformation.CaptionHeight; Rectangle r = new Rectangle(this.Location, new Size(h, h)); if (!r.Contains(pt) || Cursor.Current != Cursors.Default) base.WndProc(ref m); else { Rectangle r2 = RectangleToScreen(this.ClientRectangle); WindowMenu.Show(r2.Location); } } else { base.WndProc(ref m); } } /* Failed attempts at hiding the default window menu. protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); //IntPtr hMenu = GetSystemMenu(Handle, false); //SendMessage(hMenu, WM_SETREDRAW, (IntPtr) 0, (IntPtr) 0); //int count = GetMenuItemCount(hMenu); //for (int i = count - 1; i >= 3; i--) // RemoveMenu(hMenu, (uint) i, MF_BYPOSITION); } [DllImport("user32.dll")] public static extern int GetMenuItemCount(IntPtr hMenu); [DllImport("user32.dll")] private static extern bool RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags); //[DllImport("user32.dll")] //public static extern IntPtr DestroyMenu(IntPtr hMenu); [DllImport("user32.dll")] public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); [DllImport("user32.dll")] private static extern bool DeleteMenu(IntPtr hMenu, uint uPosition, uint uFlags); private const int MF_BYPOSITION = 0x00000400; private const int WM_SETREDRAW = 11; [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, IntPtr wParam, IntPtr lParam); // this also removes the min/max/close buttons: //private const int WS_SYSMENU = 0x80000; //protected override CreateParams CreateParams { // get { // var p = base.CreateParams; // p.Style = p.Style & ~WS_SYSMENU; // return p; // } //} */ } public class WindowMenu : ToolStripDropDown { public WindowMenu() { Items.Add(new ToolStripMenuItem("Custom1")); } } ```
15,921,574
I build a worklight application. create android app and test this application with local machine , its working fine with emulator.but when i try to test this application with android tablet it through error "The Application failed connecting to the service". I try to find application-descriptor.xml and fix localhost to `192.168.1.1:8080` my ip local machine,but it not working.In my tablet I can't to go to `192.168.1.1:8080/console/index.html` Can anybody help me regarding this issue. how can i fix this one in my worklight android application and run it on my android tablet
2013/04/10
[ "https://Stackoverflow.com/questions/15921574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265231/" ]
Some things to check: - Are your tablet and your worklight development machine on the same wireless network? (they need to be!) - Does your computer have a firewall on it which may need configuring to let the traffic through. As a test you could briefly disable the firewall and see if you then have access (subject to disclaimer of the risk involved in disabling the firewall). A test without disabling the firewall would be to try accessing 192.168.1.1:8080 from another desktop/laptop machine on that same subnet.
In a command window, run `ipconfig` and copy the IPv4 address. This is the IP address you need to place as the value for `worklightServerRootURL` in the file application-descriptor.xml. The IP address you are usingnow does not look to me like the correct (public) IP address that you need to use. Try my above suggestion.
15,921,574
I build a worklight application. create android app and test this application with local machine , its working fine with emulator.but when i try to test this application with android tablet it through error "The Application failed connecting to the service". I try to find application-descriptor.xml and fix localhost to `192.168.1.1:8080` my ip local machine,but it not working.In my tablet I can't to go to `192.168.1.1:8080/console/index.html` Can anybody help me regarding this issue. how can i fix this one in my worklight android application and run it on my android tablet
2013/04/10
[ "https://Stackoverflow.com/questions/15921574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265231/" ]
Some things to check: - Are your tablet and your worklight development machine on the same wireless network? (they need to be!) - Does your computer have a firewall on it which may need configuring to let the traffic through. As a test you could briefly disable the firewall and see if you then have access (subject to disclaimer of the risk involved in disabling the firewall). A test without disabling the firewall would be to try accessing 192.168.1.1:8080 from another desktop/laptop machine on that same subnet.
How about adding "192.168.181.1:8080" in application-descriptor.xml?
15,921,574
I build a worklight application. create android app and test this application with local machine , its working fine with emulator.but when i try to test this application with android tablet it through error "The Application failed connecting to the service". I try to find application-descriptor.xml and fix localhost to `192.168.1.1:8080` my ip local machine,but it not working.In my tablet I can't to go to `192.168.1.1:8080/console/index.html` Can anybody help me regarding this issue. how can i fix this one in my worklight android application and run it on my android tablet
2013/04/10
[ "https://Stackoverflow.com/questions/15921574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265231/" ]
Some things to check: - Are your tablet and your worklight development machine on the same wireless network? (they need to be!) - Does your computer have a firewall on it which may need configuring to let the traffic through. As a test you could briefly disable the firewall and see if you then have access (subject to disclaimer of the risk involved in disabling the firewall). A test without disabling the firewall would be to try accessing 192.168.1.1:8080 from another desktop/laptop machine on that same subnet.
I would suggest the following debugging steps: a) Go to your device browser and browse to http: //xx.xx.xx.xx:8080/console -> If this doesn't work, you have an obvious ip address issue. Then you have to figure out why, maybe you have a Symantec thingy that blocks any incoming traffic to your desktop - which they do. You should do an explicit allow. b) If a) works, then you need to check in your code to make sure your app does try to connect to the server at startup. Or else the app will only try to connect when it calls adapter. Now, go to your code. open the initOptions.js file. I typically, would set connectOnStartup to true, but also enable the onConnectionFailure so that it runs offline when there is no connection. var wlInitOptions = { ``` // # Should application automatically attempt to connect to Worklight Server on application start up // # The default value is true, we are overriding it to false here. connectOnStartup : true, // # The callback function to invoke in case application fails to connect to Worklight Server onConnectionFailure: function (){wlCommonInit();}, // # Worklight server connection timeout timeout: 2000, ``` }; 3) Make sure you have the right URL in the application-descriptor.xml <worklightServerRootURL><http://xx.xx.xx.xx:8080> </worklightServerRootURL> If you are using the consumer edition (the real purchased WL), your URL would be. <worklightServerRootURL><http://xx.xx.xx.xx:9080/worklight> </worklightServerRootURL> (Note no space in between those URL - it's just this website putting a space there when there is a line break) Redeploy your code to the WL server and create a new APK file. Update your device with the new APK file. 4) Do a test with the console again, you should see the console. Click on the Preview app link, it should work. 5) Now that you have updated your code on the server and the APK file. Open it up again on the device. Do you still see the error message? If things still not work. 6) Go to the app setting, since you have enable offline mode, it would allow you to access the App settings (it's the 4th button in Android) Go to **Worklight Settings**. Select **Server Address** -> Add the worklight URL to the Server URL. When you go back to the app, this will automatically reload the content from your WL server.
15,921,574
I build a worklight application. create android app and test this application with local machine , its working fine with emulator.but when i try to test this application with android tablet it through error "The Application failed connecting to the service". I try to find application-descriptor.xml and fix localhost to `192.168.1.1:8080` my ip local machine,but it not working.In my tablet I can't to go to `192.168.1.1:8080/console/index.html` Can anybody help me regarding this issue. how can i fix this one in my worklight android application and run it on my android tablet
2013/04/10
[ "https://Stackoverflow.com/questions/15921574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265231/" ]
Some things to check: - Are your tablet and your worklight development machine on the same wireless network? (they need to be!) - Does your computer have a firewall on it which may need configuring to let the traffic through. As a test you could briefly disable the firewall and see if you then have access (subject to disclaimer of the risk involved in disabling the firewall). A test without disabling the firewall would be to try accessing 192.168.1.1:8080 from another desktop/laptop machine on that same subnet.
1. Check ip in local machine ipconfig ( field Adaptador de Ethernet ) 2. Set this IP in field host name configuration server. 3. Rebuild 4. The other test is to check the direction in other machine, in the same network.
15,921,574
I build a worklight application. create android app and test this application with local machine , its working fine with emulator.but when i try to test this application with android tablet it through error "The Application failed connecting to the service". I try to find application-descriptor.xml and fix localhost to `192.168.1.1:8080` my ip local machine,but it not working.In my tablet I can't to go to `192.168.1.1:8080/console/index.html` Can anybody help me regarding this issue. how can i fix this one in my worklight android application and run it on my android tablet
2013/04/10
[ "https://Stackoverflow.com/questions/15921574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265231/" ]
1. Check ip in local machine ipconfig ( field Adaptador de Ethernet ) 2. Set this IP in field host name configuration server. 3. Rebuild 4. The other test is to check the direction in other machine, in the same network.
In a command window, run `ipconfig` and copy the IPv4 address. This is the IP address you need to place as the value for `worklightServerRootURL` in the file application-descriptor.xml. The IP address you are usingnow does not look to me like the correct (public) IP address that you need to use. Try my above suggestion.
15,921,574
I build a worklight application. create android app and test this application with local machine , its working fine with emulator.but when i try to test this application with android tablet it through error "The Application failed connecting to the service". I try to find application-descriptor.xml and fix localhost to `192.168.1.1:8080` my ip local machine,but it not working.In my tablet I can't to go to `192.168.1.1:8080/console/index.html` Can anybody help me regarding this issue. how can i fix this one in my worklight android application and run it on my android tablet
2013/04/10
[ "https://Stackoverflow.com/questions/15921574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265231/" ]
1. Check ip in local machine ipconfig ( field Adaptador de Ethernet ) 2. Set this IP in field host name configuration server. 3. Rebuild 4. The other test is to check the direction in other machine, in the same network.
How about adding "192.168.181.1:8080" in application-descriptor.xml?
15,921,574
I build a worklight application. create android app and test this application with local machine , its working fine with emulator.but when i try to test this application with android tablet it through error "The Application failed connecting to the service". I try to find application-descriptor.xml and fix localhost to `192.168.1.1:8080` my ip local machine,but it not working.In my tablet I can't to go to `192.168.1.1:8080/console/index.html` Can anybody help me regarding this issue. how can i fix this one in my worklight android application and run it on my android tablet
2013/04/10
[ "https://Stackoverflow.com/questions/15921574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265231/" ]
1. Check ip in local machine ipconfig ( field Adaptador de Ethernet ) 2. Set this IP in field host name configuration server. 3. Rebuild 4. The other test is to check the direction in other machine, in the same network.
I would suggest the following debugging steps: a) Go to your device browser and browse to http: //xx.xx.xx.xx:8080/console -> If this doesn't work, you have an obvious ip address issue. Then you have to figure out why, maybe you have a Symantec thingy that blocks any incoming traffic to your desktop - which they do. You should do an explicit allow. b) If a) works, then you need to check in your code to make sure your app does try to connect to the server at startup. Or else the app will only try to connect when it calls adapter. Now, go to your code. open the initOptions.js file. I typically, would set connectOnStartup to true, but also enable the onConnectionFailure so that it runs offline when there is no connection. var wlInitOptions = { ``` // # Should application automatically attempt to connect to Worklight Server on application start up // # The default value is true, we are overriding it to false here. connectOnStartup : true, // # The callback function to invoke in case application fails to connect to Worklight Server onConnectionFailure: function (){wlCommonInit();}, // # Worklight server connection timeout timeout: 2000, ``` }; 3) Make sure you have the right URL in the application-descriptor.xml <worklightServerRootURL><http://xx.xx.xx.xx:8080> </worklightServerRootURL> If you are using the consumer edition (the real purchased WL), your URL would be. <worklightServerRootURL><http://xx.xx.xx.xx:9080/worklight> </worklightServerRootURL> (Note no space in between those URL - it's just this website putting a space there when there is a line break) Redeploy your code to the WL server and create a new APK file. Update your device with the new APK file. 4) Do a test with the console again, you should see the console. Click on the Preview app link, it should work. 5) Now that you have updated your code on the server and the APK file. Open it up again on the device. Do you still see the error message? If things still not work. 6) Go to the app setting, since you have enable offline mode, it would allow you to access the App settings (it's the 4th button in Android) Go to **Worklight Settings**. Select **Server Address** -> Add the worklight URL to the Server URL. When you go back to the app, this will automatically reload the content from your WL server.
30,346,744
I am preparing for an Oracle examination and answered incorrectly to the following question: > > the combination abstract private is legal for inner classes > > > As it turns the answer is true, I answered false, as I could not find any use cases for having an abstract private inner class, that cannot be overridden from subclasses. Can someone explain, why/for what do we have that in the language?
2015/05/20
[ "https://Stackoverflow.com/questions/30346744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3194545/" ]
The Java language specification defines the meaning of private members as follows: > > Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. > > > That is, a private inner class is accessible (and may be subclassed) from any code residing in the same source file. For instance, you could do: ``` public class C { private abstract class A { abstract void foo(); } void bar() { new A() { @Override void foo() { // do something } } } } ``` It is interesting to note that a method declared private can not be overriden, but methods in private classes can be.
> > the combination abstract private is legal for inner classes > > > > Its a bit confusing but the rule is that an inner class can't have an abstract private method. if exam is saying the contrary then its wrong. **UPDATE**: if what you mean is in class declaration, then answer is true, check this **valid** piece of code... ``` public class MyOuter { abstract private class MyInner { //the combination abstract private is legal for inner classes: TRUE } } ``` To know why or when use it, check the [suggested link](https://stackoverflow.com/questions/13437922/why-nested-abstract-class-in-java), there is a [good explanation](https://stackoverflow.com/a/13437967/3850595) about this...
58,340,926
I am trying to use a custom element in my application but after upgrading to the current version of lit-element, I can't seem to find the replacement function for **\_didRender**. I have tried **firstUpdated** and **connectedCallback** with no success. What should I do. The code renders but after rendering and amking an ajax call, I expected the render to be updated but it doesnt ``` import {LitElement, html} from 'lit-element'; import '@material/mwc-formfield/mwc-formfield.js'; import '@material/mwc-checkbox/mwc-checkbox.js' import '@polymer/iron-ajax/iron-ajax.js'; class FhirActiveStatus extends LitElement{ static get properties() { return { /**activeStatus is used to show active status of person true or false. Use this property to show/hide. Default: true */ activeStatus: {type:Boolean}, /**url is used to make AJAX call to FHIR resource. Default: null */ url: {type:String}, /**value is used to take the input value of each field*/ value: {type:Boolean} } } /**default value of properties set in constructor*/ constructor() { super(); this.activeStatus = 'true'; this.value = false; } /**_didRender() was used here after the ajax call had been made*/ async firstUpdated() { this.shadowRoot.getElementById('ajax').addEventListener('iron-ajax-response', function (e) { var active = this.parentNode.host; if (e.detail.response.active) { active.shadowRoot.querySelector('.activeState').checked = true; } else if (!e.detail.response.active) { active.shadowRoot.querySelector('.activeState').checked = false; } else { this.parentNode.removeChild(this.parentNode.querySelector('#activeDiv')); } }); } render() { return html` <div id="activeDiv"> ${this.activeStatus !== 'false' ? html`<mwc-formfield class="activeStatus" alignEnd label="ACTIVE STATUS:"> <mwc-checkbox id="active" checked="${this.value}" class="activeState" @click="${e => this.value = e.target.value}"></mwc-checkbox> </mwc-formfield>` : ''} </div> <iron-ajax auto id="ajax" bubbles auto handle-as="json" url="${this.url}"></iron-ajax> `; } } window.customElements.define('fhir-active-status', FhirActiveStatus); ```
2019/10/11
[ "https://Stackoverflow.com/questions/58340926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471519/" ]
have a look at the LitElement life cycle <https://lit-element.polymer-project.org/guide/lifecycle> \_didRender() i believe now is **updated()**
You also have the ability to rely on `await this.updateComplete;` in the case that you'd like to write async/await style code over callback style code.
49,864,528
I am trying to automate docx report generation process. For this I am using java and docx4j. I have a template document containing only single page.I would like to copy that page modify it and save it in another docx document.The output report is of multiple similar pages with modification from the template. How do I go about it. PS : java and docx4j are my first choice but I am open to solutions apart from java and docx4j.
2018/04/16
[ "https://Stackoverflow.com/questions/49864528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5958785/" ]
Leaving it up to you to modify the template, here is how you could add one document to the end of another document. Suppose `base.docx` contains "This is the base document." and `template.docx` contains "The time is:", then after executing this code: ``` WordprocessingMLPackage doc = Docx4J.load(new File("base.docx")); WordprocessingMLPackage template = Docx4J.load(new File("template.docx")); MainDocumentPart main = doc.getMainDocumentPart(); Br pageBreak = Context.getWmlObjectFactory().createBr(); pageBreak.setType(STBrType.PAGE); main.addObject(pageBreak); for (Object obj : template.getMainDocumentPart().getContent()) { main.addObject(obj); } main.addParagraphOfText(LocalDateTime.now().toString()); doc.save(new File("result.docx")); ``` Then `result.docx` will contain something like: ```none This is the base document. ^L The time is: 2018-04-16T17:37:13.541984200 ``` (Where ^L represents a page break.)
> > To be more precise my original template is containing only header and some styling component. > > > This kind of information can be stored in a Word stylesheet (.dotx file). > > PS : java and docx4j are my first choice but I am open to solutions apart from java and docx4j. > > > A good tool would be [pxDoc](https://www.pxdoc.fr): you can specify a dedicated stylesheet in your document generator, or use "variable styles"and specify the stylesheet only when you launch the document generation
2,317,677
I am developing the smart device application. There are different screen resolution for different window mobile devices. I want to know that which is the standard screen resolution for windows mobile?
2010/02/23
[ "https://Stackoverflow.com/questions/2317677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/265103/" ]
There is no standard. Many possibilities exist and the recent devices usually have 800x480. Others have: 640x480, 320x240, 320x320, 400x240, etc.
The default controls scale pretty well across resolutions. I've created forms in Visual Studio and deployed to multiple resolutions without any modifications.
69,828,385
App.jsx ``` import * as React from 'react'; import * as ReactDOM from 'react-dom'; function render() { ReactDOM.render(<h2>Hello from React!</h2>, document.body); } render(); ``` So, right now my friend made a React website that I have to try to port over to an Electron App that I got off of the team's Github. However, when I change the code into this: App.jsx ``` import * as React from 'react'; import * as ReactDOM from 'react-dom'; import App from './App'; function render() { ReactDOM.render(<h1>Goodbye</h1>, document.body); } render(); ``` Nothing changes at all. All that pops up is the "Hello from React!" from earlier. I search throughout all my code files for any other instances of "Hello from React!" with vscode, but I do not see any. Does anyone know why this is happening and what I can do to fix it?
2021/11/03
[ "https://Stackoverflow.com/questions/69828385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13948708/" ]
Ok, so the answer was adding this environment variable : ``` JAVA_OPTS_APPEND=-javaagent:{{path_to_elastic_apm_agent}} ``` this command allows you to launch your java application with options.
The Java agent allows multiple ways to configure it, one of which are command line system properties. Others include packaging an `elasticapm.properties` resource file or setting environment variables. [Check out the docs](https://www.elastic.co/guide/en/apm/agent/java/current/configuration.html). Small excerpt: > > * **Properties file**: The `elasticapm.properties` file is located in the same folder as the agent jar, or provided through the `config_file` option. dynamic config. > * **Environment variables**: All configuration keys are in uppercase and prefixed with `ELASTIC_APM_`. > > > Different option sources have different priority and precedence. To attach the agent to a running JVM process (from within your application), you can use the [API to self-attach](https://www.elastic.co/guide/en/apm/agent/java/master/setup-attach-api.html#setup-attach-api-configuration).
25,199,553
``` text = ['This', 'brand', 'she', 'quenched', 'in', 'a', 'cool', 'well', 'by', 'Which', 'from', 'Love', "'", 's', 'fire'] ``` When I do a `' '.join(text)` I get the result; "This brand she quenched in a cool well by Which from Love ' s fire" I would like to join "Love ' s" as "Love's" instead of separating them. How can I do that along with the `' '.join(text)`?
2014/08/08
[ "https://Stackoverflow.com/questions/25199553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1948860/" ]
You can run a replace after joining. (Replace `" ' "` with `"'"`) ``` ' '.join(text).replace(" ' ", "'") ```
``` import re print re.sub(r"\s\'\s","'",' '.join(text)) ``` You can use this as a hack.It would be tough to join contents of list by 2 conditions.
27,369,502
I'm trying to make a vertical social share buttons for a blog post. ------------------------------------------------------------------- I want the "share\_DIV" position to be fixed after scrolling to a certain point. * because the "Share\_DIV" is not supposed to appear on header area, its position will be absolute and calculated by *jQuery* to let it be under `*the header*` and `*the title*`, then when you scroll down and reach the text body "share\_DIV" should **start** walking with you while scrolling down to the end of the text body. So the **share\_DIV** should move vertically on the scroll event, only between START POINT -> END POINT *share\_DIV has class `.vertical-container` in fiddle code.* [Fiddle Example](http://jsfiddle.net/markor91/h5t7pgfb/25/) will explain exactly what I need. How can I get it done with jQuery?
2014/12/09
[ "https://Stackoverflow.com/questions/27369502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1015648/" ]
You don't need to initialize it with a specific size - you can add objects later: ``` NSMutableArray *myArray = [NSMutableArray array]; for (int i = 0; i < 100; i++) { [myArray addObject:someData]; } ``` There are slight performance gains if you know the size ahead of time: ``` NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:100]; ``` But this is optional.
`NSNull` is the class used to represent an unset, invalid or non-existent object. Therefore you can pad the array to a specific size using instances of this class. ``` NSUInteger sizeOfArray = 10; NSMutableArray *someArray = [NSMutableArray array]; for (NSUInteger i = 0; i < sizeOfArray; i++) { [someArray addObject:[NSNull null]]; } ``` Further, you can't use the syntax `someArray[i] = xyz;` if the value at position `i` doesn't exist, as it will cause an out of bounds error.
214,687
I'm looking for a library to save an array of colour data to a PNG file. (That's all there is to it, right? I know very little about the internals of a PNG.) This is for use in Nintendo DS development, so something lightweight is preferable. I don't need any other fancy features like rotation, etc.
2008/10/18
[ "https://Stackoverflow.com/questions/214687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55/" ]
To encode any kind of PNG file, libpng is the way of the walk. However, on small devices like the DS you really want to store your image data in the format which the display hardware expects. It is technically possible to get libpng working on the platform, but it will add significant overhead, both in terms of loadtimes and footprint.
Have you looked at libpng? <http://www.libpng.org/pub/png/libpng.html> I'm not sure whether the memory footprint will be acceptable, but you should probably be aware that PNG files are a lot more involved than just an array of colors. Performance is likely to be a concern on a DS. If you go with libpng, you'll also need zlib, and if you're using DevKitPro, you'll probably run into some missing functions (from playing with the code for 5 minutes, it looks like it relies on pow() which doesn't seem to be in libnds.) I have no idea what the official Nintendo SDK offers in the way of a standard library - you might be in better shape if that's what you're using.
214,687
I'm looking for a library to save an array of colour data to a PNG file. (That's all there is to it, right? I know very little about the internals of a PNG.) This is for use in Nintendo DS development, so something lightweight is preferable. I don't need any other fancy features like rotation, etc.
2008/10/18
[ "https://Stackoverflow.com/questions/214687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55/" ]
Have you looked at libpng? <http://www.libpng.org/pub/png/libpng.html> I'm not sure whether the memory footprint will be acceptable, but you should probably be aware that PNG files are a lot more involved than just an array of colors. Performance is likely to be a concern on a DS. If you go with libpng, you'll also need zlib, and if you're using DevKitPro, you'll probably run into some missing functions (from playing with the code for 5 minutes, it looks like it relies on pow() which doesn't seem to be in libnds.) I have no idea what the official Nintendo SDK offers in the way of a standard library - you might be in better shape if that's what you're using.
I managed to find a library that supports PNG (using libpng) and allows you to just give it raw image data. It's called [LibPicture](http://www.dragonminded.com/?loc=ndsdev/LibPicture). It's a bit hefty though: ~1MB.
214,687
I'm looking for a library to save an array of colour data to a PNG file. (That's all there is to it, right? I know very little about the internals of a PNG.) This is for use in Nintendo DS development, so something lightweight is preferable. I don't need any other fancy features like rotation, etc.
2008/10/18
[ "https://Stackoverflow.com/questions/214687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55/" ]
To encode any kind of PNG file, libpng is the way of the walk. However, on small devices like the DS you really want to store your image data in the format which the display hardware expects. It is technically possible to get libpng working on the platform, but it will add significant overhead, both in terms of loadtimes and footprint.
I managed to find a library that supports PNG (using libpng) and allows you to just give it raw image data. It's called [LibPicture](http://www.dragonminded.com/?loc=ndsdev/LibPicture). It's a bit hefty though: ~1MB.
50,247,580
I have a keyword like "Click Menu Item" which takes an argument `${menuItem}`.It then clicks on the corresponding menu item making a dynamic locator xpath. I need to define/set the `LocatorVariables` and their Xpaths in separate `Locators.robot` resource file so that my testcases/keywords are xpaths free. ``` ** Keywords *** Click Menu Item [Arguments] ${menuItem} Click Element ${MenuBarLeft_MenuItem} ``` So I want to accept the variable `${menuItem}` in a Global Scope so that it will be accessible in `Locators.robot` Resource file. Though, I understand this can be achieved by using below: ``` "Set Global Variable ${menuItem} ${menuItem}" ``` but i wanted to know is there an way I can skip this step by automatic defining the scope while accepting the variable in keyword. Also please let me know if there is a better way to handle dynamic locators for such case.
2018/05/09
[ "https://Stackoverflow.com/questions/50247580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9340007/" ]
You should use `object` name in template: ``` {% block content %} <h3>{{ object.title }}</h3> <h6> on {{ object.datetime }}</h6> <div class = "code"> {{ object.content|linebreaks }} </div> {% endblock %} ``` Or if you want to use `Tutorial` variable, you need to pass `context_object_name=Tutorials` to the view: ``` path('<int:pk>', DetailView.as_view( model=Tutorials, template_name="tutorials/post.html", context_object_name='Tutorials')), ```
plus for @neverwalkaloner's answer. The reason why you can use `object` or `context_object_name` is cause you inherit `DetailView`. In `DetailView`, it has `get_object()` method. ``` def get_object(self, queryset=None): """ Return the object the view is displaying. Require `self.queryset` and a `pk` or `slug` argument in the URLconf. Subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) slug = self.kwargs.get(self.slug_url_kwarg) if pk is not None: queryset = queryset.filter(pk=pk) # Next, try looking up by slug. if slug is not None and (pk is None or self.query_pk_and_slug): slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) # If none of those are defined, it's an error. if pk is None and slug is None: raise AttributeError("Generic detail view %s must be called with " "either an object pk or a slug." % self.__class__.__name__) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404(_("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) return obj ``` It will return model object, and also you can override this method. And in `get()` method in `DetailView`, ``` def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) ``` As you see, it define `self.object` to `self.get_object()` so you can use `self.object` inside `DetailView`. Finally, you can use `object` in your template because of `get_context_data()`. `DetailView` basically add 'object' to context, so you can use it. ``` def get_context_data(self, **kwargs): """Insert the single object into the context dict.""" context = {} if self.object: context['object'] = self.object context_object_name = self.get_context_object_name(self.object) if context_object_name: context[context_object_name] = self.object context.update(kwargs) return super().get_context_data(**context) ``` It's true that CBV has little bit learning curve, but when you see django source code and read about docs, it's easy to follow. +I highly recommend [ccbv.co.kr](https://ccbv.co.uk/) - you can see which view and mixin that CBV inherit, and it's methods too.
50,247,580
I have a keyword like "Click Menu Item" which takes an argument `${menuItem}`.It then clicks on the corresponding menu item making a dynamic locator xpath. I need to define/set the `LocatorVariables` and their Xpaths in separate `Locators.robot` resource file so that my testcases/keywords are xpaths free. ``` ** Keywords *** Click Menu Item [Arguments] ${menuItem} Click Element ${MenuBarLeft_MenuItem} ``` So I want to accept the variable `${menuItem}` in a Global Scope so that it will be accessible in `Locators.robot` Resource file. Though, I understand this can be achieved by using below: ``` "Set Global Variable ${menuItem} ${menuItem}" ``` but i wanted to know is there an way I can skip this step by automatic defining the scope while accepting the variable in keyword. Also please let me know if there is a better way to handle dynamic locators for such case.
2018/05/09
[ "https://Stackoverflow.com/questions/50247580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9340007/" ]
You should use `object` name in template: ``` {% block content %} <h3>{{ object.title }}</h3> <h6> on {{ object.datetime }}</h6> <div class = "code"> {{ object.content|linebreaks }} </div> {% endblock %} ``` Or if you want to use `Tutorial` variable, you need to pass `context_object_name=Tutorials` to the view: ``` path('<int:pk>', DetailView.as_view( model=Tutorials, template_name="tutorials/post.html", context_object_name='Tutorials')), ```
{% block content %} ### {{ object.title }} ``` <h6> on {{ object.datetime }}</h6> <div class = "code"> {{ object.content|linebreak }} </div> ``` {% endblock %}
50,247,580
I have a keyword like "Click Menu Item" which takes an argument `${menuItem}`.It then clicks on the corresponding menu item making a dynamic locator xpath. I need to define/set the `LocatorVariables` and their Xpaths in separate `Locators.robot` resource file so that my testcases/keywords are xpaths free. ``` ** Keywords *** Click Menu Item [Arguments] ${menuItem} Click Element ${MenuBarLeft_MenuItem} ``` So I want to accept the variable `${menuItem}` in a Global Scope so that it will be accessible in `Locators.robot` Resource file. Though, I understand this can be achieved by using below: ``` "Set Global Variable ${menuItem} ${menuItem}" ``` but i wanted to know is there an way I can skip this step by automatic defining the scope while accepting the variable in keyword. Also please let me know if there is a better way to handle dynamic locators for such case.
2018/05/09
[ "https://Stackoverflow.com/questions/50247580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9340007/" ]
plus for @neverwalkaloner's answer. The reason why you can use `object` or `context_object_name` is cause you inherit `DetailView`. In `DetailView`, it has `get_object()` method. ``` def get_object(self, queryset=None): """ Return the object the view is displaying. Require `self.queryset` and a `pk` or `slug` argument in the URLconf. Subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) slug = self.kwargs.get(self.slug_url_kwarg) if pk is not None: queryset = queryset.filter(pk=pk) # Next, try looking up by slug. if slug is not None and (pk is None or self.query_pk_and_slug): slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) # If none of those are defined, it's an error. if pk is None and slug is None: raise AttributeError("Generic detail view %s must be called with " "either an object pk or a slug." % self.__class__.__name__) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404(_("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) return obj ``` It will return model object, and also you can override this method. And in `get()` method in `DetailView`, ``` def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) ``` As you see, it define `self.object` to `self.get_object()` so you can use `self.object` inside `DetailView`. Finally, you can use `object` in your template because of `get_context_data()`. `DetailView` basically add 'object' to context, so you can use it. ``` def get_context_data(self, **kwargs): """Insert the single object into the context dict.""" context = {} if self.object: context['object'] = self.object context_object_name = self.get_context_object_name(self.object) if context_object_name: context[context_object_name] = self.object context.update(kwargs) return super().get_context_data(**context) ``` It's true that CBV has little bit learning curve, but when you see django source code and read about docs, it's easy to follow. +I highly recommend [ccbv.co.kr](https://ccbv.co.uk/) - you can see which view and mixin that CBV inherit, and it's methods too.
{% block content %} ### {{ object.title }} ``` <h6> on {{ object.datetime }}</h6> <div class = "code"> {{ object.content|linebreak }} </div> ``` {% endblock %}
22,156,030
i accessing google cloud storage by blobstore api, I would like to generate file names automatically instead of create it in the server. actually i want to do that, because it is hard to me to create a unique file name every time the user upload file. thank you
2014/03/03
[ "https://Stackoverflow.com/questions/22156030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3376321/" ]
If you are using Python you can simply use [UUID](http://en.wikipedia.org/wiki/Universally_unique_identifier) to generate your random filenames like this: ``` import uuid ... # with dashes filename = uuid.uuid4() # or without dashhes filename = uuid.uuid4().hex ```
You can generate an organised file name simply by just by using either computer name and Internet clock time, with a Smart-Phone you can use GPS day time year and map coordinates like in the case of geotagging. Everything is unique and readily available on computer or mobile rather than leaving a server to name the file.
61,100,105
I am attempting to only run an SQL `INSERT` query if the pageID (number) which is pulled through via an AJAX call, is more than what is already in the db. A user essentially clicks on a next button, which shows the correct page content, then calls an AJAX POST request, which fires an SQL statement. Any guidance on the if checking statement would be appreciated as I have hit a brick wall. **The Next button code:** ``` <a id="next" onclick="savePgID(1,2)">Next</a> ``` **AJAX call:** ``` function savePgID(moduleID, pageID){ $.ajax({ url: "pageAJAX.php", method: "POST", data: {moduleID:moduleID, pageID:pageID}, dataType: 'json', }); } ``` **pageAJAX:** ``` <?php session_start(); require 'scripts/db.php'; $studentID = $_SESSION['studentID']; if(isset($_POST['pageID'])) { $moduleID = $_POST['moduleID']; $pageID = $_POST['pageID']; if() { // Here is where I want to check whether using the moduleID and // pageID to check if the pageID in the db is less than the page // user is on. Only if the pageID user is currently on, is // greater than what they have in db, THEN run the below insert. } else { // INSERT Query into DB, this will update the pageID when user clicks next on module $stmt = $conn->prepare ("UPDATE `studentTakingModule` SET `pageID` = ? WHERE `studentTakingModule`.`studentID` = ? AND `studentTakingModule`.`moduleID` = ? "); $stmt->bind_param("iii", $pageID, $studentID, $moduleID); $stmt->execute(); $result = $stmt->get_result(); } } ?> ``` **NOTE** \*\*\* After an answer has been supplied, I have updated the code to the below, which now never fires the `INSERT` new pageID number into my DB, (even though the current pageID is more than the pageID number in the database): ``` <?php session_start(); require 'scripts/db.php'; $studentID = $_SESSION['studentID']; if(isset($_POST['pageID'])) { $pageID = $_POST['pageID']; $moduleID = $_POST['moduleID']; $stmt = $conn->prepare ("SELECT MAX(pageID) as `pageID`, `moduleID` FROM `studentTakingModule` WHERE `studentTakingModule`.`studentID` = ? AND `studentTakingModule`.`moduleID` = ? "); $stmt->bind_param("ii", $studentID, $moduleID); $stmt->execute(); $result = $stmt->get_result(); if(!empty($result)) { $dbPageID = $result[0]['pageID']; //$dbPageID2 = $row['pageID']; if($pageID > $dbPageID) { echo "You have reached the update statement"; // INSERT Query into DB, this will update the pageID when user clicks next on module $stmt = $conn->prepare ("UPDATE `studentTakingModule` SET `pageID` = ? WHERE `studentTakingModule`.`studentID` = ? AND `studentTakingModule`.`moduleID` = ? "); $stmt->bind_param("iii", $pageID, $studentID, $moduleID); $stmt->execute(); $result = $stmt->get_result(); } } } ?> ```
2020/04/08
[ "https://Stackoverflow.com/questions/61100105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11040508/" ]
you could try to wrap the `activeMQConnectionFactory` in a `CachingConnectionFactory` and utilize the `DefaultJmsListenerContainerFactoryConfigurer` to configure the `JmsListenerContainerFactory`: ``` @Bean ConnectionFactory connectionFactory() { return new CachingConnectionFactory(activeMQConnectionFactory()); } @Bean public JmsListenerContainerFactory<?> jmsListenerContainerFactory(ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer configurer) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; } ``` EDIT start: could you try changing the `JmsTemplate` to: ``` @Bean public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) { JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setConnectionFactory(connectionFactory); jmsTemplate.setPubSubDomain(true); return jmsTemplate; } ```
I solved this with the below Code: ``` public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(){ DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory = new DefaultJmsListenerContainerFactory(); defaultJmsListenerContainerFactory.setConnectionFactory(activeMQConnectionFactory()); defaultJmsListenerContainerFactory.setPubSubDomain(true); return defaultJmsListenerContainerFactory; } @Bean public JmsTemplate jmsTemplate() { JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setConnectionFactory(activeMQConnectionFactory()); jmsTemplate.setPubSubDomain(true); return jmsTemplate; } @JmsListener(destination = "${my.inboundTopicName}", containerFactory = "jmsListenerContainerFactory") public void myProcessor(final Message xmlMessage) { /// } ``` I want to add that I am experiencing some unusual behavior. 1. At the time when the messages are generated from the producer and if the consumer is up then only the messages are consumed by the consumer. I mean that if the messages are produced by the producer and enqueued by ActiveMQ and after some time I turn on the consumer then the messages are not consumed by the consumer. 2. . Also it takes a while before the messages are consumed by the consumer.
56,518,068
This is for a homework problem, so I tried to work through it as much as I could before coming here for help. I've got it 95% solved, I just can't figure out the syntax of the last bit or what method I should be using if it's different from what I'm doing now. I can't find any solution to this online that isn't actually my classmates' answers and I'm avoiding clicking on those to see how they completed the problem. I can return the string without formatting if it only has one element, with only the word 'and' when there are two elements, and I can add commas and the word 'and' when there are more than three elements. However, I can't seem to skip adding the last comma when the array has more than three elements. ``` def oxford_comma(array) if array.length == 2 array.join(" and ") elsif array.length > 2 array.insert(-2, "and") array[0..-1].join(", ") else array.join end end ``` Here's the error message I'm getting: ``` Failure/Error: expect(oxford_comma(["kiwi", "durian", "starfruit", "mangos", "dragon fruits"])).to eq("kiwi, durian, starfruit, mangos, and dragon fruits") expected: "kiwi, durian, starfruit, mangos, and dragon fruits" got: "kiwi, durian, starfruit, mangos, and, dragon fruits" (compared using ==) ```
2019/06/09
[ "https://Stackoverflow.com/questions/56518068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559334/" ]
When you have just one element in the array, [Array#join](https://ruby-doc.org/core-2.6.3/Array.html#method-i-join) returns the element itself: ``` ['a'].join(' and ') #=> "a" ``` So, you could simplify your code prepending `"and "` to the last element when list size is 3 or more or returning `.join(' and ')` if less than 3 elements: ``` def oxford_comma(list) return list.join(' and ') if list.size < 3 list[-1] = "and " + list[-1] list.join(', ') end ```
EDIT with max comments: You can do that: ``` def oxford_comma(array) array = [*array] case array.size when 0 '' when 1 array[0].to_s when 2 array.join(' and ') else array_copy = array array_copy[-1] = "and #{array_copy[-1]}" array_copy.join(', ') end end ``` The case when is to handle edge cases for empty array, single value array and double values array. Otherwise, you change the last item to add the `and` then join everything with comma. Use a copy of the array to be non destructive. [![enter image description here](https://i.stack.imgur.com/nkKUr.png)](https://i.stack.imgur.com/nkKUr.png)
56,518,068
This is for a homework problem, so I tried to work through it as much as I could before coming here for help. I've got it 95% solved, I just can't figure out the syntax of the last bit or what method I should be using if it's different from what I'm doing now. I can't find any solution to this online that isn't actually my classmates' answers and I'm avoiding clicking on those to see how they completed the problem. I can return the string without formatting if it only has one element, with only the word 'and' when there are two elements, and I can add commas and the word 'and' when there are more than three elements. However, I can't seem to skip adding the last comma when the array has more than three elements. ``` def oxford_comma(array) if array.length == 2 array.join(" and ") elsif array.length > 2 array.insert(-2, "and") array[0..-1].join(", ") else array.join end end ``` Here's the error message I'm getting: ``` Failure/Error: expect(oxford_comma(["kiwi", "durian", "starfruit", "mangos", "dragon fruits"])).to eq("kiwi, durian, starfruit, mangos, and dragon fruits") expected: "kiwi, durian, starfruit, mangos, and dragon fruits" got: "kiwi, durian, starfruit, mangos, and, dragon fruits" (compared using ==) ```
2019/06/09
[ "https://Stackoverflow.com/questions/56518068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559334/" ]
When you have just one element in the array, [Array#join](https://ruby-doc.org/core-2.6.3/Array.html#method-i-join) returns the element itself: ``` ['a'].join(' and ') #=> "a" ``` So, you could simplify your code prepending `"and "` to the last element when list size is 3 or more or returning `.join(' and ')` if less than 3 elements: ``` def oxford_comma(list) return list.join(' and ') if list.size < 3 list[-1] = "and " + list[-1] list.join(', ') end ```
For readability, I suggest a straightforward solution. ``` def oxford_comma(arr) case arr.size when 0 "" when 1 arr.first when 2 arr.join(' and ') else [arr[0..-2].join(', '), arr.last].join(', and ') end end ``` ``` oxford_comma ["blue", "green", "pink", "white"] #=> "blue, green, pink and white" oxford_comma ["blue", "green"] #=> "blue and green" oxford_comma ["blue"] #=> "blue" oxford_comma [] #=> "" ```
42,657,575
I have 3 images and each of them have a div after it. I am trying to adjust all the image's height to be the same as the height of the div after it. However, all the images are being given the height of the **first** div, not the one after it. I believe this is because when `$(".text").outerHeight()` is used, it always gets the height of the first `<div class="text">`. I have tried using this `.each` function to resolve this, but to no avail: ``` $('.container').each(function(i, obj) { $(".container").find('img').css("height", $(".text").outerHeight()); }); ``` Here is my full code without the `.each` function: ```js $(".container").find('img').css("height", $(".text").outerHeight()); ``` ```css div.container { border: 1px solid; margin-bottom: 30px; } img { float: left; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <img src="https://images-na.ssl-images-amazon.com/images/M/MV5BMzg2Mjg1OTk0NF5BMl5BanBnXkFtZTcwMjQ4MTA3Mw@@._V1_SX300.jpg" alt="RED" /> <div class="text"> <h2>Red</h2> <p>When his peaceful life is threatened by a high-tech assassin, .</p> </div> </div> <div class="container"> <img src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTAyNzQyNTcwNjVeQTJeQWpwZ15BbWU3MDAwOTQ4Nzk@._V1_SX300.jpg" alt="White House Down" /> <div class="text"> <h2>White House Down (2013)</h2> <p>While on a tour of the White House with his young daughter, a Capitol policeman springs into action to save his child and protect the president from a heavily armed group of paramilitary invaders.</p> </div> </div> <div class="container"> <img src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTAyNzQyNTcwNjVeQTJeQWpwZ15BbWU3MDAwOTQ4Nzk@._V1_SX300.jpg" alt="White House Down" /> <div class="text"> <h2>White House Down (2013)</h2> <p>While on a tour of the White House with his young daughter, a Capitol policeman springs into action to save his child and protect the president from a heavily armed group of paramilitary invaders.</p> </div> </div> ```
2017/03/07
[ "https://Stackoverflow.com/questions/42657575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5798798/" ]
I think you're on the right track. I would split on spaces to get all the words into an array. Then for-loop over the array and, where the index modulo 2 = 1 or 0 (depending on whether you want to alter even or odd words), use the char overload of replace .replace('x', 'y') to change your words. Then you just put the sentence back together
If you want to replace every "A" with "Z" in a word, you can use this line: ``` s.Replace("A", "Z"); ``` If you have an array of strings, you can just iterate over the array, and replace A's with Z's for every string: ``` string[] array = ... for (int i = 0; i < array.Length; i++) array[i] = array[i].Replace("A", "Z"); ``` Then, finally, if you only want to do this for every other string, just increase `i` by 2 each time, instead of 1: ``` string[] array = ... for (int i = 0; i < array.Length; i += 2) array[i] = array[i].Replace("A", "Z"); ```
2,492,674
Assume I have a set of weighted samples, where each samples has a corresponding weight between 0 and 1. I'd like to estimate the parameters of a gaussian mixture distribution that is biased towards the samples with higher weight. In the usual non-weighted case gaussian mixture estimation is done via the EM algorithm. Is there an implementation (any language is OK) that permits passing weights? If not, how can I modify the algorithm to account for the weights? If not, how to incorporate the weights in the initial formula of the maximum-log-likelihood formulation of the problem?
2010/03/22
[ "https://Stackoverflow.com/questions/2492674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292209/" ]
You can calculate a weighted log-Likelihood function; just multiply the every point with it's weight. Note that you need to use the log-Likelihood function for this. So your problem reduces to minimizing $-\ln L = \sum\_i w\_i \ln f(x\_i|q)$ (see [the Wikipedia article](http://en.wikipedia.org/wiki/Maximum_likelihood#Principles) for the original form).
Just a suggestion as no other answers are sent. You could use the normal EM with GMM (OpenCV for ex. has many wrappers for many languages) and put some points twice in the cluster you want to have "more weight". That way the EM would consider those points more important. You can remove the extra points later if it does matter. Otherwise I think this goes quite extreme mathematics unless you have strong background in advanced statistics.
2,492,674
Assume I have a set of weighted samples, where each samples has a corresponding weight between 0 and 1. I'd like to estimate the parameters of a gaussian mixture distribution that is biased towards the samples with higher weight. In the usual non-weighted case gaussian mixture estimation is done via the EM algorithm. Is there an implementation (any language is OK) that permits passing weights? If not, how can I modify the algorithm to account for the weights? If not, how to incorporate the weights in the initial formula of the maximum-log-likelihood formulation of the problem?
2010/03/22
[ "https://Stackoverflow.com/questions/2492674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292209/" ]
I've just had the same problem. Even though the post is older, it might be interesting to someone else. honk's answer is in principle correct, it's just not immediate to see how it affects the implementation of the algorithm. From the Wikipedia article for [Expectation Maximization](http://en.wikipedia.org/wiki/Expectation-maximization_algorithm) and a very nice [Tutorial](http://www.ee.washington.edu/techsite/papers/documents/UWEETR-2010-0002.pdf), the changes can be derived easily. If $v\_i$ is the weight of the i-th sample, the algorithm from the tutorial (see end of Section 6.2.) changes so that the $gamma\_{ij}$ is multiplied by that weighting factor. For the calculation of the new weights $w\_j$, $n\_j$ has to be divided by the sum of the weights $\sum\_{i=1}^{n} v\_i$ instead of just n. That's it...
Just a suggestion as no other answers are sent. You could use the normal EM with GMM (OpenCV for ex. has many wrappers for many languages) and put some points twice in the cluster you want to have "more weight". That way the EM would consider those points more important. You can remove the extra points later if it does matter. Otherwise I think this goes quite extreme mathematics unless you have strong background in advanced statistics.
2,492,674
Assume I have a set of weighted samples, where each samples has a corresponding weight between 0 and 1. I'd like to estimate the parameters of a gaussian mixture distribution that is biased towards the samples with higher weight. In the usual non-weighted case gaussian mixture estimation is done via the EM algorithm. Is there an implementation (any language is OK) that permits passing weights? If not, how can I modify the algorithm to account for the weights? If not, how to incorporate the weights in the initial formula of the maximum-log-likelihood formulation of the problem?
2010/03/22
[ "https://Stackoverflow.com/questions/2492674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292209/" ]
You can calculate a weighted log-Likelihood function; just multiply the every point with it's weight. Note that you need to use the log-Likelihood function for this. So your problem reduces to minimizing $-\ln L = \sum\_i w\_i \ln f(x\_i|q)$ (see [the Wikipedia article](http://en.wikipedia.org/wiki/Maximum_likelihood#Principles) for the original form).
I was looking for a similar solution related to gaussian kernel estimation (instead of a gaussian mixture) of the distribution. The standard [gaussian\_kde](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html#scipy.stats.gaussian_kde) does not allow that but I found a python implementation of a modified version here <http://mail.scipy.org/pipermail/scipy-user/2013-May/034580.html>
2,492,674
Assume I have a set of weighted samples, where each samples has a corresponding weight between 0 and 1. I'd like to estimate the parameters of a gaussian mixture distribution that is biased towards the samples with higher weight. In the usual non-weighted case gaussian mixture estimation is done via the EM algorithm. Is there an implementation (any language is OK) that permits passing weights? If not, how can I modify the algorithm to account for the weights? If not, how to incorporate the weights in the initial formula of the maximum-log-likelihood formulation of the problem?
2010/03/22
[ "https://Stackoverflow.com/questions/2492674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292209/" ]
You can calculate a weighted log-Likelihood function; just multiply the every point with it's weight. Note that you need to use the log-Likelihood function for this. So your problem reduces to minimizing $-\ln L = \sum\_i w\_i \ln f(x\_i|q)$ (see [the Wikipedia article](http://en.wikipedia.org/wiki/Maximum_likelihood#Principles) for the original form).
I think this analysis can be possibly be done via the `pomegranate` (see [Pomegranate](https://pomegranate.readthedocs.io/en/latest/) docs page) that supports a weighted Gaussian Mixture Modeling. According to their doc: > > weights : array-like, shape (n\_samples,), optional > The initial weights of each sample in the matrix. If nothing is > passed in then each sample is assumed to be the same weight. > Default is None. > > > Here is a Python snippet I wrote that can possibly help you do a weighted GMM: ```python from pomegranate import * import numpy as np # Generate some data N = 200 X_vals= np.random.normal(-17, 0.9, N).reshape(-1,1) # Needs to be in Nx1 shape X_weights = w_function(X_vals) # Needs to be in 1xN shape or alternatively just feed in the weight data you have pmg_model = GeneralMixtureModel.from_samples([NormalDistribution], 2, X_vals, weights=X_weights.T[0]) ``` [[Figure] Observed versus weighted distribution of the data we are analyzing](https://i.stack.imgur.com/xL87i.png) [[Figure] GMM of the weighted data](https://i.stack.imgur.com/2hMdf.png)
2,492,674
Assume I have a set of weighted samples, where each samples has a corresponding weight between 0 and 1. I'd like to estimate the parameters of a gaussian mixture distribution that is biased towards the samples with higher weight. In the usual non-weighted case gaussian mixture estimation is done via the EM algorithm. Is there an implementation (any language is OK) that permits passing weights? If not, how can I modify the algorithm to account for the weights? If not, how to incorporate the weights in the initial formula of the maximum-log-likelihood formulation of the problem?
2010/03/22
[ "https://Stackoverflow.com/questions/2492674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292209/" ]
I've just had the same problem. Even though the post is older, it might be interesting to someone else. honk's answer is in principle correct, it's just not immediate to see how it affects the implementation of the algorithm. From the Wikipedia article for [Expectation Maximization](http://en.wikipedia.org/wiki/Expectation-maximization_algorithm) and a very nice [Tutorial](http://www.ee.washington.edu/techsite/papers/documents/UWEETR-2010-0002.pdf), the changes can be derived easily. If $v\_i$ is the weight of the i-th sample, the algorithm from the tutorial (see end of Section 6.2.) changes so that the $gamma\_{ij}$ is multiplied by that weighting factor. For the calculation of the new weights $w\_j$, $n\_j$ has to be divided by the sum of the weights $\sum\_{i=1}^{n} v\_i$ instead of just n. That's it...
I was looking for a similar solution related to gaussian kernel estimation (instead of a gaussian mixture) of the distribution. The standard [gaussian\_kde](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html#scipy.stats.gaussian_kde) does not allow that but I found a python implementation of a modified version here <http://mail.scipy.org/pipermail/scipy-user/2013-May/034580.html>
2,492,674
Assume I have a set of weighted samples, where each samples has a corresponding weight between 0 and 1. I'd like to estimate the parameters of a gaussian mixture distribution that is biased towards the samples with higher weight. In the usual non-weighted case gaussian mixture estimation is done via the EM algorithm. Is there an implementation (any language is OK) that permits passing weights? If not, how can I modify the algorithm to account for the weights? If not, how to incorporate the weights in the initial formula of the maximum-log-likelihood formulation of the problem?
2010/03/22
[ "https://Stackoverflow.com/questions/2492674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292209/" ]
I've just had the same problem. Even though the post is older, it might be interesting to someone else. honk's answer is in principle correct, it's just not immediate to see how it affects the implementation of the algorithm. From the Wikipedia article for [Expectation Maximization](http://en.wikipedia.org/wiki/Expectation-maximization_algorithm) and a very nice [Tutorial](http://www.ee.washington.edu/techsite/papers/documents/UWEETR-2010-0002.pdf), the changes can be derived easily. If $v\_i$ is the weight of the i-th sample, the algorithm from the tutorial (see end of Section 6.2.) changes so that the $gamma\_{ij}$ is multiplied by that weighting factor. For the calculation of the new weights $w\_j$, $n\_j$ has to be divided by the sum of the weights $\sum\_{i=1}^{n} v\_i$ instead of just n. That's it...
I think this analysis can be possibly be done via the `pomegranate` (see [Pomegranate](https://pomegranate.readthedocs.io/en/latest/) docs page) that supports a weighted Gaussian Mixture Modeling. According to their doc: > > weights : array-like, shape (n\_samples,), optional > The initial weights of each sample in the matrix. If nothing is > passed in then each sample is assumed to be the same weight. > Default is None. > > > Here is a Python snippet I wrote that can possibly help you do a weighted GMM: ```python from pomegranate import * import numpy as np # Generate some data N = 200 X_vals= np.random.normal(-17, 0.9, N).reshape(-1,1) # Needs to be in Nx1 shape X_weights = w_function(X_vals) # Needs to be in 1xN shape or alternatively just feed in the weight data you have pmg_model = GeneralMixtureModel.from_samples([NormalDistribution], 2, X_vals, weights=X_weights.T[0]) ``` [[Figure] Observed versus weighted distribution of the data we are analyzing](https://i.stack.imgur.com/xL87i.png) [[Figure] GMM of the weighted data](https://i.stack.imgur.com/2hMdf.png)
19,330,441
I have an array that I am looping through and pushing specific values to a separate array. EX: ``` first_array = ["Promoter: 8", "Passive: 7"] ``` I want to push every value that is an integer to a separate array, that would look like this in the end: ``` final_array = [8,7] ``` It would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?
2013/10/12
[ "https://Stackoverflow.com/questions/19330441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665588/" ]
``` first_array.map{|a| a.match(/\d+/)}.compact.map{|a| a[0].to_i } ``` * Use a regex to grab the integers, * compact the blank spaces from the strings with no integers, and * convert them all to ints
If the integer part of each string in (which look like members of a hash) is always preceded by at least one space, and there is no other whitespace (other than possibly at the beginning of the string), you could do this: ``` first_array = ["Promoter: 8", "Passive: 7"] Hash[*first_array.map(&:split).flatten].values.map(&:to_i) # => [8,7] ``` * map first\_array => [["Promoter:", "8"], ["Passive:", "7"]] * flatten => ["Promoter:", "8", "Passive:", "7"] * convert to hash => {"Promoter:" => "8", "Passive:" => "7"} * get hash values => ["8", "7"] * convert to ints => [8, 7] Note the need for the splat: ``` Hash[*["Promoter:", "8", "Passive:", "7"]] => Hash["Promoter:", "8", "Passive:", "7"] => {"Promoter:" => "8", "Passive:" => "7"} ```
19,330,441
I have an array that I am looping through and pushing specific values to a separate array. EX: ``` first_array = ["Promoter: 8", "Passive: 7"] ``` I want to push every value that is an integer to a separate array, that would look like this in the end: ``` final_array = [8,7] ``` It would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?
2013/10/12
[ "https://Stackoverflow.com/questions/19330441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665588/" ]
``` first_array.map{|a| a.match(/\d+/)}.compact.map{|a| a[0].to_i } ``` * Use a regex to grab the integers, * compact the blank spaces from the strings with no integers, and * convert them all to ints
And I have to add this super short but complicated one-liner solution: ``` a = ["Promoter: 8", "Passive: 7"] p a.grep(/(\d+)/){$&.to_i} #=> [8,7] ```
19,330,441
I have an array that I am looping through and pushing specific values to a separate array. EX: ``` first_array = ["Promoter: 8", "Passive: 7"] ``` I want to push every value that is an integer to a separate array, that would look like this in the end: ``` final_array = [8,7] ``` It would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?
2013/10/12
[ "https://Stackoverflow.com/questions/19330441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665588/" ]
``` first_array.map{|a| a.match(/\d+/)}.compact.map{|a| a[0].to_i } ``` * Use a regex to grab the integers, * compact the blank spaces from the strings with no integers, and * convert them all to ints
Your question, as formulated, has an easy practical answer, already provided by others. But it seems to me, that your array of strings ``` a = ["Promoter: 8", "Passive: 7"] ``` envies being a `Hash`. So, from broader perspective, I would take freedom of converting it to a Hash first: ``` require 'pyper' # (type "gem install pyper" in your command line to install it) hsh = Hash[ a.τBmm2dτ &/(\w+): *(\d+)/.method( :match ) ] #=> {"Promoter"=>"8", "Passive"=>"7"} # (The construction of #τBmm2dτ Pyper method will be explained in the appendix.) ``` Now, having your input data in a hash, you can do things with them more easily, eg. ``` hsh.τmbtiτ #=> [8, 7] ``` --- **APPENDIX: Explanation of the Pyper methods.** Pyper methods are similar to Lisp #car/#cdr methods in that, that a combination of letters controls the method behavior. In the first method, `#τBmm2dτ`: * τ - opening and ending character * m - means #map * B - means take a block * 2 - means first 3 elements of an array * d - means all elements except the first one (same meaning as in #cdr, btw.) So, in `#τBmm2dτ`, `Bm` applies the block as follows: ``` x = ["Promoter: 8", "Passive: 7"].map &/(\w+): *(\d+)/.method( :match ) #=> [#<MatchData "Promoter: 8" 1:"Promoter" 2:"8">, #<MatchData "Passive: 7" 1:"Passive" 2:"7">] # Which results in an array of 2 MatchData objects. ``` Then, `m2d` chars map (`m`) the MatchData objects using `2` and `d` chars. Character `2` gives ``` x = x.map { |e| e.to_a.take 3 } #=> [["Promoter: 8", "Promoter", "8"], ["Passive: 7", "Passive", "7"]] ``` and `d` removes the first element from each: ``` x = x.map { |e| e.drop 1 } #=> [["Promoter", "8"], ["Passive", "7"]] ``` In the secon method, `#τmbtiτ`, `m` means again `#map`, `b` means take the second element, and `ti` means convert it to `Integer`: ``` {"Promoter"=>"8", "Passive"=>"7"}.to_a.map { |e| Integer e[1] } #=> [8, 7] ```
19,330,441
I have an array that I am looping through and pushing specific values to a separate array. EX: ``` first_array = ["Promoter: 8", "Passive: 7"] ``` I want to push every value that is an integer to a separate array, that would look like this in the end: ``` final_array = [8,7] ``` It would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?
2013/10/12
[ "https://Stackoverflow.com/questions/19330441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665588/" ]
``` first_array.map{|s| s[/\d+/].to_i} # => [8, 7] ```
If the integer part of each string in (which look like members of a hash) is always preceded by at least one space, and there is no other whitespace (other than possibly at the beginning of the string), you could do this: ``` first_array = ["Promoter: 8", "Passive: 7"] Hash[*first_array.map(&:split).flatten].values.map(&:to_i) # => [8,7] ``` * map first\_array => [["Promoter:", "8"], ["Passive:", "7"]] * flatten => ["Promoter:", "8", "Passive:", "7"] * convert to hash => {"Promoter:" => "8", "Passive:" => "7"} * get hash values => ["8", "7"] * convert to ints => [8, 7] Note the need for the splat: ``` Hash[*["Promoter:", "8", "Passive:", "7"]] => Hash["Promoter:", "8", "Passive:", "7"] => {"Promoter:" => "8", "Passive:" => "7"} ```
19,330,441
I have an array that I am looping through and pushing specific values to a separate array. EX: ``` first_array = ["Promoter: 8", "Passive: 7"] ``` I want to push every value that is an integer to a separate array, that would look like this in the end: ``` final_array = [8,7] ``` It would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?
2013/10/12
[ "https://Stackoverflow.com/questions/19330441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665588/" ]
``` first_array.map{|s| s[/\d+/].to_i} # => [8, 7] ```
And I have to add this super short but complicated one-liner solution: ``` a = ["Promoter: 8", "Passive: 7"] p a.grep(/(\d+)/){$&.to_i} #=> [8,7] ```
19,330,441
I have an array that I am looping through and pushing specific values to a separate array. EX: ``` first_array = ["Promoter: 8", "Passive: 7"] ``` I want to push every value that is an integer to a separate array, that would look like this in the end: ``` final_array = [8,7] ``` It would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?
2013/10/12
[ "https://Stackoverflow.com/questions/19330441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665588/" ]
``` first_array.map{|s| s[/\d+/].to_i} # => [8, 7] ```
Your question, as formulated, has an easy practical answer, already provided by others. But it seems to me, that your array of strings ``` a = ["Promoter: 8", "Passive: 7"] ``` envies being a `Hash`. So, from broader perspective, I would take freedom of converting it to a Hash first: ``` require 'pyper' # (type "gem install pyper" in your command line to install it) hsh = Hash[ a.τBmm2dτ &/(\w+): *(\d+)/.method( :match ) ] #=> {"Promoter"=>"8", "Passive"=>"7"} # (The construction of #τBmm2dτ Pyper method will be explained in the appendix.) ``` Now, having your input data in a hash, you can do things with them more easily, eg. ``` hsh.τmbtiτ #=> [8, 7] ``` --- **APPENDIX: Explanation of the Pyper methods.** Pyper methods are similar to Lisp #car/#cdr methods in that, that a combination of letters controls the method behavior. In the first method, `#τBmm2dτ`: * τ - opening and ending character * m - means #map * B - means take a block * 2 - means first 3 elements of an array * d - means all elements except the first one (same meaning as in #cdr, btw.) So, in `#τBmm2dτ`, `Bm` applies the block as follows: ``` x = ["Promoter: 8", "Passive: 7"].map &/(\w+): *(\d+)/.method( :match ) #=> [#<MatchData "Promoter: 8" 1:"Promoter" 2:"8">, #<MatchData "Passive: 7" 1:"Passive" 2:"7">] # Which results in an array of 2 MatchData objects. ``` Then, `m2d` chars map (`m`) the MatchData objects using `2` and `d` chars. Character `2` gives ``` x = x.map { |e| e.to_a.take 3 } #=> [["Promoter: 8", "Promoter", "8"], ["Passive: 7", "Passive", "7"]] ``` and `d` removes the first element from each: ``` x = x.map { |e| e.drop 1 } #=> [["Promoter", "8"], ["Passive", "7"]] ``` In the secon method, `#τmbtiτ`, `m` means again `#map`, `b` means take the second element, and `ti` means convert it to `Integer`: ``` {"Promoter"=>"8", "Passive"=>"7"}.to_a.map { |e| Integer e[1] } #=> [8, 7] ```
19,330,441
I have an array that I am looping through and pushing specific values to a separate array. EX: ``` first_array = ["Promoter: 8", "Passive: 7"] ``` I want to push every value that is an integer to a separate array, that would look like this in the end: ``` final_array = [8,7] ``` It would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?
2013/10/12
[ "https://Stackoverflow.com/questions/19330441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665588/" ]
And I have to add this super short but complicated one-liner solution: ``` a = ["Promoter: 8", "Passive: 7"] p a.grep(/(\d+)/){$&.to_i} #=> [8,7] ```
If the integer part of each string in (which look like members of a hash) is always preceded by at least one space, and there is no other whitespace (other than possibly at the beginning of the string), you could do this: ``` first_array = ["Promoter: 8", "Passive: 7"] Hash[*first_array.map(&:split).flatten].values.map(&:to_i) # => [8,7] ``` * map first\_array => [["Promoter:", "8"], ["Passive:", "7"]] * flatten => ["Promoter:", "8", "Passive:", "7"] * convert to hash => {"Promoter:" => "8", "Passive:" => "7"} * get hash values => ["8", "7"] * convert to ints => [8, 7] Note the need for the splat: ``` Hash[*["Promoter:", "8", "Passive:", "7"]] => Hash["Promoter:", "8", "Passive:", "7"] => {"Promoter:" => "8", "Passive:" => "7"} ```
19,330,441
I have an array that I am looping through and pushing specific values to a separate array. EX: ``` first_array = ["Promoter: 8", "Passive: 7"] ``` I want to push every value that is an integer to a separate array, that would look like this in the end: ``` final_array = [8,7] ``` It would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?
2013/10/12
[ "https://Stackoverflow.com/questions/19330441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665588/" ]
Your question, as formulated, has an easy practical answer, already provided by others. But it seems to me, that your array of strings ``` a = ["Promoter: 8", "Passive: 7"] ``` envies being a `Hash`. So, from broader perspective, I would take freedom of converting it to a Hash first: ``` require 'pyper' # (type "gem install pyper" in your command line to install it) hsh = Hash[ a.τBmm2dτ &/(\w+): *(\d+)/.method( :match ) ] #=> {"Promoter"=>"8", "Passive"=>"7"} # (The construction of #τBmm2dτ Pyper method will be explained in the appendix.) ``` Now, having your input data in a hash, you can do things with them more easily, eg. ``` hsh.τmbtiτ #=> [8, 7] ``` --- **APPENDIX: Explanation of the Pyper methods.** Pyper methods are similar to Lisp #car/#cdr methods in that, that a combination of letters controls the method behavior. In the first method, `#τBmm2dτ`: * τ - opening and ending character * m - means #map * B - means take a block * 2 - means first 3 elements of an array * d - means all elements except the first one (same meaning as in #cdr, btw.) So, in `#τBmm2dτ`, `Bm` applies the block as follows: ``` x = ["Promoter: 8", "Passive: 7"].map &/(\w+): *(\d+)/.method( :match ) #=> [#<MatchData "Promoter: 8" 1:"Promoter" 2:"8">, #<MatchData "Passive: 7" 1:"Passive" 2:"7">] # Which results in an array of 2 MatchData objects. ``` Then, `m2d` chars map (`m`) the MatchData objects using `2` and `d` chars. Character `2` gives ``` x = x.map { |e| e.to_a.take 3 } #=> [["Promoter: 8", "Promoter", "8"], ["Passive: 7", "Passive", "7"]] ``` and `d` removes the first element from each: ``` x = x.map { |e| e.drop 1 } #=> [["Promoter", "8"], ["Passive", "7"]] ``` In the secon method, `#τmbtiτ`, `m` means again `#map`, `b` means take the second element, and `ti` means convert it to `Integer`: ``` {"Promoter"=>"8", "Passive"=>"7"}.to_a.map { |e| Integer e[1] } #=> [8, 7] ```
If the integer part of each string in (which look like members of a hash) is always preceded by at least one space, and there is no other whitespace (other than possibly at the beginning of the string), you could do this: ``` first_array = ["Promoter: 8", "Passive: 7"] Hash[*first_array.map(&:split).flatten].values.map(&:to_i) # => [8,7] ``` * map first\_array => [["Promoter:", "8"], ["Passive:", "7"]] * flatten => ["Promoter:", "8", "Passive:", "7"] * convert to hash => {"Promoter:" => "8", "Passive:" => "7"} * get hash values => ["8", "7"] * convert to ints => [8, 7] Note the need for the splat: ``` Hash[*["Promoter:", "8", "Passive:", "7"]] => Hash["Promoter:", "8", "Passive:", "7"] => {"Promoter:" => "8", "Passive:" => "7"} ```
21,935,187
I receive date as string from web service in following format `2014-02-27T11:17:00.000Z` Could someone tell me how to parse it as Date time object in Java. I tried parsing it `Date.parse()` but it didn't work properly. Then I tried date formatter but it crashes the app. Could someone enlighten me please.
2014/02/21
[ "https://Stackoverflow.com/questions/21935187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3296042/" ]
``` SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Date d = sdf.parse("2014-02-27T11:17:00.000Z"); ```
You can use dateformat class for that. ``` DateFormat sdt = new SimpleDateFormat(put your format here); Date stime= sdt.parse(starttime); Date etime = sdt.parse(endtime); ``` Starttime and end time are the strings which you want to parse
21,935,187
I receive date as string from web service in following format `2014-02-27T11:17:00.000Z` Could someone tell me how to parse it as Date time object in Java. I tried parsing it `Date.parse()` but it didn't work properly. Then I tried date formatter but it crashes the app. Could someone enlighten me please.
2014/02/21
[ "https://Stackoverflow.com/questions/21935187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3296042/" ]
``` SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Date d = sdf.parse("2014-02-27T11:17:00.000Z"); ```
Declare a SimpleDateTimeFormat to match your datetime from C# and then use .parse() method on it to get the (Java) Date. Example: ``` private static final SimpleDateFormat FORMAT_FULL_DATE = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'.000Z'"); // replace kk with hh for am/pm format public static Date getDateTimeFromString(final String string) { try { return FORMAT_FULL_DATE.parse(string); } catch (ParseException e) { e.printStackTrace(); return null; } } ```
47,997,549
The data in my table looks like this: ``` date, app, country, sales 2017-01-01,XYZ,US,10000 2017-01-01,XYZ,GB,2000 2017-01-02,XYZ,US,30000 2017-01-02,XYZ,GB,1000 ``` I need to find, for each app on a daily basis, the ratio of US sales to GB sales, so ideally the result would look like this: ``` date, app, ratio 2017-01-01,XYZ,10000/2000 = 5 2017-01-02,XYZ,30000/1000 = 30 ``` I'm currently dumping everything into a csv and doing my calculations offline in Python but I wanted to move everything onto the SQL side. One option would be to aggregate each country into a subquery, join and then divide, such as ``` select d1_us.date, d1_us.app, d1_us.sales / d1_gb.sales from (select date, app, sales from table where date between '2017-01-01' and '2017-01-10' and country = 'US') as d1_us join (select date, app, sales from table where date between '2017-01-01' and '2017-01-10' and country = 'GB') as d1_gb on d1_us.app = d1_gb.app and d1_us.date = d1_gb.date ``` Is there a less messy way to go about doing this?
2017/12/27
[ "https://Stackoverflow.com/questions/47997549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722950/" ]
You can use the ratio of SUM(CASE WHEN) and GROUP BY in your query to do this without requiring a subquery. ``` SELECT DATE, APP, SUM(CASE WHEN COUNTRY = 'US' THEN SALES ELSE 0 END) / SUM(CASE WHEN COUNTRY = 'GB' THEN SALES END) AS RATIO FROM TABLE1 GROUP BY DATE, APP; ``` Based on the likelihood of the GB sales being zero, you can tweak the GB's ELSE condition, maybe `ELSE 1`, to avoid Divide by zero error. It really depends on how you want to handle exceptions.
You can use one query with grouping and provide the condition once: ``` SELECT date, app, SUM(CASE WHEN country = 'US' THEN SALES ELSE 0 END) / SUM(CASE WHEN country = 'GB' THEN SALES END) AS ratio WHERE date between '2017-01-01' AND '2017-01-10' FROM your_table GROUP BY date, app; ``` However, this gives you zero if there are no records for US and `NULL` if there are no records for GB. If you need to return different values for those cases, you can use another `CASE WHEN` surrounding the division. For example, to return -1 and -2 respectively, you can use: ``` SELECT date, app, CASE WHEN COUNT(CASE WHEN country = 'US' THEN 1 ELSE 0 END) = 0 THEN -1 WHEN COUNT(CASE WHEN country = 'GB' THEN 1 ELSE 0 END) = 0 THEN -2 ELSE SUM(CASE WHEN country = 'US' THEN SALES ELSE 0 END) / SUM(CASE WHEN country = 'GB' THEN SALES END) END AS ratio WHERE date between '2017-01-01' AND '2017-01-10' FROM your_table GROUP BY date, app; ```
47,997,549
The data in my table looks like this: ``` date, app, country, sales 2017-01-01,XYZ,US,10000 2017-01-01,XYZ,GB,2000 2017-01-02,XYZ,US,30000 2017-01-02,XYZ,GB,1000 ``` I need to find, for each app on a daily basis, the ratio of US sales to GB sales, so ideally the result would look like this: ``` date, app, ratio 2017-01-01,XYZ,10000/2000 = 5 2017-01-02,XYZ,30000/1000 = 30 ``` I'm currently dumping everything into a csv and doing my calculations offline in Python but I wanted to move everything onto the SQL side. One option would be to aggregate each country into a subquery, join and then divide, such as ``` select d1_us.date, d1_us.app, d1_us.sales / d1_gb.sales from (select date, app, sales from table where date between '2017-01-01' and '2017-01-10' and country = 'US') as d1_us join (select date, app, sales from table where date between '2017-01-01' and '2017-01-10' and country = 'GB') as d1_gb on d1_us.app = d1_gb.app and d1_us.date = d1_gb.date ``` Is there a less messy way to go about doing this?
2017/12/27
[ "https://Stackoverflow.com/questions/47997549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722950/" ]
You can use the ratio of SUM(CASE WHEN) and GROUP BY in your query to do this without requiring a subquery. ``` SELECT DATE, APP, SUM(CASE WHEN COUNTRY = 'US' THEN SALES ELSE 0 END) / SUM(CASE WHEN COUNTRY = 'GB' THEN SALES END) AS RATIO FROM TABLE1 GROUP BY DATE, APP; ``` Based on the likelihood of the GB sales being zero, you can tweak the GB's ELSE condition, maybe `ELSE 1`, to avoid Divide by zero error. It really depends on how you want to handle exceptions.
``` DROP TABLE IF EXISTS t; CREATE TABLE t ( date DATE, app VARCHAR(5), country VARCHAR(5), sales DECIMAL(10,2) ); INSERT INTO t VALUES ('2017-01-01','XYZ','US',10000), ('2017-01-01','XYZ','GB',2000), ('2017-01-02','XYZ','US',30000), ('2017-01-02','XYZ','GB',1000); WITH q AS ( SELECT date, app, country, SUM(sales) AS sales FROM t GROUP BY date, app, country ) SELECT q1.date, q1.app, q1.country || ' vs ' || NVL(q2.country,'-') AS ratio_between, CASE WHEN q2.sales IS NULL OR q2.sales = 0 THEN 0 ELSE ROUND(q1.sales / q2.sales, 2) END AS ratio FROM q AS q1 LEFT JOIN q AS q2 ON q2.date = q1.date AND q2.app = q1.app AND q2.country != q1.country -- WHERE q1.country = 'US' ORDER BY q1.date; ``` **Results for any country vs any country (WHERE q1.country='US' is commented out)** ``` date,app,ratio_between,ratio 2017-01-01,XYZ,GB vs US,0.20 2017-01-01,XYZ,US vs GB,5.00 2017-01-02,XYZ,GB vs US,0.03 2017-01-02,XYZ,US vs GB,30.00 ``` **Results for US vs any other country (WHERE q1.country='US' uncommented)** ``` date,app,ratio_between,ratio 2017-01-01,XYZ,US vs GB,5.00 2017-01-02,XYZ,US vs GB,30.00 ``` The trick is in JOIN clause. Results of a subquery q which aggregates data by date, app and country are joined with results themselves but on date and app. This way, for every date, app and country we get a "match" with any another country on same date and app. By adding q1.country != q2.country, we exclude results for same country, highlighted below with \* ``` date,app,country,sales,date,app,country,sales *2017-01-01,XYZ,GB,2000.00,2017-01-01,XYZ,GB,2000.00* 2017-01-01,XYZ,GB,2000.00,2017-01-01,XYZ,US,10000.00 2017-01-01,XYZ,US,10000.00,2017-01-01,XYZ,GB,2000.00 *2017-01-01,XYZ,US,10000.00,2017-01-01,XYZ,US,10000.00* 2017-01-02,XYZ,GB,1000.00,2017-01-02,XYZ,US,30000.00 *2017-01-02,XYZ,GB,1000.00,2017-01-02,XYZ,GB,1000.00* *2017-01-02,XYZ,US,30000.00,2017-01-02,XYZ,US,30000.00* 2017-01-02,XYZ,US,30000.00,2017-01-02,XYZ,GB,1000.00 ```
41,506
There is a blind test that asks participants to distinguish Coke and Pepsi. A participant will test 6 cups of drink and tell whether it was Coke or Pepsi. Assuming that the participant can tell the difference between them, though not perfect, if he judged that the first three were all Coke, then he would think it is much more likely that the remaining three would be Pepsi rather than Coke. Then the last three experiments cannot give precise information about the participant's ability to distinguish. Such a problem can happen when the participant knows a priori that there would be equal numbers of Coke and Pepsi. Then the experimenter might think of flipping a coin six times to decide which cola is given to the participant. Then it is possible that all or most of 6 cups are Cokes. It may be problematic when the participant is good at telling Coke a Coke but not as good at telling Pepsi a Pepsi. Is there any methods to solve this problem?
2012/10/30
[ "https://stats.stackexchange.com/questions/41506", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/15997/" ]
I do think it is a study design problem and a famous one in that some think RA Fisher did not actually realize it in making his famous Lady tasting cups of tea example and one that haunts clinical trials who try to prevent any unblinding of treatment assignment in clinical trials. A solution suggested from what is done there (choosing block size randomly) is to first randomly choose the ratio of coke to pepsi and then chose the order. Do make the choice of all coke or all pepsi very very low but not zero and then try to get "there is a chance that all will be coke or pepsi” into the informed consent.
You could (truthfully) tell the participants that you will flip a coin each time you provide a soda and that the coin flip will determine P vs C. You can go on to explain to them, "If the last five were Coke (or Pepsi), Coke and Pepsi are equally likely on the next test." One problem is that some of your participants won't believe the explanation and will remain convinced that five heads in a row makes tails more likely on the next flip. But you might want to carefully simulate how you will analyze the data once you get it because randomly scrambling three and three is not the same experiment as flipping a coin on each soda.
6,493,630
I'm binding an ObservableCollection to a control which has a converter to change its visibility depending on if the collection has any values or not: Simplified example: **XAML:** ``` <Window.Resources> <local:MyConverter x:Key="converter"/> </Window.Resources> <Grid x:Name="grid"> <Rectangle Height="100" Width="200" Fill="CornflowerBlue" Visibility="{Binding Converter={StaticResource converter}}"/> <Button Content="click" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click"/> </Grid> ``` **C#:** ``` ObservableCollection<string> strings; public MainWindow() { InitializeComponent(); strings = new ObservableCollection<string>(); grid.DataContext = strings; } private void Button_Click(object sender, RoutedEventArgs e) { strings.Add("new value"); } ``` When the collection is bound, the Rectangle is visible when there are values and not when the collection is empty. However, if the collection is empty and I add a value at runtime, the Rectangle does not appear (the converter's Convert method isn't even fired). Am I missing something or just trying to ask too much of IValueConverter?
2011/06/27
[ "https://Stackoverflow.com/questions/6493630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128837/" ]
OK, so here's how I got around the problem using a `MultiValueConverter` The converter now looks like: ``` public object Convert( object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { ObservableCollection<string> strings = values[0] as ObservableCollection<string>; if (strings == null || !strings.Any()) return Visibility.Collapsed; else return Visibility.Visible; } public object[] ConvertBack( object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } ``` And the XAML now looks like: ``` <Rectangle Height="100" Width="200" Fill="CornflowerBlue"> <Rectangle.Visibility> <MultiBinding Converter="{StaticResource converter}"> <Binding Path="."/> <Binding Path="Count"/> </MultiBinding> </Rectangle.Visibility> </Rectangle> ``` The C# remains the same :)
You must set the DataContext after creating the collection; it is probable that you initialize the "strings"collection to "null", you set the DataContext in the constructor to that value(e.g. null), then you actually create the collection--this way, the DataContext remains null. You must set the DataContext again after creating the collection.
6,493,630
I'm binding an ObservableCollection to a control which has a converter to change its visibility depending on if the collection has any values or not: Simplified example: **XAML:** ``` <Window.Resources> <local:MyConverter x:Key="converter"/> </Window.Resources> <Grid x:Name="grid"> <Rectangle Height="100" Width="200" Fill="CornflowerBlue" Visibility="{Binding Converter={StaticResource converter}}"/> <Button Content="click" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click"/> </Grid> ``` **C#:** ``` ObservableCollection<string> strings; public MainWindow() { InitializeComponent(); strings = new ObservableCollection<string>(); grid.DataContext = strings; } private void Button_Click(object sender, RoutedEventArgs e) { strings.Add("new value"); } ``` When the collection is bound, the Rectangle is visible when there are values and not when the collection is empty. However, if the collection is empty and I add a value at runtime, the Rectangle does not appear (the converter's Convert method isn't even fired). Am I missing something or just trying to ask too much of IValueConverter?
2011/06/27
[ "https://Stackoverflow.com/questions/6493630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128837/" ]
I think the converter in a Binding is always called if the Binding source has been updated and notifies about that update (as a DependencyProperty or using INotifyPropertyChanged). However, an ObservableCollection does not raise the PropertyChanged event if an item has been added or removed, but it raises the CollectionChanged event. It does not raise any event at all if an item in the collection is changed. Even if the item itself raises PropertyChanged, this will not update the Binding on the collection since the Binding source is not the item, but the collection. I fear your approach will not work this way. You could bind directly to ObservableCollection.Count and add an appropriate math converter to it to perform the inversion and multiplication, but the Count property does not perform change notification, so this no option. I think you will have to provide another property in your ViewModel or code-behind which handles these cases... best regards,
You must set the DataContext after creating the collection; it is probable that you initialize the "strings"collection to "null", you set the DataContext in the constructor to that value(e.g. null), then you actually create the collection--this way, the DataContext remains null. You must set the DataContext again after creating the collection.
6,493,630
I'm binding an ObservableCollection to a control which has a converter to change its visibility depending on if the collection has any values or not: Simplified example: **XAML:** ``` <Window.Resources> <local:MyConverter x:Key="converter"/> </Window.Resources> <Grid x:Name="grid"> <Rectangle Height="100" Width="200" Fill="CornflowerBlue" Visibility="{Binding Converter={StaticResource converter}}"/> <Button Content="click" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click"/> </Grid> ``` **C#:** ``` ObservableCollection<string> strings; public MainWindow() { InitializeComponent(); strings = new ObservableCollection<string>(); grid.DataContext = strings; } private void Button_Click(object sender, RoutedEventArgs e) { strings.Add("new value"); } ``` When the collection is bound, the Rectangle is visible when there are values and not when the collection is empty. However, if the collection is empty and I add a value at runtime, the Rectangle does not appear (the converter's Convert method isn't even fired). Am I missing something or just trying to ask too much of IValueConverter?
2011/06/27
[ "https://Stackoverflow.com/questions/6493630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/128837/" ]
OK, so here's how I got around the problem using a `MultiValueConverter` The converter now looks like: ``` public object Convert( object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { ObservableCollection<string> strings = values[0] as ObservableCollection<string>; if (strings == null || !strings.Any()) return Visibility.Collapsed; else return Visibility.Visible; } public object[] ConvertBack( object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } ``` And the XAML now looks like: ``` <Rectangle Height="100" Width="200" Fill="CornflowerBlue"> <Rectangle.Visibility> <MultiBinding Converter="{StaticResource converter}"> <Binding Path="."/> <Binding Path="Count"/> </MultiBinding> </Rectangle.Visibility> </Rectangle> ``` The C# remains the same :)
I think the converter in a Binding is always called if the Binding source has been updated and notifies about that update (as a DependencyProperty or using INotifyPropertyChanged). However, an ObservableCollection does not raise the PropertyChanged event if an item has been added or removed, but it raises the CollectionChanged event. It does not raise any event at all if an item in the collection is changed. Even if the item itself raises PropertyChanged, this will not update the Binding on the collection since the Binding source is not the item, but the collection. I fear your approach will not work this way. You could bind directly to ObservableCollection.Count and add an appropriate math converter to it to perform the inversion and multiplication, but the Count property does not perform change notification, so this no option. I think you will have to provide another property in your ViewModel or code-behind which handles these cases... best regards,
787,449
I have a modem+wireless router that my ISP gave that I use to connect to the internet as well as connect my IP TV box. I just bought a Time Capsule and I want to use it as the wireless access point. Unfortunately I am having difficulty getting the TC to connect to the internet. I have already turned off the wireless on the ISP router but I am afraid if I mess with any DHCP settings I might lose access to my TV set top box; ditto with bridge mode. However I am open to any suggestion. Isnt there a way for the TC to connect to the internet over my existing router and use a different IP range to allow wireless devices to connect to it?
2014/07/24
[ "https://superuser.com/questions/787449", "https://superuser.com", "https://superuser.com/users/59789/" ]
Well, as it turns out there IS a way to do this. Connect the TC to the ISP's router using an ethernet cable. This will cause the ISP's router to allocate an IP address for it. Go into your ISP router's settings and find the place where you can reserve an IP. It will probably ask you for the IP and MAC address. You can find these details on the page where the router shows all connected devices. Next, open the DHCP settings page on the ISP's router and reduce the allocated range. For eg: if the range allocated was from 192.168.1.1 to 192.168.1.253 change the ending address to 192.168.1.150. This is just an example, you can change the end address to anything you want. After you have done this, go to your TC's internet settings and change the address allocation setting to Static; by default it would have been set to DHCP + NAT. Enter the IP address you reserved in the previous step, here. In all possibility it would already have be filled in. Next, go to the DHCP page of the TC and change the allocation range to 192.168.1.151 - 192.168.1.250. We are allocating the remaining range to the TC so that it can hand it out to any connected clients. Restart the ISP's router. Once that is up, restart the TC.
Put the time capsule in bridge mode: <https://discussions.apple.com/message/23393821> that turns off the 2nd router and let's your ISPs device perform router functions.
11,229,627
I have two divs: ``` <div class="dialog large"></div> ``` and ``` <div class="dialog"></div> ``` I have to remove the one with the class "dialog" but keep the one with "dialog large". If I do `$('dialog').remove();` they are both removed. Can anyone help me with this?
2012/06/27
[ "https://Stackoverflow.com/questions/11229627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310276/" ]
``` $('div.dialog:not(.large)').remove(); ``` **[DEMO](http://jsfiddle.net/QStkd/512/)** ### A little explain `div.dialog` will select `div` with `class=dialog` (in this case both div will select). But `div.dialog:not(.large)` will exclude those `div` with `class` `large` and remove them. ### Related Refs * **[:not()](http://api.jquery.com/not-selector/)** * **[class selector](http://api.jquery.com/class-selector/)**
Use this: ``` $("div.dialog").not('.large').remove(); ``` [Fiddle](http://jsfiddle.net/v74V4/1/) here...
11,229,627
I have two divs: ``` <div class="dialog large"></div> ``` and ``` <div class="dialog"></div> ``` I have to remove the one with the class "dialog" but keep the one with "dialog large". If I do `$('dialog').remove();` they are both removed. Can anyone help me with this?
2012/06/27
[ "https://Stackoverflow.com/questions/11229627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310276/" ]
``` $('div.dialog:not(.large)').remove(); ``` **[DEMO](http://jsfiddle.net/QStkd/512/)** ### A little explain `div.dialog` will select `div` with `class=dialog` (in this case both div will select). But `div.dialog:not(.large)` will exclude those `div` with `class` `large` and remove them. ### Related Refs * **[:not()](http://api.jquery.com/not-selector/)** * **[class selector](http://api.jquery.com/class-selector/)**
There are many many ways to do it. You could also use `filter()` as an alternative maybe suitable for other more complicated cases. ``` $('div.dialog').filter(function(){ return !$(this).is('.large') }) ```
11,229,627
I have two divs: ``` <div class="dialog large"></div> ``` and ``` <div class="dialog"></div> ``` I have to remove the one with the class "dialog" but keep the one with "dialog large". If I do `$('dialog').remove();` they are both removed. Can anyone help me with this?
2012/06/27
[ "https://Stackoverflow.com/questions/11229627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310276/" ]
``` $('div.dialog:not(.large)').remove(); ``` **[DEMO](http://jsfiddle.net/QStkd/512/)** ### A little explain `div.dialog` will select `div` with `class=dialog` (in this case both div will select). But `div.dialog:not(.large)` will exclude those `div` with `class` `large` and remove them. ### Related Refs * **[:not()](http://api.jquery.com/not-selector/)** * **[class selector](http://api.jquery.com/class-selector/)**
if you want to remove DIVs where the class is exactly "dialog", try: ``` $('div[class="dialog"]').remove(); ```
18,711,025
i will try to make this as simple as possible. I have a working GUI with *SELECT, INSERT, DELETE and UPDATE* (**CRUD**) buttons and I am required to use a helper class and NOT just have the code running behind the buttons ect. But I have NO IDEA what so EVER on how to even start coding this. I don't understand how I can code an action for a button or a label if i'm working in another class. I have tried doing "ClassNameHere: Form1" but I get an error: > > lblInfo is inacessible due to its protection level > > cmbTable is inaccessible due to its protection level > > > I have googled that and tried changing classes to `public` and not public ect ect to no avail. So I have to get this code (this is just the `SELECT`query) ``` private void fillcomboBox() { try { conn = new MySqlConnection(connstring); conn.Open(); MySqlCommand myCommand = new MySqlCommand("SELECT * FROM person", conn); MySqlDataReader myReader; myReader = myCommand.ExecuteReader(); cmbTable.Items.Clear(); while (myReader.Read()) { cmbTable.Items.Add(myReader["personID"] + " | " + myReader["firstName"] + " | " + myReader["lastName"] + " | " + myReader["address"] + " | " + myReader["phoneNumber"] + " | " + myReader["postCode"] + " | " + myReader["dateOfBirth"]); } } catch (Exception err) {//handle the error with a message lblInfo.Text = " Error reading the database."; lblInfo.Text += err.Message; ; } finally { } } ``` To work in a different class (the helper class) and be linked to the form so that it works but is not behind the buttons...I hope that makes sense. But like I said, I have no clue on how to even start coding this. I would love ANY input, anything at all. Thank you.
2013/09/10
[ "https://Stackoverflow.com/questions/18711025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469932/" ]
``` $("#div-my-table").text("<table>"); $.each(data, function (i, item) { $("#div-my-table").append("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>"); }); $("#div-my-table").append("</table>"); ``` `append` does not output the html directly like that. It appends full elements and won't take broken pieces of html. You want: ``` var $table = $("<table></table>"); $.each(data, function (i, item) { $table.append($("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>")); }); $("#div-my-table").append($table); ``` **edit** To make this a full solution, also you need `$(document)` rather than `$("document")`.
I think this is your problem ``` $("document").ready(function () { ``` remove quotes ``` $(document).ready(function () { ```
18,711,025
i will try to make this as simple as possible. I have a working GUI with *SELECT, INSERT, DELETE and UPDATE* (**CRUD**) buttons and I am required to use a helper class and NOT just have the code running behind the buttons ect. But I have NO IDEA what so EVER on how to even start coding this. I don't understand how I can code an action for a button or a label if i'm working in another class. I have tried doing "ClassNameHere: Form1" but I get an error: > > lblInfo is inacessible due to its protection level > > cmbTable is inaccessible due to its protection level > > > I have googled that and tried changing classes to `public` and not public ect ect to no avail. So I have to get this code (this is just the `SELECT`query) ``` private void fillcomboBox() { try { conn = new MySqlConnection(connstring); conn.Open(); MySqlCommand myCommand = new MySqlCommand("SELECT * FROM person", conn); MySqlDataReader myReader; myReader = myCommand.ExecuteReader(); cmbTable.Items.Clear(); while (myReader.Read()) { cmbTable.Items.Add(myReader["personID"] + " | " + myReader["firstName"] + " | " + myReader["lastName"] + " | " + myReader["address"] + " | " + myReader["phoneNumber"] + " | " + myReader["postCode"] + " | " + myReader["dateOfBirth"]); } } catch (Exception err) {//handle the error with a message lblInfo.Text = " Error reading the database."; lblInfo.Text += err.Message; ; } finally { } } ``` To work in a different class (the helper class) and be linked to the form so that it works but is not behind the buttons...I hope that makes sense. But like I said, I have no clue on how to even start coding this. I would love ANY input, anything at all. Thank you.
2013/09/10
[ "https://Stackoverflow.com/questions/18711025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469932/" ]
``` $("#div-my-table").text("<table>"); $.each(data, function (i, item) { $("#div-my-table").append("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>"); }); $("#div-my-table").append("</table>"); ``` `append` does not output the html directly like that. It appends full elements and won't take broken pieces of html. You want: ``` var $table = $("<table></table>"); $.each(data, function (i, item) { $table.append($("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>")); }); $("#div-my-table").append($table); ``` **edit** To make this a full solution, also you need `$(document)` rather than `$("document")`.
The following section ``` $("#div-my-table").text("<table>"); $.each(data, function(i, item) { $("#div-my-table").append("<tr><td>" + item.EncoderName +"</td><td>" + item.EncoderStatus + "</td></tr>"); }); $("#div-my-table").append("</table>"); ``` should be something like: ``` var $table = $('<table></table>'); $.each(data, function(i, item) { $table.append("<tr><td>" + item.EncoderName +"</td><td>" + item.EncoderStatus + "</td></tr>"); }); $("#div-my-table").append($table); ``` Also: `$('document')` should be `$(document)` because `$('document')` looks for an element `<document></document>` which does not exist. Whereas `$(document)` converts the document global object to a jQuery object. In the first correction, please remember that `$.text('')` does not handle html, and will write the result as just `'&lt;table&gt;'`. The above corrected model is also better because using a disconnected/not-attached jquery object to populate elements from an iterator is faster. **EDIT:** The url you've specified is marked as Malware by chrome, so I'm using a substitute service <http://date.jsontest.com/>. Also, since that service just returns one object, I'm wrapping that object in an array myself so that you can still see how `$.each` was working. The fiddle is here: <http://jsfiddle.net/2xTjf/>
18,711,025
i will try to make this as simple as possible. I have a working GUI with *SELECT, INSERT, DELETE and UPDATE* (**CRUD**) buttons and I am required to use a helper class and NOT just have the code running behind the buttons ect. But I have NO IDEA what so EVER on how to even start coding this. I don't understand how I can code an action for a button or a label if i'm working in another class. I have tried doing "ClassNameHere: Form1" but I get an error: > > lblInfo is inacessible due to its protection level > > cmbTable is inaccessible due to its protection level > > > I have googled that and tried changing classes to `public` and not public ect ect to no avail. So I have to get this code (this is just the `SELECT`query) ``` private void fillcomboBox() { try { conn = new MySqlConnection(connstring); conn.Open(); MySqlCommand myCommand = new MySqlCommand("SELECT * FROM person", conn); MySqlDataReader myReader; myReader = myCommand.ExecuteReader(); cmbTable.Items.Clear(); while (myReader.Read()) { cmbTable.Items.Add(myReader["personID"] + " | " + myReader["firstName"] + " | " + myReader["lastName"] + " | " + myReader["address"] + " | " + myReader["phoneNumber"] + " | " + myReader["postCode"] + " | " + myReader["dateOfBirth"]); } } catch (Exception err) {//handle the error with a message lblInfo.Text = " Error reading the database."; lblInfo.Text += err.Message; ; } finally { } } ``` To work in a different class (the helper class) and be linked to the form so that it works but is not behind the buttons...I hope that makes sense. But like I said, I have no clue on how to even start coding this. I would love ANY input, anything at all. Thank you.
2013/09/10
[ "https://Stackoverflow.com/questions/18711025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469932/" ]
``` $("#div-my-table").text("<table>"); $.each(data, function (i, item) { $("#div-my-table").append("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>"); }); $("#div-my-table").append("</table>"); ``` `append` does not output the html directly like that. It appends full elements and won't take broken pieces of html. You want: ``` var $table = $("<table></table>"); $.each(data, function (i, item) { $table.append($("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>")); }); $("#div-my-table").append($table); ``` **edit** To make this a full solution, also you need `$(document)` rather than `$("document")`.
We can Implement **Jquery Template** for easy rendering of JSON data.The usage is as follows 1.Download "**jquery.tmpl.min.js**" file and include in your page. 2.We are considering the table as our container.And the we will define the template need to to be inserted into the container. Example of Template: ``` //The data inside JSON object we will use as follows //Note:Template definition should be inside Script tag same as javascript functions <script id="tableContentTemplate" type="text/x-jquery-tmpl"> <tr> <td> Deal Id :\${EncoderName }</td> <td> Deal Id :\${EncoderStatus }</td> </tr> </script> ``` 3. Define methods to render data through template to container.Based on requirements we can change these methods as they are user defined methods ``` function emptyContainer(container){ $( container ).empty(); } function renderTemplate( container, template, data ){ $.tmpl( $(template), data, {array: data} ).appendTo( container ); } function AddExtraTemplate( container, template ){ $.tmpl( $(template)).appendTo( container ); } ``` 4.In success function of Ajax call the methods as follows ``` $.getJSON("http://www.celeritas-solutions.com/pah_brd_v1/productivo/getGroups.php?organizationCode=att&userId1", function (data) { emptyContainer("#div-my-table");//empty container renderTemplateForOffice( "#div-my-table", "#tableContentTemplate" , data ); // render template based on data.For multiple values it will render multiple times.Separate Iteration is not required. }); ``` Please inspect your json Data, It should look like as follows {'EncoderName':'XYZ','EncoderStatus':'Completed'}
13,652,386
I have a table of statuses, each of which have a name attribute. Currently I can do: ``` FooStatus.find_by_name("bar") ``` And that's fine. But I'm wondering if I could do: ``` FooStatus.bar ``` So I have this approach: ``` class FooStatus < ActiveRecord::Base def self.method_missing(meth, *args, &block) if self.allowed_statuses.include?(meth.to_s.titleize) self.where("name = ?", meth.to_s.titleize).first else super(meth, *args, &block) end end def self.allowed_statuses self.pluck(:name) end end ``` The above code works, but it leads to the following weird behavior: ``` FooStatus.respond_to?(:bar) => false FooStatus.bar => #<FooStatus name: 'bar'> ``` That's not great, but if I try to implement respond\_to?, I get a recursion problem ``` class FooStatus < ActiveRecord::Base def self.method_missing(meth, *args, &block) if self.allowed_statuses.include?(meth.to_s.titleize) self.where("name = ?", meth.to_s.titleize).first else super(meth, *args, &block) end end def self.allowed_statuses self.pluck(:name) end def self.respond_to?(meth, include_private = false) if self.allowed_statuses.include?(meth.to_s.titleize) true else super(meth) end end end ``` And that gets me: ``` FooStatus.bar => ThreadError: deadlock; recursive locking ``` Any ideas on getting method\_missing and respond\_to to work together?
2012/11/30
[ "https://Stackoverflow.com/questions/13652386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648538/" ]
I don't know if I'd recommend your approach... seems too magical to me and I worry about what happens when you have a status with a name of 'destroy' or some other method you might legitimately want to call (or that Rails' calls internally that you aren't aware of). But... instead of mucking with method missing, I think you'd be better off extending the class and automatically defining the methods by looping through allowed\_statuses and creating them. This will make respond\_to? work. And you could also check to make sure it's not already defined somewhere else...
Use a scope. ``` class FooStatus < ActiveRecord::Base scope :bar, where(:name => "bar") # etc end ``` Now, you can do `FooStatus.bar` which will return an ActiveRelation object. If you expect this to return a single instance, you could do `FooStatus.bar.first` or if many `FooStatus.bar.all`, or you could put the `.first` or `.all` on the end of the scope in which case it'll return the same thing as the finder. You can also define a scope with a lambda if the input isn't constant (not always "bar"). [Section 13.1 of this guide has an example](http://guides.rubyonrails.org/active_record_querying.html#scopes)
13,652,386
I have a table of statuses, each of which have a name attribute. Currently I can do: ``` FooStatus.find_by_name("bar") ``` And that's fine. But I'm wondering if I could do: ``` FooStatus.bar ``` So I have this approach: ``` class FooStatus < ActiveRecord::Base def self.method_missing(meth, *args, &block) if self.allowed_statuses.include?(meth.to_s.titleize) self.where("name = ?", meth.to_s.titleize).first else super(meth, *args, &block) end end def self.allowed_statuses self.pluck(:name) end end ``` The above code works, but it leads to the following weird behavior: ``` FooStatus.respond_to?(:bar) => false FooStatus.bar => #<FooStatus name: 'bar'> ``` That's not great, but if I try to implement respond\_to?, I get a recursion problem ``` class FooStatus < ActiveRecord::Base def self.method_missing(meth, *args, &block) if self.allowed_statuses.include?(meth.to_s.titleize) self.where("name = ?", meth.to_s.titleize).first else super(meth, *args, &block) end end def self.allowed_statuses self.pluck(:name) end def self.respond_to?(meth, include_private = false) if self.allowed_statuses.include?(meth.to_s.titleize) true else super(meth) end end end ``` And that gets me: ``` FooStatus.bar => ThreadError: deadlock; recursive locking ``` Any ideas on getting method\_missing and respond\_to to work together?
2012/11/30
[ "https://Stackoverflow.com/questions/13652386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648538/" ]
I agree with Philip Hallstrom's suggestion. If you know allowed\_statuses when the class is built, then just loop through the list and define the methods explicitly: ``` %w(foo bar baz).each do |status| define_singleton_method(status) do where("name = ?", status.titleize).first end end ``` …or if you need that list of statuses elsewhere in the code: ``` ALLOWED_STATUSES = %w(foo bar baz).freeze ALLOWED_STATUSES.each do |status| define_singleton_method(status) do where("name = ?", status.titleize).first end end ``` Clearer, shorter, and far less prone to future breakage and weird rabbit hole conflicts with ActiveRecord like the one you're in. You can do really cool things with method\_missing and friends, but it's not the first approach to go to when doing metaprogramming. Explicit is usually better when possible. I also agree with Philip's concernt about creating conflicts with built-in methods. Having a hard-coded list of statuses prevents that from going too far, but you might consider a convention like `FooStatus.named_bar` instead of `FooStatus.bar` if that list is likely to grow or change.
I don't know if I'd recommend your approach... seems too magical to me and I worry about what happens when you have a status with a name of 'destroy' or some other method you might legitimately want to call (or that Rails' calls internally that you aren't aware of). But... instead of mucking with method missing, I think you'd be better off extending the class and automatically defining the methods by looping through allowed\_statuses and creating them. This will make respond\_to? work. And you could also check to make sure it's not already defined somewhere else...
13,652,386
I have a table of statuses, each of which have a name attribute. Currently I can do: ``` FooStatus.find_by_name("bar") ``` And that's fine. But I'm wondering if I could do: ``` FooStatus.bar ``` So I have this approach: ``` class FooStatus < ActiveRecord::Base def self.method_missing(meth, *args, &block) if self.allowed_statuses.include?(meth.to_s.titleize) self.where("name = ?", meth.to_s.titleize).first else super(meth, *args, &block) end end def self.allowed_statuses self.pluck(:name) end end ``` The above code works, but it leads to the following weird behavior: ``` FooStatus.respond_to?(:bar) => false FooStatus.bar => #<FooStatus name: 'bar'> ``` That's not great, but if I try to implement respond\_to?, I get a recursion problem ``` class FooStatus < ActiveRecord::Base def self.method_missing(meth, *args, &block) if self.allowed_statuses.include?(meth.to_s.titleize) self.where("name = ?", meth.to_s.titleize).first else super(meth, *args, &block) end end def self.allowed_statuses self.pluck(:name) end def self.respond_to?(meth, include_private = false) if self.allowed_statuses.include?(meth.to_s.titleize) true else super(meth) end end end ``` And that gets me: ``` FooStatus.bar => ThreadError: deadlock; recursive locking ``` Any ideas on getting method\_missing and respond\_to to work together?
2012/11/30
[ "https://Stackoverflow.com/questions/13652386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648538/" ]
I agree with Philip Hallstrom's suggestion. If you know allowed\_statuses when the class is built, then just loop through the list and define the methods explicitly: ``` %w(foo bar baz).each do |status| define_singleton_method(status) do where("name = ?", status.titleize).first end end ``` …or if you need that list of statuses elsewhere in the code: ``` ALLOWED_STATUSES = %w(foo bar baz).freeze ALLOWED_STATUSES.each do |status| define_singleton_method(status) do where("name = ?", status.titleize).first end end ``` Clearer, shorter, and far less prone to future breakage and weird rabbit hole conflicts with ActiveRecord like the one you're in. You can do really cool things with method\_missing and friends, but it's not the first approach to go to when doing metaprogramming. Explicit is usually better when possible. I also agree with Philip's concernt about creating conflicts with built-in methods. Having a hard-coded list of statuses prevents that from going too far, but you might consider a convention like `FooStatus.named_bar` instead of `FooStatus.bar` if that list is likely to grow or change.
Use a scope. ``` class FooStatus < ActiveRecord::Base scope :bar, where(:name => "bar") # etc end ``` Now, you can do `FooStatus.bar` which will return an ActiveRelation object. If you expect this to return a single instance, you could do `FooStatus.bar.first` or if many `FooStatus.bar.all`, or you could put the `.first` or `.all` on the end of the scope in which case it'll return the same thing as the finder. You can also define a scope with a lambda if the input isn't constant (not always "bar"). [Section 13.1 of this guide has an example](http://guides.rubyonrails.org/active_record_querying.html#scopes)
191,981
Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper. EDIT: Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end. First, the clarifications: 1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles. 2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies. 3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question). 4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species. 5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them. 6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture. So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering. I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion). As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah. As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment. As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean. Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them.
2020/12/14
[ "https://worldbuilding.stackexchange.com/questions/191981", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81238/" ]
**Maybe, if they can overcome population density issues.** The key way to develop all of those civilization issues is to have a very high density of people working together on shared ideas, without them needing to mine the landscape and so gaining greater technology as they get better at mining. As such, you need natural skyscrapers. One way to do this is with [Inosculation](https://en.wikipedia.org/wiki/Inosculation) where you can grow trees together. This civilization could have very advanced tree growing techniques where they can grow trees together to form houses and homes and platforms for their homes. The trees could naturally provide a large bounty for them. As such, they could have huge cities of tens or hundreds of thousands on shared trees, without having any technology that is useful on a scale of less than years. **The main problem is working out how they handle conflict and danger.** They can be peace loving sure, but what happens when a hostile pest destroys their food stocks, or a natural disaster wrecks their home, or a plague kills their people? When times are tough, people often resort to war to get new resources, no matter how peace loving. For this I would suggest [flower war.](https://en.wikipedia.org/wiki/Flower_war) Rather than having costly and large engagements, small fights between mostly nobles and some commoners would be the norm. You meet on a set date, fight with proven weapons, and whoever is more skilled in melee combat wins. You can trade resources based off this. This would prevent the need for large scale costly wars which would advance technology.
Yes, technology and advanced civilisation are not related. The most advanced civilisations may have no recognisable technology and be completely integrated with nature, working with it instead of against it, without war, crime, poverty or hatred. Other cultures will sneer at them as mere hippies, or decry the entire concept as a reversion to the 'noble savage stereotype' ...while secretly envying their relaxed lifestyle.
191,981
Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper. EDIT: Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end. First, the clarifications: 1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles. 2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies. 3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question). 4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species. 5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them. 6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture. So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering. I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion). As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah. As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment. As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean. Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them.
2020/12/14
[ "https://worldbuilding.stackexchange.com/questions/191981", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81238/" ]
Maybe in the sea ---------------- I think it is possible, with aquatic species. Ocean is different from land in all the ways that makes rise of sapience possible (hello dolphins), but limits severely what kind of technology they can use. There's no fire, no metals, so your species population density might reach those critical stages where it kickstarts the necessity for regulations, etiquette and so on, in terms of the technology they would be restricted to hunter gatherers or early agriculture at best, since the easy paths that were available for us to start doing stuff like metal smelting would be closed off for them. Do keep in mind though that we really have little idea about how intricate were social and cultural interactions in our prehistoric ancestors. Nothing except physical artifacts remained, and writing was invented only seven thousand years later. I do not think that before "civilization" they were dumb brutes as they often depicted in media.
> > Can a civilization be highly evolved as far as culture, ethics, societal norms, ***laws***, language, ***literature*** and ***arts***, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? > > > I've added emphasis. How do you expect your civilisation to produce writing, drawing sculpting etc materials without technology? And what is the need for a complex set of laws when only a few hundred people who the land can support in proximity can interact? Does your technology level of "agriculture" include food storage? Processing of fresh food into preserved forms for winter? Transport of foodstuffs? The other issue is that if there is a similar civilisation nearby which has also developed all of these items, but has additionally developed weapons, then your civilisation will not last long before it is attacked and its resources are captured. However it is feasible, and has happened in the real world, that a geographically isolated civilisation could last a very long time with just enough technology to meet current needs whilst focussing on developing literature and arts. You will still need to think about how it would cope with unexpected events: famines, earthquakes etc. if there is little culture of problem-solving and technological development
191,981
Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper. EDIT: Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end. First, the clarifications: 1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles. 2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies. 3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question). 4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species. 5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them. 6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture. So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering. I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion). As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah. As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment. As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean. Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them.
2020/12/14
[ "https://worldbuilding.stackexchange.com/questions/191981", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81238/" ]
No, the other way round. ======================== Civilization is the inevitable consequence of technology. Specifically, the technology called "Literacy" As soon as a culture starts storing information for future generations, whether by actual Writing and Literacy or via very strict Oral Traditions, that culture starts to gather knowledge. And this gathering of knowledge is what makes civilization possible. And by gathering knowledge, it becomes easier to live, easier to grow, and....easier to gather more knowledge. More people, more knowledge, *is* civilization.
**Maybe, if they can overcome population density issues.** The key way to develop all of those civilization issues is to have a very high density of people working together on shared ideas, without them needing to mine the landscape and so gaining greater technology as they get better at mining. As such, you need natural skyscrapers. One way to do this is with [Inosculation](https://en.wikipedia.org/wiki/Inosculation) where you can grow trees together. This civilization could have very advanced tree growing techniques where they can grow trees together to form houses and homes and platforms for their homes. The trees could naturally provide a large bounty for them. As such, they could have huge cities of tens or hundreds of thousands on shared trees, without having any technology that is useful on a scale of less than years. **The main problem is working out how they handle conflict and danger.** They can be peace loving sure, but what happens when a hostile pest destroys their food stocks, or a natural disaster wrecks their home, or a plague kills their people? When times are tough, people often resort to war to get new resources, no matter how peace loving. For this I would suggest [flower war.](https://en.wikipedia.org/wiki/Flower_war) Rather than having costly and large engagements, small fights between mostly nobles and some commoners would be the norm. You meet on a set date, fight with proven weapons, and whoever is more skilled in melee combat wins. You can trade resources based off this. This would prevent the need for large scale costly wars which would advance technology.
191,981
Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper. EDIT: Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end. First, the clarifications: 1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles. 2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies. 3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question). 4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species. 5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them. 6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture. So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering. I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion). As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah. As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment. As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean. Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them.
2020/12/14
[ "https://worldbuilding.stackexchange.com/questions/191981", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81238/" ]
No -- They're both the result of population density exceeding a critical level. Both to cause and maintain. This goes back to [Gobekli Tepe](https://www.smithsonianmag.com/history/gobekli-tepe-the-worlds-first-temple-83613665/) and the stories that go with it. One of them being that it's the first place where population density exceeded that capable of being sustained by a hunter gatherer lifestyle. The earliest evidence of farming is in the same area in the same period. Civilisation is a relationship between people, the rules of this relationship are dependent on how much people have to interact with each other. You need language, you need laws, you need communication. One person alone can do what they like and need never speak or write, the more people have to interact, the more structure is required, this is the basis for civilisation. As long as the population density never exceeds what your technological level comfortably supports, there's no driving incentive for increased technology, nor the manpower to support it. The aeolipile remains an interesting toy, not a critical proof of concept.
Yes, technology and advanced civilisation are not related. The most advanced civilisations may have no recognisable technology and be completely integrated with nature, working with it instead of against it, without war, crime, poverty or hatred. Other cultures will sneer at them as mere hippies, or decry the entire concept as a reversion to the 'noble savage stereotype' ...while secretly envying their relaxed lifestyle.
191,981
Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper. EDIT: Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end. First, the clarifications: 1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles. 2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies. 3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question). 4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species. 5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them. 6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture. So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering. I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion). As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah. As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment. As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean. Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them.
2020/12/14
[ "https://worldbuilding.stackexchange.com/questions/191981", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81238/" ]
No, the other way round. ======================== Civilization is the inevitable consequence of technology. Specifically, the technology called "Literacy" As soon as a culture starts storing information for future generations, whether by actual Writing and Literacy or via very strict Oral Traditions, that culture starts to gather knowledge. And this gathering of knowledge is what makes civilization possible. And by gathering knowledge, it becomes easier to live, easier to grow, and....easier to gather more knowledge. More people, more knowledge, *is* civilization.
Technology per se is a rather broad term. You can have civilization without certain technologies. The Mayas had a fairly developed civilization with respect to weapons, astronomy, religion, architecture and agriculture, all advanced to a quite good level. Despite that they never came out with the technology of a wheel for transportation, which I would say it's at the base of the practical techniques. So, yes, it's totally plausible.
191,981
Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper. EDIT: Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end. First, the clarifications: 1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles. 2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies. 3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question). 4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species. 5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them. 6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture. So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering. I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion). As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah. As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment. As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean. Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them.
2020/12/14
[ "https://worldbuilding.stackexchange.com/questions/191981", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81238/" ]
No, the other way round. ======================== Civilization is the inevitable consequence of technology. Specifically, the technology called "Literacy" As soon as a culture starts storing information for future generations, whether by actual Writing and Literacy or via very strict Oral Traditions, that culture starts to gather knowledge. And this gathering of knowledge is what makes civilization possible. And by gathering knowledge, it becomes easier to live, easier to grow, and....easier to gather more knowledge. More people, more knowledge, *is* civilization.
Technology far predates Civilization (and construction and agriculture) ----------------------------------------------------------------------- Assuming a standard definition that nearly all scholars use for technology, it has existed since humans could first reasonably called humans, and probably even before that. Technology is: > > Technology is the sum of techniques, skills, methods, and processes used in the production of goods or services or in the accomplishment of objectives, such as scientific investigation. > > > ... > > The simplest form of technology is the development and use of basic tools. The prehistoric discovery of how to control fire and the later Neolithic Revolution increased the available sources of food, and the invention of the wheel helped humans to travel in and control their environment. > > > Basic tools date back to [2.6 million years ago](https://humanorigins.si.edu/evidence/behavior/stone-tools#:%7E:text=The%20earliest%20stone%20toolmaking%20developed,cores%2C%20and%20sharp%20stone%20flakes.). The earliest civilizations are only [thousands of years old](https://en.wikipedia.org/wiki/Human_history#:%7E:text=Sumer%2C%20located%20in%20Mesopotamia%2C%20is,script%2C%20appeared%20around%203000%20BCE.). With that we can easily answer the question: -------------------------------------------- > > Is technology a natural consequence of civilization? > > > and > > Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? > > > Technology is obviously not a consequence of civilization, it far predates it. Moreover, it is unthinkable that you would have civilization without technology, even with the caveats given. The technology used to create construction and agriculture would inevitably lead to those techniques being used for other things. We can see that tools were used millions of years before construction and agriculture were even conceived.
191,981
Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper. EDIT: Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end. First, the clarifications: 1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles. 2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies. 3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question). 4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species. 5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them. 6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture. So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering. I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion). As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah. As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment. As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean. Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them.
2020/12/14
[ "https://worldbuilding.stackexchange.com/questions/191981", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81238/" ]
### Maybe, in a magically-powered fantasy universe with inconsistent physics. In fantasy world where the laws of physics behave in an inconsistent fashion but there is sufficient amounts of magic to allow life to function despite that, it might be possible that a society doesn't develop much if any technology if it relies primarily on magic instead. For instance, if smelting iron ore into a consistently usable form isn't possible without magic, then they probably won't use non-magical iron tools. If gears randomly jam up and break, then you won't have clockwork or watermills. If refining flammable oil is as likely to result in an explosive as lantern fuel, then you won't see any oil lanterns.
in my opinion, i think its possible if we are not talking about human as the focus, but alien lifeform or other animals society, especially if they cant manipulate tools and depend on group work. for example ant and bee, at least from quick google they are considered as civilization with their society, and i think ant are quite advance regarding agriculture/domestication and building, but they dont develop any tools as far as i know, and only using their body feature or ability including using their larvae silk to glued the materials in case of weaver ants. i dont know why mine get downvote, after seeing OP edit it turn out not about human anyway and mean electronic technology specifically, but here copy paste some answer from [quora](https://www.quora.com/Do-ants-have-civilization), also i want to remind ppl that OP originally is fine with advance agriculture and architecture technology. > > I. Embryonic civilizations, which still only possess the basics of the elements of civilization (although they are still very advanced; > the Sumerians were embryonic and are famous for being the first > civilization and for being advanced) > > > II. Advanced civilizations, which feature advanced elements of the > keys. > > > The five key elements of civilization are: > > > I. Centralized Government > > > II. Organized Religion > > > III. Job Specialization > > > IV. Social Classes > > > V. Arts, architecture, writing > > > We can assume from this point that the ants are an embryonic > civilization. > > > Ants and Technological Advancement > > > Fun fact: Did you know that ants discovered agriculture? For millions > of years, in fact, ants have developed the skill to grow, harvest, and > eat several small plants. > > > Other fun fact: Ants & Vassals. > > > A vassal kingdom is an otherwise independent country which pays > tribute to a greater power. Tribute is essentially, in historical > cases, a portion of supplies and manpower. Vassals would pay their > rulers in soldiers, food, or labor. One species of ants, called > Slavemaking Ants, literally invade colonies and take 10% of their > larvae every month or so. This larvae is carried home and raised like > the slavemakers’ own children. These ants, after being birthed, > genuinely think that they are part of the colony, even if they’re > another species of ant, and will then join their kidnappers in raids > against even its home colony without any memory. Slavemaking ants use > this strategy to boost their numbers. > > > Social Heirarchy: > > > Simply put: > > > Queens—Alpha & Beta Males—Soldiers—Omega Males & Females. > > > Every ant knows its place. > > > Religion: > > > A hive mind, one could potentially argue that ants worship their > queens as if they were deities. Like chimpanzees, they cold > hypothetically possess a very primitive spirituality. Chimp religion, > however, is still under research. > > > Architecture & Arts: > > > Ants all have one uniform colony style: Tunnels and mounds. Larger > queendoms can be several interconnected mounds spanning multiple > acres. One of the largest ant Queendoms of all time, located in Japan, > spanned over 640 acres and possessed 45,000 different anthills. Its > population could’ve consisted of as many as 306 MILLION ants. > > >
191,981
Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture? They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper. EDIT: Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end. First, the clarifications: 1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles. 2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies. 3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question). 4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species. 5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them. 6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture. So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering. I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion). As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah. As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment. As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean. Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them.
2020/12/14
[ "https://worldbuilding.stackexchange.com/questions/191981", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/81238/" ]
Technology is a *prerequisite* for civilization ----------------------------------------------- Civilization means cities. The word in fact [has a common root with city](https://www.etymonline.com/word/civil). To have a city requires a lot of assorted technologies. Building materials. Storage containers. Fire. One of the key ones you've identified is agriculture. In order to have cities, you have to have technologies and capabilities that go beyond strategies that will work for smaller-scale communities. Cities need an external food supply, and they need the wherewithal to get the food from the supply to them. Efficiency creates more efficiency ---------------------------------- I saw a very interesting proposition, which I can't find right now, that put one of reasons for the increase in the technological progress rate like this: Very roughly, the rate of technological progress is dependent on the number of people that have surplus time, folks whose immediate demands on their time and attention (subsistence, maintaining infrastructure, manning the army, etc) are not total. See, creating a new invention takes time, often for little short-term practical benefit. The benefits in the long term are astounding - computers, antibiotics, airplanes - but they can take a *very* long time to be realized. [John Dalton](https://www.britannica.com/biography/John-Dalton/Atomic-theory) discovered the atom around 1800 (although a Greek had hypothesized their existence long before). The first [nuclear power plant](https://en.wikipedia.org/wiki/Nuclear_power#First_nuclear_reactor) - a research reactor - came online in 1942. So a society has to be well off enough to be able to support folks that do nothing but pursue pie in the sky technological innovation and especially basic research. And the more of those folks you have, the more technology you have. You can't have a civilization *at all* without people discovering enough technology to make cities work. So you have to have some of them around. And the funny thing is, the more technology you have, the more productivity improves, the society will naturally produce more and more of these folks. (Generally speaking, of course.) TL;DR yes, technological advancement is a natural consequence of civilization. Necessity is the mother of invention.
Maybe in the sea ---------------- I think it is possible, with aquatic species. Ocean is different from land in all the ways that makes rise of sapience possible (hello dolphins), but limits severely what kind of technology they can use. There's no fire, no metals, so your species population density might reach those critical stages where it kickstarts the necessity for regulations, etiquette and so on, in terms of the technology they would be restricted to hunter gatherers or early agriculture at best, since the easy paths that were available for us to start doing stuff like metal smelting would be closed off for them. Do keep in mind though that we really have little idea about how intricate were social and cultural interactions in our prehistoric ancestors. Nothing except physical artifacts remained, and writing was invented only seven thousand years later. I do not think that before "civilization" they were dumb brutes as they often depicted in media.