source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0045542804.txt" ]
Q: Parse a ziped XML file with PHP from an URL I would like to parse a XML file from URL and with PHP. For the moment, with this code, I can have the content of the XML file, but I am not succeeding in using the simplexml_load_string in order to use it as a XML content. Indeed, when I echo zip, the text appears without the XML tags. Would you have an idea? Thanks. <?php $file = 'http://url_here_.zip'; $newfile = 'tmp_name_file.zip'; if (!copy($file, $newfile)) { echo "failed to copy $file...\n";} $zip = new ZipArchive(); if ($zip->open($newfile)!==TRUE) { exit("cannot open <$filename>\n"); } else { $zip->getFromName('Scrutins_XIV.xml'); $xml = simplexml_load_string(file_get_contents($zip)); $zip->close(); } ?> A: Try this: $xml_string = $zip->getFromName('Scrutins_XIV.xml'); if ( $xml_string!= false ) { $xml = simplexml_load_string($xml_string); }
[ "stackoverflow", "0013339957.txt" ]
Q: Automatic serialization with Linq to Sql Is there any way to store data in the table kind of this: Inside SettingsModel column, which is defined in Linq-to-Sql like this: And also with DataContext option turned to the: With the class SettingsModel defined like this: namespace ElQueue.DataClasses { [DataContract] public sealed class SettingsModel { [DataMember(IsRequired = true)] public int[] VideoMediaData { get; set; } } } This way? ... using (SomeDataContext dataContext = new SomeDataContext()) { SettingsModel m = new SettingsModel(); m.VideoMediaData = new int[] { 1, 2, 3 }; dataContext.MainTableSettings.InsertOnSubmit(new MainTableSetting() { SettingsModel = m }); dataContext.SubmitChanges(); } using (SomeDataContext dataContext = new SomeDataContext()) { var r = dataContext.MainTableSettings.Single(); } You see, the code above doesnt work correctly, it is throwing exception which says that it cannot convert string to MainTableSetting which means that either it can not save all the serialized data or that plus cannot deserialize it back. I need some advices how to point this Linq-to-Sql to actually do serialization (and vice versa) when I access the database. A: Although you can map XElement and XDocument to SQL Server as shown in the Type Mapping Run Time Behavior Matrix, the System.Data.Linq.DataContext.CreateDatabase method has no default SQL Server type mapping for these types. If a class implements Parse() and ToString(), you can map the object to any SQL text type (CHAR, NCHAR, VARCHAR, NVARCHAR, TEXT, NTEXT, XML). The object is stored in the database by sending the value returned by ToString() to the mapped database column. The object is reconstructed by invoking Parse() on the string returned by the database. http://msdn.microsoft.com/en-us/library/bb386947.aspx#TextMapping public sealed class SettingsModel { // ... public static SettingsModel Parse(string source) { SettingsModel res; // Deserialise the object return res; } }
[ "stackoverflow", "0035628222.txt" ]
Q: Input hour and minute from user, and add duration to display updated time I need to write the program that accepts three integers as input (hour, minute, duration). Hour is in 24 hour format. The hour and minute should be considered the start time, and duration should be in minutes. You should then calculate the end time and display it properly in the format ##:##. This is what I got but my Starting time displays weird. #include <stdio.h> int main(int argc, char *argv[]) { int h=0,m=0,d=0,ht=0,t=0; printf("Starting Hours: "); scanf("%d",&h); printf("Starting Minutes: "); scanf("%d",&m); printf("Starting Time is %d,%d ,What is the duration"); scanf("%d",&d); t=(m+d); ht=t/60; h=(h+ht)%24; m=t%60; printf("Ending Time: %d:%d",h,m); getchar(); return 0; } My starting time displays something like this: when I enter 12 for hours, and 52 for min my Starting time displays as -2114693200:1. Not sure why happens A: missing arguments in printf() causing undefined behaviour. printf("Starting Time is %d,%d ,What is the duration"); it should be printf("Starting Time is %d,%d ,What is the duration",h,m); You also don't need to modulo by 24 unless you want to convert hour to days... if you want that you need to store and print number of days as well. h=(h+ht)%24;
[ "stackoverflow", "0020258876.txt" ]
Q: vb.net data not inserting into ms access database This is my form snapshot This is my code to insert data into data base Imports System.Data.OleDb Public Class Test Dim cnn As New OleDb.OleDbConnection Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim cmd As New OleDb.OleDbCommand If Not cnn.State = ConnectionState.Open Then cnn.Open() End If cmd.Connection = cnn cmd.CommandText = "INSERT INTO Test(ID, Test) " & _ " VALUES(" & Me.TextBox1.Text & ",'" & Me.TextBox2.Text & "')" cmd.ExecuteNonQuery() cnn.Close() End Sub Private Sub Test_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cnn = New OleDb.OleDbConnection cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\OfficeAutomationSystem.accdb; Persist Security Info=False" End Sub End Class My database name is : OfficeAutomationSystem.accdb , Table Name is: Test , Table Structure is as follows: FieldName DataType ID Number Test Text Code is running successfully, and giving no error. When I see in database, there was no record found in that What's the error? I'm unable to find it. So Please, Help me. Thanks in advance A: Sometimes Data Source=|DataDirectory|\... is problematic when debugging. Please bear on mind that you'll have another database in \bin\debug at your project folder when you are debugging your code. Probably you're updating the records in this database instead the original one. Try to set an absolute path and check if the records are being updated.
[ "stackoverflow", "0002397806.txt" ]
Q: Zend_Controller_Router Static Route Here is my route definition in the bootstrap file: $router = $this->frontController->getRouter(); $route = new Zend_Controller_Router_Route_Static( 'tipovanie', array('module' => 'default', 'controller' => 'index', 'action' => 'contest') ); $router->addRoute('contest', $route); Now when I go to /tipovanie I get correctly displayed the same content as at /index/contest. However, I am using url view helper to construct some links in my layout like this: <a href="<?php echo $this->url(array('module' => 'default', 'controller' => 'view', 'action' => 'user', 'id' => $this->escape($u->id)), null, true); ?>"><?php echo $this->escape($u->username); ?></a> And those links are pointing to: /tipovanie When viewing the /tipovanie page. On other pages without static rewritten route the url view helper works fine and the printed link is correct (for example /view/user/id/5). A: I am an idiot. I forgot to specify the default route for those links: <a href="<?php echo $this->url(array('module' => 'default', 'controller' => 'view', 'action' => 'user', 'id' => $this->escape($u->id)), 'default', true); ?>"><?php echo $this->escape($u->username); ?></a>
[ "stackoverflow", "0046793206.txt" ]
Q: How to show an exception message if the user doesn't check a radio button in Xamarin Android? Hi I need to display a error message on the screen if the user doesn't check a radio button. In this code there are 13 radio buttons separeted on 4 radio groups. I tried to use try/catch and if/else but the screen stills not showing the Toast error message. Another doubt: I know that radio groups doesn't allow a person to choose more than 1 option, but how can I do an excepeiton that allows the user just to pick 1 button of one single radio group? For example: now I have to choose at least 4 buttons (1 of each radio group) but I want to do it in a way that just one of any group will be good enough Here is the code using Android.App; using Android.Content.PM; using Android.Content.Res; using Android.OS; using Android.Support.V4.Widget; using Android.Views; using Android.Widget; using System.Collections; using Android.Support.V7.App; using Android.Support.V4.View; using Android.Support.Design.Widget; using Auth0.OidcClient; using Android.Content; using IdentityModel.OidcClient; using Android.Graphics; using System.Net; using System; using Android.Runtime; using Android.Text.Method; using System.Text; namespace whirlpoolapp { [Activity(Label = "whirlpoolapp", MainLauncher = true)] [IntentFilter( new[] { Intent.ActionView }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, DataScheme = "whirlpoolapp.whirlpoolapp", DataHost = "lucasmoreira.auth0.com", DataPathPrefix = "/android/whirlpoolapp.whirlpoolapp/callback")] public class MainActivity : Activity { private ArrayList enderecos; TextView queroreconhecer; TextView crie; TextView conquiste; TextView entregue; TextView viva; TextView comentar; EditText comentário; Spinner spinner; ArrayAdapter adapter; RadioGroup rdgcrie; RadioGroup rdgconquiste; RadioGroup rdgentregue; RadioGroup rdgviva; Button enviar; private Auth0Client client; private AuthorizeState authorizeState; ProgressDialog progress; protected override void OnResume() { base.OnResume(); if (progress != null) { progress.Dismiss(); progress.Dispose(); progress = null; } } protected override async void OnNewIntent(Intent intent) { base.OnNewIntent(intent); var loginResult = await client.ProcessResponseAsync(intent.DataString, authorizeState); var sb = new StringBuilder(); if (loginResult.IsError) { sb.AppendLine($"An error occurred during login: {loginResult.Error}"); } else { sb.AppendLine($"ID Token: {loginResult.IdentityToken}"); sb.AppendLine($"Access Token: {loginResult.AccessToken}"); sb.AppendLine($"Refresh Token: {loginResult.RefreshToken}"); sb.AppendLine(); sb.AppendLine("-- Claims --"); foreach (var claim in loginResult.User.Claims) { sb.AppendLine($"{claim.Type} = {claim.Value}"); } } } private async void LoginButtonOnClick(object sender, EventArgs eventArgs) { progress = new ProgressDialog(this); progress.SetTitle("Log In"); progress.SetMessage("Please wait while redirecting to login screen..."); progress.SetCancelable(false); // disable dismiss by tapping outside of the dialog progress.Show(); // Prepare for the login authorizeState = await client.PrepareLoginAsync(); // Send the user off to the authorization endpoint var uri = Android.Net.Uri.Parse(authorizeState.StartUrl); var intent = new Intent(Intent.ActionView, uri); intent.AddFlags(ActivityFlags.NoHistory); StartActivity(intent); } protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); client = new Auth0Client(new Auth0ClientOptions { Domain = Resources.GetString(Resource.String.auth0_domain), ClientId = Resources.GetString(Resource.String.auth0_client_id), Activity = this }); //preenche o arraylist com os dados GetEmails(); //cria a instância do spinner declarado no arquivo Main spinner = FindViewById<Spinner>(Resource.Id.spnDados); //cria textview queroreconhecer = FindViewById<TextView>(Resource.Id.txtReconhecer); crie = FindViewById<TextView>(Resource.Id.txtCrie); conquiste = FindViewById<TextView>(Resource.Id.txtConquiste); entregue = FindViewById<TextView>(Resource.Id.txtEntregue); viva = FindViewById<TextView>(Resource.Id.txtViva); comentar = FindViewById<TextView>(Resource.Id.txtComentário); comentário = FindViewById<EditText>(Resource.Id.edtComentario); rdgcrie = FindViewById<RadioGroup>(Resource.Id.rdgCrie); rdgconquiste = FindViewById<RadioGroup>(Resource.Id.rdgConquiste); rdgentregue = FindViewById<RadioGroup>(Resource.Id.rdgEntregue); rdgviva = FindViewById<RadioGroup>(Resource.Id.rdgViva); adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, enderecos); spinner.Adapter = adapter; spinner.ItemSelected += Spinner_ItemSelected; enviar = FindViewById<Button>(Resource.Id.button1); enviar.Click += enviar_Click; void GetEmails() { enderecos = new ArrayList(); enderecos.Add("Escolha um colaborador abaixo"); enderecos.Add("alexandre_bonfim@whirlpool.com"); enderecos.Add("alexandre_t_pires@whirlpool.com"); enderecos.Add("ana_carolina_simoes @whirlpool.com"); enderecos.Add("ana_claudia_s_belarmino@whirlpool.com"); enderecos.Add("andre_costa@whirlpool.com"); enderecos.Add("andre_l_teixeira@whirlpool.com"); enderecos.Add("andreza_a_valle@whirlpool.com"); enderecos.Add("anna_carolina_b_ferreira@whirlpool.com"); enderecos.Add("bruno_b_souza@whirlpool.com"); enderecos.Add("bruno_c_castanho@whirlpool.com"); enderecos.Add("bruno_s_lombardero@whirlpool.com"); enderecos.Add("caio_c_sacoman@whirlpool.com"); enderecos.Add("carla_sedin@whirlpool.com"); enderecos.Add("cassia_r_nascimento@whirlpool.com"); enderecos.Add("celia_r_araujo@whirlpool.com"); enderecos.Add("cesar_leandro_de_oliveira@whirlpool.com"); enderecos.Add("daniel_b_szortyka@whirlpool.com"); enderecos.Add("denis_caciatori@whirlpool.com"); enderecos.Add("elisabete_c_ferreira@whirlpool.com"); enderecos.Add("erick_c_senzaki@whirlpool.com"); enderecos.Add("erika_g_souza@whirlpool.com"); enderecos.Add("fabiana_monteiro@whirlpool.com"); enderecos.Add("fernando_v_santos@whirlpool.com"); enderecos.Add("gabriel_roveda@whirlpool.com"); enderecos.Add("herivelto_alves_jr@whirlpool.com"); enderecos.Add("jefferson_s_pecanha@whirlpool.com"); enderecos.Add("josiane_a_teles@whirlpool.com"); enderecos.Add("juliana_g_saito@whirlpool.com"); enderecos.Add("juliano_ventola@whirlpool.com"); enderecos.Add("leonardo_l_costa@whirlpool.com"); enderecos.Add("leonardo_r_silva@whirlpool.com"); enderecos.Add("lucas_m_santos@whirlpool.com"); enderecos.Add("luiz_perea@whirlpool.com"); enderecos.Add("norma_raphaeli@whirlpool.com"); enderecos.Add("patricia_f_prates@whirlpool.com"); enderecos.Add("priscila_l_dattilo@whirlpool.com"); enderecos.Add("priscila_m_konte@whirlpool.com"); enderecos.Add("reider_a_bernucio@whirlpool.com"); enderecos.Add("renato_occhiuto@whirlpool.com"); enderecos.Add("ricardo_a_fernandes@whirlpool.com"); enderecos.Add("ricardo_matos_campaneruti @whirlpool.com"); enderecos.Add("rogerio_pagotto@whirlpool.com"); enderecos.Add("ruben_c_anacleto@whirlpool.com"); enderecos.Add("taise_azevedo@whirlpool.com"); enderecos.Add("vinicius_marques_assis@whirlpool.com"); enderecos.Add("wanderly_t_limeira@whirlpool.com"); }// fim getEmails void Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; string toast = string.Format("Colaborador selecionado: {0}", spinner.GetItemAtPosition(e.Position)); Toast.MakeText(this, toast, ToastLength.Long).Show(); string texto = toast; } } void enviar_Click(object sender, EventArgs e) { try { RadioButton rdbgrupo1 = FindViewById<RadioButton>(rdgconquiste.CheckedRadioButtonId); RadioButton rdbgrupo2 = FindViewById<RadioButton>(rdgcrie.CheckedRadioButtonId); RadioButton rdbgrupo3 = FindViewById<RadioButton>(rdgviva.CheckedRadioButtonId); RadioButton rdbgrupo4 = FindViewById<RadioButton>(rdgentregue.CheckedRadioButtonId); if (rdbgrupo1.Selected == false || rdbgrupo2.Selected == false || rdbgrupo3.Selected == false || rdbgrupo4.Selected == false) { string excecao = "Ao menos um botão de cada campo deve ser selecionado e o comentário deve ser preenchido"; Toast.MakeText(this, excecao, ToastLength.Long).Show(); } else { String emailescolhido = spinner.SelectedItem.ToString(); String campocomentario = comentário.Text; string message = "Ao menos um botão de cada campo deve ser selecionado"; Toast.MakeText(ApplicationContext, message, ToastLength.Long).Show(); var email = new Intent(Android.Content.Intent.ActionSend); //send to email.PutExtra(Android.Content.Intent.ExtraEmail, new string[] { "" + emailescolhido }); //cc to email.PutExtra(Android.Content.Intent.ExtraCc, new string[] { "comite_clima_ti@whirlpool.com" }); //subject email.PutExtra(Android.Content.Intent.ExtraSubject, "SABIA QUE VOCÊ FOI RECONHECIDO?"); //content email.PutExtra(Android.Content.Intent.ExtraText, "Você foi reconhecido pelo(s) valor(es) de: " + rdbgrupo1.Text + " , " + rdbgrupo2.Text + " , " + rdbgrupo3.Text + " e " + rdbgrupo4.Text); email.PutExtra(Android.Content.Intent.ExtraText, "" + campocomentario); email.SetType("message/rfc822"); StartActivity(email); } } catch (Java.Lang.Exception ex) { string excecao = "Ao menos um botão de cada campo deve ser selecionado e o comentário deve ser preenchido"; Toast.MakeText(this, excecao, ToastLength.Long).Show(); } } } } A: How to show an exception message if the user doesn't check a radio button in Xamarin Android? You could use radioGroup.CheckedRadioButtonId to get the result whether a RadioGroup is check, upon empty selection, the returned value is -1. public int RadioGroupIsChecked(RadioGroup radioGroup) { //-1 means empty selection return radioGroup.CheckedRadioButtonId; } //When user doesn't check a radio button, show a Toast if (RadioGroupIsChecked(group) == -1 || RadioGroupIsChecked(group2) == -1 || RadioGroupIsChecked(group3) == -1 || RadioGroupIsChecked(group4) == -1) { string excecao = "Ao menos um botão de cada campo deve ser selecionado e o comentário deve ser preenchido"; Toast.MakeText(this, excecao, ToastLength.Long).Show(); }
[ "stackoverflow", "0021106632.txt" ]
Q: IF: command not found, windows cmd I am trying to run the following command using c++ IF exist C:/Users/Alacran/Desktop/ESP/001/ echo exists ELSE mkdir C:/Users/Alacran/Desktop/ESP/001/ && echo created but I am getting the error "IF: command not found" here is what I am doing in my c++ program //string id is defined .... stringstream ss; ss << "IF exist C:/Users/Alacran/Desktop/ESP/" << id.c_str() << "/ echo exists ELSE mkdir " << "C:/Users/Alacran/Desktop/ESP/" << id.c_str() << " && echo created"; string info = ss.str(); char* path = new char(info.length() + 1); strcpy(path, info.c_str()); system(path); string instance; cout << "Enter instance number" << endl; getline(cin, instance, '\n'); .... Thanks in advance A: Your command IF exist C:/Users/Alacran/Desktop/ESP/001/ echo exists ELSE mkdir C:/Users/Alacran/Desktop/ESP/001/ && echo created has syntax issues and logic issues. Try this instead: (md "C:\Users\Alacran\Desktop\ESP\001" 2>nul) && echo created || echo exists Also, instead of trying to issue such a command from C++, just create the directory via some appropriate API, for example using Boost filesystem.
[ "math.stackexchange", "0001750791.txt" ]
Q: Proving arbitrary intersection of closed intervals is nonempty I'm trying to prove the following statment: Let $\{I_{\alpha}\}_{\alpha\in\Gamma}$ be a collection of closed intervals, where $\Gamma\neq\emptyset$ is an arbitrary index set, such that $I_{\alpha}\cap I_{\beta}\neq\emptyset$ for every $\alpha,\beta\in\Gamma,$ $\alpha\neq\beta.$ Then $\bigcap_{\alpha\in\Gamma}I_{\alpha}\neq\emptyset.$ My attempt is based in consider that those intervals are compact because they are closed and bounded in $\mathbb{R}.$ Since intervals are compatc sets, so intersection is compact and satisfy the property of finite intersection, which implies intersection of all intervals is nonempty. Is this correct? Is there another way to prove this easier? I'd appreciate any kind of help. Thanks in advanced! A: I think "closed intervals" means intervals of the form $[a,b]$. The statement is false if you include half-intervals. (Consider the collection $\{[1,\infty),[2,\infty),[3,\infty),\ldots\}$.) A: We only know that $I_\alpha$ intersects $I_\beta$ for any two indices $\alpha$ and $\beta$. To get a non-empty intersection it is necessary to show that any finite intersection is of $I_\alpha$ is closed, and there we have to use that we have intervals (as the sides of a triangle show: they intersect pairwise but not all three at the same time). Denote $I_\alpha = [l_\alpha, r_\alpha]$ for every $\alpha$. Then $[l_\alpha, r_\alpha] \cap [l_\beta, r_\beta] \neq \emptyset]$ means exactly that $\max(l_\alpha, l_\beta) \le \min(r_\alpha, r_\beta)$ (draw a picture). Use this to show that finite intersections of these intervals are also non-empty. Then apply the fact that the family of intervals has the finite intersection property to get the full non-empty intersection.
[ "stackoverflow", "0021491504.txt" ]
Q: The two Strings don't update, keep returning "?" This is just a class file of my whole project. I've checked everyother class and I found that this was the culprit. It's supposed to take in the city and state that was parsed in another class(so you're left with city=Dallas and state=TX for example) but when those parameter are passed through, they don't update the private String state and private String city. I keep getting ?,? as the output from the toString method public class Address { private String city; private String state; public Address() { city="?"; state="?"; } public String getCity() { return city; } public String getState() { return state; } public void setState(String s) { //System.out.println(s); state=s; //System.out.println(state); } public void setCity(String c) { city=c; } public String toString() { String cityState=city+","+state; return cityState; } } Tester Class import java.io.*; import java.util.*; public class Assignment4 { public static void main (String[] args) { // local variables, can be accessed anywhere from the main method char input1; String inputInfo = new String(); String line = new String(), line2; //instantiate a Bank array Bank[] accounts = new Bank[10]; Bank bank1 = null; Scanner scan = new Scanner(System.in); int index = 0; // print the menu printMenu(); do // will ask for user input { System.out.println("What action would you like to perform?"); line = scan.nextLine().trim(); input1 = line.charAt(0); input1 = Character.toUpperCase(input1); if (line.length() == 1) {// matches one of the case statements switch (input1) { case 'A': //Add Bank System.out.print("Please enter the bank information:\n"); inputInfo = scan.nextLine(); bank1 = BankParser.bankParser(inputInfo); accounts[index] = bank1; index++; break; case 'B': //Display banks for (int i=0; i< index; i++) System.out.print(accounts[i].toString()); break; case 'Q': //Quit break; case '?': //Display Menu printMenu(); break; default: System.out.print("Unknown action\n"); break; } } else { System.out.print("Unknown action\n"); } } while (input1 != 'Q' || line.length() != 1); } /** The method printMenu displays the menu to a user**/ public static void printMenu() { System.out.print("Choice\t\tAction\n" + "------\t\t------\n" + "A\t\tAdd Bank\n" + "B\t\tDisplay Banks\n" + "Q\t\tQuit\n" + "?\t\tDisplay Help\n\n"); } } Bank.java class public class Bank { Address Address=new Address(); private String bankName; private String bankID; private Address bankAddress= new Address(); public Bank() { bankName="?"; bankID="?"; } public String getBankName() { return bankName; } public String getBankID() { return bankID; } public Address getBankAddress() { return bankAddress; } public void setBankName(String bName) { bankName=bName; } public void setBankID(String bID) { bankID=bID; } public void setBankAddress(String city, String state) { Address.setCity(city); Address.setState(state); } public String toString() { String bankInfo="\nBank Name:\t\t"+bankName+"\nBank ID: \t\t"+bankID+"\nBank address:\t\t"+bankAddress+"\n\n"; return bankInfo; } } BankParser.Java class public class BankParser { public static Bank bankParser(String lineToParse) { Bank bank=new Bank(); String delims="[/]+"; String[] primaryParse=lineToParse.split(delims); bank.setBankName(primaryParse[0]); bank.setBankID(primaryParse[1]); String[] secondaryParse=primaryParse[2].split("[,]"); //String city=secondaryParse[0]; //String state=secondaryParse[1]; bank.setBankAddress(secondaryParse[0], secondaryParse[1]); //System.out.println(secondaryParse[1]); return bank; } } A: public void setBankAddress(String city, String state) { Address.setCity(city); Address.setState(state); } Here is your problem, you did likely want to do public void setBankAddress(String city, String state) { bankAddress.setCity(city); bankAddress.setState(state); } instead.
[ "travel.stackexchange", "0000081171.txt" ]
Q: Personal Item On Spirit Airlines Is a laptop bag considered a personal item on Spirit Airlines? I know I can bring a small backpack but was not clear what a personal item represented. A: This video shows the sizer which apparently says a personal item is 16" x 14" x 12". Here's the relevant portion of a frame: I also found it on the Spirit site and it'll change to 18" x 14" x 8" for Travel April 4, 2017 and beyond. This is free and the "normal" carry on, max size 22" x 18" x 10" is paid.
[ "stackoverflow", "0014844021.txt" ]
Q: passenger error Please install the mysql2 adapter: `gem install activerecord-mysql2-adapter`, ruby 1.9.2 rails 2.3.8 i have a problem - i have Ubuntu 12.04 server and I am trying to host ruby on rails app on it. I have chosen passenger with apache. I have installed RVM and made gemset "ruby-1.9.2-p320@myapp" and it works. I have really old rails 2.3.8 app, which is just for archive for me and I dont have any time to update it. I have passenger error Please install the mysql2 adapter: 'gem install activerecord-mysql2-adapter' (no such file to load -- active_record/connection_adapters/mysql2_adapter) My "gem list": actionmailer (2.3.8) actionpack (2.3.8) activerecord (2.3.8) activerecord-mysql2-adapter (0.0.3) activeresource (2.3.8) activesupport (2.3.8) bundler (1.2.3) daemon_controller (1.1.1) fastthread (1.0.7) mislav-will_paginate (2.3.11) mysql2 (0.2.7) passenger (3.0.19) rack (1.1.6) rails (2.3.8) rake (10.0.3) rubygems-bundler (1.1.0) rubygems-update (1.8.25, 1.3.5) rvm (1.11.3.6) sqlite3 (1.3.7) sqlite3-ruby (1.3.3) thoughtbot-paperclip (2.3.1) will_paginate (3.0.4) I can using ruby script/console get to database records, so connection with database is established and it WORKS. Is there any ideas for solution? Thank you. If any extra info is needed, it will be provided asap. A: This was misconfiguration of Passenger and Apache from my part. Just follow these loveley tutorial and all will be OK: http://everydayrails.com/2010/09/13/rvm-project-gemsets.html And if you afterwards run into problems of UTF-8 errors for older rails apps, just read on that here: http://railsforum.com/viewtopic.php?id=42009
[ "stackoverflow", "0002152261.txt" ]
Q: Possible to fetch Facebook application API secret? I'm using FB.Connect.createApplication (http://developers.facebook.com/docs/?u=facebook.jslib.FB.Connect.createApplication) to create applications on the fly. The problem is that the method doesn't return the API secret (only the app ID and api key). This is a big problem. Does anyone know if it's possible to fetch this data provided you have the application ID and API key? Thanks A: Found out that what I'm trying to do is impossible. The next best solution is to create a child application, and make calls on its behalf (from the parent application).
[ "stackoverflow", "0031738458.txt" ]
Q: Why doesn't my couchbase view return data? I have created sample view in my couchbase 4.0 B version for windows. I also published my view. I am accessing it through java program, but not getting any result, but instead getting some error with json. Here is the full code of what I am doing. Created view: function (doc, meta) { if(doc.type && doc.type == "beer") { emit(doc.name, doc.brewery_id); } } My java code using it: package com.couch.base.simple; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import rx.Observable; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func1; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.view.AsyncViewResult; import com.couchbase.client.java.view.AsyncViewRow; import com.couchbase.client.java.view.Stale; import com.couchbase.client.java.view.ViewQuery; public class Client3 { public static void main(String[] args) { // getView("_design/dev_beer", "_view/by_name"); // getView( "_design/beer", "_view/by_name" ); getView( "_design/beer", "by_name" ); } public static ArrayList<AsyncViewRow> getView(String designDoc, String view) { Cluster cluster = CouchbaseCluster.create(); final Bucket bucket = cluster.openBucket("bucket-1"); ArrayList<AsyncViewRow> result = new ArrayList<AsyncViewRow>(); final CountDownLatch latch = new CountDownLatch(1); System.out.println("METHOD START"); bucket.async() .query(ViewQuery.from(designDoc, view).limit(20) .stale(Stale.FALSE)) .doOnNext(new Action1<AsyncViewResult>() { @Override public void call(AsyncViewResult viewResult) { if (!viewResult.success()) { System.out.println(viewResult.error()); } else { System.out.println("Query is running!"); } } }) .flatMap( new Func1<AsyncViewResult, Observable<AsyncViewRow>>() { @Override public Observable<AsyncViewRow> call( AsyncViewResult viewResult) { return viewResult.rows(); } }).subscribe(new Subscriber<AsyncViewRow>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable throwable) { System.err.println("Whoops: " + throwable.getMessage()); } @Override public void onNext(AsyncViewRow viewRow) { result.add(viewRow); } }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); }`enter code here` return result; } } Error in console while running this program: INFO: CoreEnvironment: {sslEnabled=false, sslKeystoreFile='null', sslKeystorePassword='null', queryEnabled=false, queryPort=8093, bootstrapHttpEnabled=true, bootstrapCarrierEnabled=true, boot strapHttpDirectPort=8091, bootstrapHttpSslPort=18091, boot strapCarrierDirectPort=11210, bootstrapCarrierSslPort=11207, ioPoolSize=4, computationPoolSize=4, responseBufferSize=16384, requestBufferSize=16384, kvServiceEndpoints=1, viewServiceEndpoints=1, queryServiceEndpoints=1, ioPool=NioEventLoopGroup, coreScheduler=CoreScheduler, eventBus=DefaultEventBus, packageNameAndVersion=couchbase-java-client/2.1.0 (git: 2.1.0), dcpEnabled=false, retryStrategy=BestEffort, maxRequestLifetime=75000, retryDelay=com.couchbase.client.core.time.ExponentialDelay@27ddd392, reconnectDelay=com.couchbase.client.core.time.ExponentialDelay@19e1023e, Jul 31, 2015 10:17:11 AM com.couchbase.client.core.node.CouchbaseNode$5 call INFO: Connected to Node 127.0.0.1 Jul 31, 2015 10:17:11 AM com.couchbase.client.core.config.DefaultConfigurationProvider$6 call INFO: Opened bucket bucket-1 METHOD START Jul 31, 2015 10:17:12 AM com.couchbase.client.java.view.ViewRetryHandler shouldRetry INFO: Received a View HTTP response code (400) I did not expect, not retrying. {"error":"bad_request","reason":"attachments not supported in Couchbase"} A: I was doing very silly mistake, I was creating the views on beer-sample bucket, but in code I was doing query on bucket-1 bucket, so was getting error. So please be sure that you are querying the same bucket on which the views are created. Thanks for all your support.
[ "ell.stackexchange", "0000040407.txt" ]
Q: Parsing: He was sure he would leave behind in his community, should he die Ever since Barry's funeral, Gavin had dwelled, with a sense of deep inadequacy, on the comparatively small gap that [A] he was sure [B] he would leave behind in his community, should he die. Looking at Mary, he wondered whether it would not be better to leave a huge hole in one person's heart. Had Barry not realized how Mary felt? Had he not realized how lucky he was? (The Casual Vacancy, J. K. Rowling) What does ‘leave behind’ mean in the context? Is there a blank [gap] after leave behind, coindexed with ‘comparatively small gap’? Are the he’s different: [A] Gavin, [B] Barry? Is this clause, ‘Should he die,’ the complement of ‘he was sure’? A: Yes, "leave behind" refers to the "gap" He would leave a gap behind. "should he die" is a condition. Treat it the same as "if he would die". I.E. If he would die, he would leave a gap behind. since "should he die" is a condition of "he would leave behind a gap", and since Barry is already dead (we know he's dead because he had a funeral), It doesn't make sense for He to refer to Barry. It refers to Gavin both times. A: Ever since Barry's funeral, Gavin had dwelled, with a sense of deep inadequacy, on the comparatively small gap that [A] he was sure [B] he would leave behind in his community, should he die. The phrase should he die is a conditional antecedent. It has the same funtion as an if-clause. We know this because the subject he and the modal verb should are inverted. "Should he ..." "Ever since Bary's funeral" and "with a sense of deep inadequacy" are adjuncts. We don't need them to understand the main meaning of the sentence. Let's ignore them for the time being. The sentence therefore means the same as: Gavin had dwelled on the comparatively small gap that he was sure he would leave behind in his community, if he died. Both ocurrences of he refer to the same person, Gavin: Gavin had dwelled on the gap that Gavin was sure that Gavin would leave behind in his community if he died. There is a relative clause in the sentence. Because of this there is an empty object position after "leave". It has the same indentity as the "comparatively small gap": Gavin dwelled on the comparatively gap(i) that [ he was sure that he would leave _____(i) behind in his community if he died ]. We can understand it like this: Gavin dwelled on the gap that [ he was sure he would leave (it) behind in his community if he died ].
[ "music.stackexchange", "0000002406.txt" ]
Q: What to check when buying a new electric guitar? I have been playing acoustic guitar for quite some time now. I'm not a beginner but neither am I pro. I'm now looking into buying an electric guitar. My questions are - What do I need to check/lookout for when trying out the guitars? What kind of amplifier should I go for? What are the other necessary items needed with an electric guitar? A: When it comes to buying your first electric guitar, you want to take your time, try not to rush into it. Once you have found a guitar that suits your intended playing style, and price range, there a few things it would be a good idea to check. The action: if the action of the strings is too high, it could make playing difficult and uncomfortable for you. If it is too low, you may experience the dreaded fret buzz. Make sure the neck is straight. A bent or warped neck is really not good. Quickly check the intonation: play a 12th fret harmonic, and then the 12th fret note. They should be at the same pitch. If they are not, that needs to be fixed. Check the tone and volume controls work, along with the pickup selector and possibly the tremolo, as Stuart suggested. Check every pickup works, and that it sounds clean. It should not be too hissy or crackly. Most decent guitar shops offer a free setup with each guitar purchase. Get one done anyway, even if the guitar seems fine. A well set up guitar is a joy to play, one with no setup at all can be an annoying and frustrating experience to play. With your first amp, I would recommend a small solid state amp. Again, as Stuart mentioned, Line 6, Marshall and Fender all market a very good range of beginner amps, with, in my opinion, The Line 6 Spider IV series being the most versatile and probably cheapest. In terms of other accessories, you need a cable (the amp does not come with one), a guitar strap, and picks. I would suggest getting a range of pick weights/thicknesses and find your preference, even if you already have a preferred pick when playing acoustic. I would also suggest a clip on chromatic tuner, so you can tune quickly. You may already have one if you play acoustic, but if not, get one, they are invaluable. Hope this helps! :) A: Don't spend too much money on a guitar. When you start playing electric, you'll have a hard time distinguishing between different guitars. Once you've been playing for a while, you'll be able to tell huge differences in the size of the neck, scale, pickups, body, neck joint, etc. But prior to having much experience, you won't be able to tell what it is you really want. So start cheap (relatively speaking). In the US $300 will get you a decent guitar and $450 will get you a nice guitar. There isn't much reason to spend more than about 500-600 for a first electric (if you think that doesn't qualify as "don't spend too much", I hear you, but you're in for a shock later in your guitar life). Don't worry about the intonation or action. You can have someone fix that stuff. However, you want to check that the guitar feels well constructed. Do the tone and volume pots move smoothly? Is the neck straight? Does the fretboard fit the neck well? Do the joints look well constructed and clean? Are the frets set cleanly in to the fretboard? In the lower price range, you can get a lot of variability in construction (you can in the upper range too, unfortunately, but not as much), so you want to make sure that your guitar is well built. Do not order a guitar sight unseen, play before buying. Think about who your favorite electric artists are and see what guitars they play. If they all play something similar, I'd look at that style of guitar for a first go around (a cheaper version, obviously). I'd plan on replacing any first guitar eventually. So don't worry too much about the decision. You will also need an amp and a guitar cord, maybe a tuner. It's also worth picking up a spare set of strings. For an amp, I disagree with the Line 6 recomendations. I've had a couple students go that route and they universally hate the sheap Line 6 stuff. The clean sounds are absolutely terrible. You can't really go wrong with Fender or Marshal, however, my absolute favorite starter amps that I recommend to all my students are the Vox Valvetronix. For under $200, these amps sound awesome and will grow with your playing for a lot longer than other stuff in the price range, in my opinion. Again, $200 might sound like a lot, but it's worth it (and it's not a lot, just ask my wife about the $4000 amp I keep bugging her about). A: First of all play it and make sure it feels good and suits your style. Check there are no buzzes and rattles from the fret board. Make sure all the switches and controls work. Check the tremelo works ok if it has one. Make sure the action is ok. Check the paintwork for any scratches etc. Try and buy from a reputable shop and all the above should have been taken care of. You will need a guitar, amplifier, strap, lead, and some picks. Try and get an amplifier with a clean and dirty sound on it. Line 6, Marshall, and fender all make some well priced versatile amplifiers. Take plenty of time selecting amps and guitars otherwise you will be back in the store in a few weeks looking for new gear.
[ "askubuntu", "0000859781.txt" ]
Q: How do I know which software downloads to trust? When I search for software in the Ubuntu Software Center, how do I know whether or not software is trustworthy to download? On Windows, I came to be careful about downloading just anything because it might be packaged with adware, or possibly even malicious code. For example, I found the Metadata Anonymization Tool (website here) in the software centre. A: All of the software on the Ubuntu Software Center is safe and is maintained / verified, reviewed / developed by known developers (either from Debian or Ubuntu) and that's the reason it is in the Ubuntu repositories. More risky business is when installing applications from third-party sources which is done by adding the Personal Package Archive (PPA) to your system. After a PPA is added it is trusted by the system and any updated software from that PPA will be updated automatically. Well, if some developer goes rogue and makes a malicious software then that application will come in as an update, if the particular PPA was added. Hence, adding PPAs should be done cautiously. Read more in the following excellent links. Which Ubuntu repositories are totally safe and free from malware? Are PPA's safe to add to my system and what are some "red flags" to watch out for? Is there any guarantee that software from Launchpad PPAs is free from viruses and backdoor threats? Case where the user compiles and installs using make/cmake Generally some libraries, custom compilers and customized applications which are system build and parameter dependent (need configure) are installed that way. Hence, usually these softwares come from known developers, researchers, scientists, companies, GNU developers, etc... However, exercise caution and use your experience while building softwares from source. Don't just blindly build any piece of code !
[ "math.stackexchange", "0002288217.txt" ]
Q: 2.8.2 Stephen Abbott : Absolute convergence for double series So here is the problem. Given absolute convergence for a double series (infinite sum over $|a_{ij}|$) , show the double series $(a_{ij})$ converges . The proof strategy is: 1) keep one index fixed - so given i is fixed we know the series over j converges absolutely to some $b_i$ i.e $\Sigma_j |a_{ij}| $ converges to $b_i$, so the actual series $\Sigma_j a_{ij}$ must converge to a $b'_i$. Also we know $b'_i \leq b_i$ (because $a_{ij} \leq |a_{ij}|$). Now if we knew $b'_i \geq 0$, then comparison test applies (2.7.4). And we are done (just have to take infinite sum over $b_i$). But - it is not obvious to me why $b'_i \geq 0$ (i know $b_i \geq 0$ for sure as its the limit of the absolute values). I am missing something obvious - HELP! Based on T(op?) Gunn's response, we have $|b'_i| <b_i$, so $|b'_i| \geq 0$ so comparison test claims $b'_i$ has absolute convergence - hence $b'_i$ has convergence. A: The comparison test can only be used if the terms of the series are nonnegative. Suppose the series $\sum_{i,j}|a_{ij}|$ converges. Let $b_{ij} = \max(a_{ij},0$) and $c_{ij} = \max(-a_{ij},0)$. Since $0 \leqslant b_{ij} \leqslant |a_{ij}|$ and $0 \leqslant c_{ij} \leqslant |a_{ij}|$ we can now apply the comparison test to conclude that $\sum_{i,j}b_{ij}$ and $\sum_{i,j}c_{ij}$ converge. Therefore, we have convergence of $$\sum_{i,j}a_{ij} = \sum_{i,j}(b_{ij} - c_{ij}) = \sum_{i,j}b_{ij} - \sum_{i,j}c_{ij} $$ Also be aware that convergence of a double series (to $S$) in the strictest sense is that for any $\epsilon >0$ there exists a positive integer $N$ such that for all $n,m > N$ we have $$\left|\sum_{i=1}^m \sum_{j=1}^n a_{ij} - S \right| < \epsilon$$ A: Suppose $ \sum_i \sum_j |a_{ij}|$ converges. Then for each $i$, $\sum_j |a_{ij}|$ converges. Hence $\sum_j a_{ij}$ converges. The key observation from here is the "Infinite Triangle Inequality": $$ \left\lvert \sum_{j = 1}^\infty a_{ij} \right\rvert \le \sum_{j = 1}^\infty |a_{ij}|. $$
[ "dba.stackexchange", "0000177624.txt" ]
Q: Is there Hypothetical-Set Aggregate Function equivalent to `ntile` in Postgres? Is there Hypothetical-Set Aggregate Function equivalent to ntile (or some other good solution) in Postgres? I have this query: select frctl ,* from (select * from d_al where not rtn is null and not fund_val is null ) dx ,lateral( select round(percent_rank(dx.fund_val) WITHIN GROUP (ORDER BY fund_val)::numeric , 6) AS frctl from d_al where gen_qtr_end_dt <= dx.gen_qtr_end_dt and not rtn is null and not fund_val is null ) x order by gen_qtr_end_dt_id, frctl The query produces periodic historical percentile ranks. Ranking a value in a certain period/date relative to the current period/date plus all the historical periods/dates (periods before it) time series-wise/chronologically. It works perfectly, except I want fractiles (i.e. the option to create deciles, quartiles, etc.) like ntile(#) does naturally. Do I have to build a case statement to fit the fractiles I want? For example, if I want ntile(4) (quartiles), do I have to build a case statement based off of 0, 0.25, 0.5,0.75,1. Then if I want ntile(10) (deciles), do I have to build a case statement based off of 0, 0.1, 0.2,0.3,0.4 ... etc? Or is there an ntile type Hypothetical-Set Aggregate Function I am missing? Helpful links: https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-HYPOTHETICAL-TABLE Percentile rank that takes sorted argument (or same functionality) in PostgreSQL 9.3.5 (In the link directly above the problem is a bit different, but very related.) The data: Big - efficiency is important, but not the focus of my question. Table d_al has three columns, two matter here: gen_qtr_end_dt - not unique, not null, type date fund_val - can be null, type numeric rtn - can be null, type numeric, not important here I have Postgres 9.6. PS - this query does all of the history, but my next step is to do a number of days rolling period look back (rather than all of the history). edit 1: Here is how I am solving it now (with a case statement as mentioned): I put the above query in an cte then... with pl as ( select x.pctl ,dx.fund_val , dx.rtn ,dx.gen_qtr_end_dt from (select * from d_al where not rtn is null and not fund_val is null ) dx ,lateral( select round(percent_rank(dx.fund_val) WITHIN GROUP (ORDER BY fund_val)::numeric , 6) AS pctl from d_al where gen_qtr_end_dt <= dx.gen_qtr_end_dt and not rtn is null and not fund_val is null ) x ) -- , f as( select gen_qtr_end_dt_id ,case when pl.pctl < 0.1 then 1 when pl.pctl < 0.2 then 2 when pl.pctl < 0.3 then 3 when pl.pctl < 0.4 then 4 when pl.pctl < 0.5 then 5 when pl.pctl < 0.6 then 6 when pl.pctl < 0.7 then 7 when pl.pctl < 0.8 then 8 when pl.pctl < 0.9 then 9 else 10 end frctl ,rtn ,fund_val ,* from pl order by gen_qtr_end_dt, frctl ...which is a bit cumbersome/rigid but doable if need be. edit 2: And here is a sample of the output from edit 1 above: frctl fund_val pctl gen_qtr_end_dt 1 -14.514 0 3/31/2001 2 -8.618 0.142857 3/31/2001 3 1.707 0.285714 3/31/2001 5 26.162 0.428571 3/31/2001 6 141.873 0.571429 3/31/2001 8 216 0.714286 3/31/2001 9 254 0.857143 3/31/2001 1 -15.237 0.071429 6/30/2001 1 -32 0 6/30/2001 3 -6.949 0.285714 6/30/2001 5 6.307 0.428571 6/30/2001 6 28.542 0.571429 6/30/2001 7 140.816 0.642857 6/30/2001 9 239 0.857143 6/30/2001 1 -47 0.043478 9/30/2001 1 -63.367 0 9/30/2001 2 -16.599 0.130435 9/30/2001 4 -6.087 0.347826 9/30/2001 6 31.425 0.565217 9/30/2001 7 47.137 0.608696 9/30/2001 8 150.678 0.73913 9/30/2001 8 200 0.782609 9/30/2001 10 1902.684 0.956522 9/30/2001 1 -246.545 0 12/31/2001 2 -18.731 0.125 12/31/2001 4 -0.043 0.375 12/31/2001 4 -6 0.34375 12/31/2001 5 9.285 0.46875 12/31/2001 6 43.519 0.59375 12/31/2001 7 111 0.65625 12/31/2001 8 154.573 0.78125 12/31/2001 10 1017.514 0.9375 12/31/2001 1 -23.678 0.095238 3/31/2002 4 2.229 0.357143 3/31/2002 5 14 0.428571 3/31/2002 5 17.689 0.452381 3/31/2002 6 67.245 0.595238 3/31/2002 7 130.604 0.642857 3/31/2002 8 156 0.761905 3/31/2002 8 179.399 0.785714 3/31/2002 9 213.756 0.833333 3/31/2002 10 855.2 0.928571 3/31/2002 1 -26.536 0.076923 6/30/2002 3 1.295 0.288462 6/30/2002 4 9 0.365385 6/30/2002 5 16.714 0.423077 6/30/2002 6 64.547 0.557692 6/30/2002 6 103.539 0.596154 6/30/2002 8 181.284 0.769231 6/30/2002 9 203 0.807692 6/30/2002 10 600.194 0.923077 6/30/2002 10 284.306 0.903846 6/30/2002 1 -85 0.016129 9/30/2002 1 -25.475 0.096774 9/30/2002 2 -20.394 0.129032 9/30/2002 4 2.551 0.33871 9/30/2002 6 102.395 0.564516 9/30/2002 7 113.453 0.612903 9/30/2002 8 168.205 0.725806 9/30/2002 9 248 0.854839 9/30/2002 10 800.551 0.935484 9/30/2002 10 460.067 0.903226 9/30/2002 edit 3: As it stands, the way I am doing it here is so slow it is unusable. The slow part is the query with percent_rank() in it. A: Try trunc(10 * pl.pctl) + 1, but as percent_rank returns 0 <= n <= 1 the maximum value will be 11 instead of 10. CUME_DIST is quite similar to PERCENT_RANK but returns 0 < n <= 1, thus you might switch to 1-cume_dist... (ORDER BY fund_val DESC) for the pctl calculation.
[ "stackoverflow", "0024389983.txt" ]
Q: sencha app build native without minify JS I want be able to build a native app, but without minifying the JS so I can debug it later confortably. Currently I'm executing: sencha app build native How can I be able to build without minifying JS files? Thanks A: For native build, you can only have testing option after upgrade to Sencha CMD 5.x, refer to http://docs.sencha.com/cmd/5.x/cmd_upgrade_guide.html Under Cordova / PhoneGap "These build profiles ensure that all of the “sencha app build” command variations are equivalent to previous releases. You will notice, however, that “native” is now a build profile instead of an environment (like “testing” or “production”). This means you can now do “sencha app build native testing” which was previously not possible." So, the command should be sencha app build native testing A: You need to use this command line instead: sencha app build testing That way, all JavaScript source files are bundled but not minified; and you could debug easily. See Sencha CMD 4 documentation for more details.
[ "stackoverflow", "0025048593.txt" ]
Q: Using bash to create a directory in HDFS if the directory does not exist I want to test whether a directory exists in the Hadoop Distributed File System (HDFS). I want to create the directory if it does not exist and do nothing otherwise. When I modify the code at http://jugnu-life.blogspot.com/2012/10/hadoop-fs-test-example.html: #!/bin/bash directory=/raw/tool/ if hadoop fs -test –d $directory ; then echo "Directory exists" else hadoop fs -mkdir $directory echo "Creating directory" fi I get the error: -test: Too many arguments: expected 1 but got 2 Usage: hadoop fs [generic options] -test -[defsz] <path> What am I doing wrong? A: Assuming you copied/pasted your example, the - before the d is incorrect. I copied the the command lines from your post, notice how the - before the day expands differently. $ echo -test | od -c 0000000 - t e s t \n $ echo –d | od -c 0000000 342 200 223 d \n
[ "stackoverflow", "0004130414.txt" ]
Q: How To Create a Custom UITableViewCell With Embedded Picture That Forces Other Table Rows Off Screen Ey guys, so I want to create a grouped table view which has the first row of the first section be a large image(take up 3/4ths of the screen). I want the other section and table rows to be just visible below this large picture. So I have created this custom cell that is extremely large, to hold this picture. It's dimensions are 320(W) x 340(H) pixels. Image's dimensions: 320(W) x 340(H) along with X:-10 Y:-11. Here is the code for the header part of my custom cell class: #import <UIKit/UIKit.h> @interface MainViewHeaderCell : UITableViewCell { UILabel *cellLabel; UIImageView *cellImage; } @property (nonatomic, retain) IBOutlet UILabel *cellLabel; @property (nonatomic, retain) IBOutlet UIImageView *cellImage; @end I specified the dimensions and customized my cell in Interface Builder. I connected the proper outlets and build and run, but the custom cell I made doesn't take up 3/4ths of the screen like the image does, resulting in my image going over the next section and next rows of my table. It seems that the custom cell only gets big enough to not force any other rows off the screen, thus the reason for the image overlapping the table rows. Do you guys have any ideas of what I can do to remedy this problem? A: Sounds like you've only set the height of the cell in IB. Make sure you've also implemented heightForRowAtIndexPath: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if ((indexPath.section == 0) && (indexPath.row == 0)) return 340.0; else return 44.0; }
[ "stackoverflow", "0035961723.txt" ]
Q: Mongoengine custom validation with modify I am trying to apply custom validation on a Mongoengine modify operation as seen below: class Form(Document): fields = ListField(EmbeddedDocumentField(Field)) def modify(self, *args, **kwargs): for field in self.fields: if not [field for field in self.fields if field.type == "email"]: raise ValidationError("Form must have an email field") super(Form, self).modify(**kwargs) def update_form(self, modify_kwargs): return self.modify(**modify_kwargs) However when I call update_form, the custom validation does not take the updated data into account in modify. Is there some sort of a pre-hook for doing this type of validation? A: You're verifying against the objects field attribute rather than kwargs. But make sure each field is an object that contains .type. You shouldn't be using the python reserved word type though. class Form(Document): fields = ListField(EmbeddedDocumentField(Field)) def modify(self, *args, **kwargs): if not [field for field in kwargs.get('fields', []) if field.type == "email"]: raise ValidationError("Form must have an email field") super(Form, self).modify(**kwargs) def update_form(self, modify_kwargs): return self.modify(**modify_kwargs)
[ "stackoverflow", "0017022251.txt" ]
Q: Hide/Show HTML.ActionLink using jQuery I am working on ASP.NET MVC3 application. In my razor view I use @HTML.ActionLink to implement delete functionality for my custom image gallery. However when I show enlarged image I want to hide this link, and when the user clicks it back to thumb size I want to show the link again. Here is my razor code: <span class="document-image-frame"> @if (image != null) { <img src="file:\\105.3.2.7\upload\@image.Name" alt="docImg" style="cursor: pointer;" /> @Html.ActionLink("Изтрий", "DeletePicture", new { documentImageID = image.Id }, new { @class = "delete" }) } </span> Then my jQuery script: $('.document-image-frame img').click(function () { $(this).parent().toggleClass("document-image-frame"); //$(this).parent().child('a').hide(); }) This part - $(this).parent().toggleClass("document-image-frame"); is working fine but I don't know how to access the actionlink in order to show-hide it. A: You can find the link like this: $(this).parent().find("a.delete").show(); // or .hide() I like to also use the class to specify the link to delete, in case you may want to add other links in the future and you want them to behave differently...
[ "ru.stackoverflow", "0000225424.txt" ]
Q: Зависимость height от widht (в %) Добрый вечер! Потихоньку начал осваивать CSS, поэтому прошу — сильно не пинайте, если вопрос глупый. :) Произвожу блочную верстку страницы, все вычисления размеров блоков ведутся в %. Проблема в следующем — поскольку при изменении формата разрешения (4:3 или 16:9) изменяется вычисление параметра widht, как для контейнера (контейнер у меня = 100%), так и для блока (=10%), то весь блок растягивается и превращается в прямоугольник, а мне нужны квадраты. Вопрос: что нужно сделать, чтобы параметр height вычислялся из widht и был ему равен? То есть как сделать зависимость height от widht, чтобы height подстраивался под widht, и тем самым высота блока была равна ширине и при этом параметр widht мог бы спокойно "гулять" в зависимости от формата экрана? Получается, height должен "гулять" вместе с widht... Ну как-то так. :) A: Use CSS to Specify the Aspect Ratio of a Fluid Element Creating Intrinsic Ratios for Video Адаптивные фоновые изображения (на русском) пример
[ "stackoverflow", "0041306535.txt" ]
Q: Vaadin layout expansion Using Vaadin 7, I'm trying to accomplish a layout similar to other questions asked here, yet with one major difference: I want my content layout to fill out the remaining space only if there is not enough content within. This will result in a layout such the the following: I also want the layout to be able to do the following: When I add more content, enough to fill the content layout area, and proceed to add more, the footer will stay in place, scrollbar appears and the content added after will be added below the footer. In addition to the first picture, adding enough content should result in the following layout: A: I don't know whether I understand your question correctly or not but lets try my code and see if it helps: final VerticalLayout layout = new VerticalLayout(); layout.setMargin(true); layout.setSpacing(true); layout.setStyleName("flow_visible"); final HorizontalLayout navBarLayout = new HorizontalLayout(); final VerticalLayout contentLayout = new VerticalLayout(); final VerticalLayout spacingLayout = new VerticalLayout(); final HorizontalLayout footerLayout = new HorizontalLayout(); String dummyText = "TDummy text"; navBarLayout.addComponent(new Label("Navigation bar")); navBarLayout.setStyleName("navbar"); navBarLayout.setWidth("100%"); contentLayout.setSizeFull(); contentLayout.setSpacing(true); Button addButton = new Button("Add more content", (Button.ClickListener) clickEvent -> { contentLayout.addComponent(new Label(dummyText), contentLayout.getComponentCount() - 2); }); contentLayout.addComponent(addButton); for (int i = 0; i < 6; i++) { contentLayout.addComponent(new Label(dummyText)); } spacingLayout.setSizeFull(); contentLayout.addComponent(spacingLayout); contentLayout.setExpandRatio(spacingLayout, 1f); footerLayout.addComponent(new Label("Footer")); footerLayout.setStyleName("footer"); footerLayout.setWidth("100%"); contentLayout.addComponent(footerLayout); layout.addComponent(navBarLayout); layout.addComponent(contentLayout); layout.setSizeFull(); layout.setExpandRatio(contentLayout, 1f); How this code works: http://i.imgur.com/1HH1wm7.gif
[ "stackoverflow", "0019367953.txt" ]
Q: What is the error with rake db:migrate? I tried executing this command rake db:migrate i keep getting the error: ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment rake aborted! You should not use the `match` method in your router without specifying an HTTP method. How can i fix this? A: If this is rails 4 you should use get or post instead of match in your routes file. For example, make the following changes to your config/routes.rb file: get 'your/:route' => 'your_controller#your_action' post 'your/:route' => 'your_controller#your_action'
[ "stackoverflow", "0029806080.txt" ]
Q: Numpy - constructing matrix of Jaro (or Levenshtein) distances using numpy.fromfunction I am doing some text analysis right now and as part of it I need to get a matrix of Jaro distances between all of words in specific list (so pairwise distance matrix) like this one: │CHEESE CHORES GEESE GLOVES ───────┼─────────────────────────── CHEESE │ 0 0.222 0.177 0.444 CHORES │0.222 0 0.422 0.333 GEESE │0.177 0.422 0 0.300 GLOVES │0.444 0.333 0.300 0 So, I tried to construct it using numpy.fromfunction. Per documentation and examples it passes coordinates to the function, gets its results, constructs the matrix of results. I tried the below approach: from jellyfish import jaro_distance def distance(i, j): return 1 - jaro_distance(feature_dict[i], feature_dict[j]) feature_dict = 'CHEESE CHORES GEESE GLOVES'.split() distance_matrix = np.fromfunction(distance, shape=(len(feature_dict),len(feature_dict))) Notice: jaro_distance just accepts 2 strings and returns a float. And I got a error: File "<pyshell#26>", line 4, in distance return 1 - jaro_distance(feature_dict[i], feature_dict[j]) TypeError: only integer arrays with one element can be converted to an index I added print(i), print(j) into beginning of the function and I found that instead of real coordinates something odd is passed: [[ 0. 0. 0. 0.] [ 1. 1. 1. 1.] [ 2. 2. 2. 2.] [ 3. 3. 3. 3.]] [[ 0. 1. 2. 3.] [ 0. 1. 2. 3.] [ 0. 1. 2. 3.] [ 0. 1. 2. 3.]] Why? The examples on numpy site clearly show that just two integers are passed, nothing else. I tried to exactly reproduce their example using a lambda function, but I get exactly same error: distance_matrix = np.fromfunction(lambda i, j: 1 - jaro_distance(feature_dict[i], feature_dict[j]), shape=(len(feature_dict),len(feature_dict))) Any help is appreciated - I assume I misunderstood it somehow. A: As suggested by @xnx I have investigated the question and found out that fromfunc is not passing coordinates one by one, but actually passess all of indexies at the same time. Meaning that if shape of array would be (2,2) numpy will not perform f(0,0), f(0,1), f(1,0), f(1,1), but rather will perform: f([[0., 0.], [1., 1.]], [[0., 1.], [0., 1.]]) But looks like my specific function could vectorized and will produce needed results. So the code to achieve the needed is below: from jellyfish import jaro_distance import numpy def distance(i, j): return 1 - jaro_distance(feature_dict[i], feature_dict[j]) feature_dict = 'CHEESE CHORES GEESE GLOVES'.split() funcProxy = np.vectorize(distance) distance_matrix = np.fromfunction(funcProxy, shape=(len(feature_dict),len(feature_dict))) And it works fine.
[ "stackoverflow", "0034339069.txt" ]
Q: parse string into substrings c# I've been given this string below. It's not something I can change either. I need to create a for-loop which goes through this string and creates a list of substrings based on each 'object'. Is there something in regex which would allow me to break this into the desired target? I'm not very familiar with parsing methods in C#. Advice would be greatly appreciated. Thanks Supplied STRING { [#HEADER_15618] = { { name = "Donuts", isEnabled = true, isWired = false, }, { name = "Test", isEnabled = true, isWired = false, }, }, } desired output List<string> strings = { "{ name = "Donuts", isEnabled = true, isWired = false, }", "{ name = "Test", isEnabled = true, isWired = false, }", } Keeping in mind that the number of items change change it's not always just two. And the number inside the #HEADER is not always the same. A: Okay, this is a kind of a hack solution. I'm sure there are better ways to handle it using Regex as such I would suggest you add a regex tag to your post to get some of the regex gurus in here. var strings = input.Split(new string[] { "= {", "}," }, StringSplitOptions.RemoveEmptyEntries) .Skip(1) .Select(x => x.Trim()) .Where(x => x.StartsWith("{")) .Select(x => x + " }") .ToList(); Start by splitting the string based on two strings. The first one gets rid of the header, the other splits the objects up. Next, skip the first one as it is the header which we don't want. Then find all entries that start with a { to get rid of the last few entries which we also don't want. Then we use another Select to append a } back on that was eaten by the string.Split(). Again, by no means is this an efficient solution, especially if the input string contains a lot of objects as it creates a lot of strings in the process of processing the input. Regex probably offers a better solution.
[ "stackoverflow", "0047332221.txt" ]
Q: JavaScript to detect what checkboxes and checked and perform action I have a jsp page with a checkbox declared like so <form:checkbox path="affProgramSessionList[${status.index}].programSessionDetailId" id="checkbox_${session.id}" data-id="${session.id}" value="${session.id}" /> it is contained within a for loop and basically a checkbox is displayed for each session. That all works fine and I have no issues. currently when a check box is checked this function is ran $("input[id*='checkbox_']").each(function () { $(this).click(function(){ var dataid = $(this).attr("data-id"); var divId = "fullAttendence_" + dataid; var divIdAttendee = "attendeeType_" + dataid; $('#' + divId).toggle(this.checked); $('#' + divIdAttendee).toggle(this.checked); }); }); This then results in some other checkboxes being checked and some divs that were hidden being shown. I am now adding in functionality for if someone had checked some check boxes and saved and comes back to the page then those check boxes will be checked. I have that part working but I can't get the function to run properly. I have the following if ($("input[id*='checkbox_']").is(':checked')) { var dataid = $(this).attr("data-id"); var divId = "fullAttendence_" + dataid; var divIdAttendee = "attendeeType_" + dataid; $('#' + divId).toggle(this.checked); $('#' + divIdAttendee).toggle(this.checked); } This function DOES get called as I tested it with a console.log. the issue is that var dataid = $(this).attr("data-id"); comes back as undefined Now my assumption right now is just that my new function to check for checked boxes and the other function that gets call are not working quite the same and my function doesn't know which check box was checked just that at least one was? any help is really appreciated. A: if ($("input[id*='checkbox_']").is(':checked')) { ... will filter out the first checked input and operate on that. If you want to iterate on all checkboxes, use this construct: $("input[id*='checkbox_']").each(function() { if ($(this).is(':checked')) { // do something } });
[ "stackoverflow", "0059789345.txt" ]
Q: Writing inside a .html using JQuery and an if Statement in Javascript I have a HTML with my Tic Tac Toe field. With several onlick's HTML (game.html): <table class="nes-table is-bordered is-centered" id="tttpattern"> <tbody> <tr> <td class="square" id="0.0" onclick="gameController.putScore('0.0')"></td> <td class="square" id="0.1" onclick="gameController.putScore('0.1')"></td> <td class="square" id="0.2" onclick="gameController.putScore('0.2')"></td> </tr> <tr> <td class="square" id="1.0" onclick="gameController.putScore('1.0')"></td> <td class="square" id="1.1" onclick="gameController.putScore('1.1')"></td> <td class="square" id="1.2" onclick="gameController.putScore('1.2')"></td> </tr> <tr> <td class="square" id="2.0" onclick="gameController.putScore('2.0')"></td> <td class="square" id="2.1" onclick="gameController.putScore('2.1')"></td> <td class="square" id="2.2" onclick="gameController.putScore('2.2')"></td> </tr> </tbody> </table> When I click on one of the onclick's, my code runs the putScore function inside my gameController.js. Inside this js I want to check if the used user_id inside my payload is the same as the player1 ID I get from my DB. If this is the case my programm should write an X in the square I clicked. But it doesn't. Does anybody got an Idea how I can write the X inside the square? putScore function (gameController.js) putScore: function (option) { gameModel.putScore(APP.route.param.gameID, {"field" : option}).then(function (data) { if (APP.payload.user_id === data.player1) { $("#" + data.field).text("X"); } else { $("#" + data.field).text("O"); } }).catch(function(e) {APP.logError(e)}); } Did I made any mistake? I think the important part is this: $("#" + data.field).text("X"); A: Is there a reason you aren't using option natively rather than complicating it using jquery? document.getElementById(option).innerHTML = "X"; Would do the trick here?
[ "stackoverflow", "0006948479.txt" ]
Q: Extras on Email Intent - Preferences XML I'm wanting to trigger an Email from my xml preferences screen and also attach a pre-defined subject and start the cursor in the Body field of the email application Here's what I've got so far <Preference android:title="Support" android:summary="Having a problem?"> <intent android:action="android.intent.action.VIEW" android:data="mailto:support@xxxxx.com" /> </Preference> Works great for triggering the email intent, but how would i go about accomplishing the others via xml? attaching the subject and all? A: You can use both mailto query parameters, as jondavidjohn says, and also intent extras, and you can mix and match them both. For example: <intent android:action="android.intent.action.VIEW" android:data="mailto:xxxxx@xxxxxxx.com?subject=this is a test subject"> <extra android:name="android.intent.extra.TEXT" android:value="This is a test" /> </intent> ...will allow you to set the body of an email as well as the subject. You can also specify the subject as an extra. This lets you use XML string resources rather than hardcoding, too: <extra android:name="android.intent.extra.SUBJECT" android:value="@string/email_subject" /> I just grabbed the Intent extra names from Intent.java; the email-related ones are all in a bunch together. I've only just discovered this and haven't done much testing, but this certainly seems to work with my GMail mail client. Also, if it's any help, I did have success using the "body" of the mailto: URI, e.g. mailto:example@example.com?subject=This%20is%20a%20subject&body=This%20is%20a%20body Don't know whether it helped that I url-encoded my mailto URL; I was just doing it through force of habit, coming from a web background. But that definitely works and sets a body in both GMail and K9 Mail apps.
[ "christianity.stackexchange", "0000009777.txt" ]
Q: Is there any biblical doctrine on how to avoid paranoia as a Christian under an Protestant framework? It seems clear to most who have read the Bible that it portrays Christians as a minority among a wicked world empire that desires nothing less than the extinction of Christ in his church. Jesus said narrow is the road that leads to life and ‘few’ find it. (Math 7:13) Jesus warned his disciples about the world hating them (John 15:18). Also, even within the church Christians are said to be persecuted by the legalists who are absorbed with the outward form of religion (Gal 4:28) while denying its internal power. (2 Tim 3:5) Considering this extreme level of conflict that the poor believer finds himself facing (at least according to the biblical proposal) how can he/she avoid spinning 'conspiracy theories' and falling into ‘they are out to get me’ mentality? Is there any doctrine about sanctification within an Protestant framework that would enable a Christian to eliminate paranoia in a hostile world? Five mainstream protestant theories of sanctification are conveniently found here (Wesleyan, Reformed, Pentecostal, Keswick, Augustinian-Dispensational). Please state the view that the post, is more or less, ascribing to and show how this view of sanctification would be applied to enable a Christian to manage paranoia in terms of a specific crisis and long term control. A: What can keep him calm? The ninth blessing: Blessed are ye, when men shall revile you, and persecute you, and shall say all manner of evil against you falsely, for my sake. Rejoice, and be exceeding glad: for great is your reward in heaven: for so persecuted they the prophets which were before you. You should be happy when you are persecuted for Christ's sake, not afraid. If you have faith in Christ, then you know that persecution is blessing and that God is more powerful than your persecutor. You don't feel a need to revenge or fear. So you are not in a danger of paranoia.
[ "stackoverflow", "0033029943.txt" ]
Q: CSS Adjustment Not Working for Some Divs I'm having trouble locating which CSS code to adjust in order to lower down the 2nd row of image thumbnails on this page: http://www.criminal-lawyers.com.au/ebooks-other-legal-resources. All thumbnails are under the class img_thumb. Initially, they were all scattered and I had to adjust the CSS codes related to this class in order to lower them down so that they rest exactly on the line. So I adjusted the top margin. But doing this only corrected the position of the thumbnails on the first row, but not the position of those on the second row. How do I adjust the 2nd row without affecting the first row? I could create a class for each thumbnail then adjust from there but is there a way for me not to do that? I'm thinking maybe I'm just missing out an important element. A: Increase the height to 185px of this div .bs_product.sk03_md { float: left !important; margin-right: 30px; margin-top: 100px !important; height: 185px; position: relative !important; display: block; direction: ltr !important; }
[ "craftcms.stackexchange", "0000036133.txt" ]
Q: Get first X paragraphs, then output the rest The below is code that works to only show the first paragraph, then show the rest. Is it possible to instead, show the first five or six paragraphs, then show the rest? {# Split paragraphs using a limit of 2 #} {% set paragraphs = block.body|split('</p>', 2) %} {# Get first paragraph and add the missing closing tag #} {% set firstParagraph = paragraphs|first ~ '</p>' %} {{ firstParagraph|raw }} {# The rest of the text is here, due to the limit in the split filter #} {{ paragraphs|last|raw }} Wordsmith works for this, but I'm unable to see a way to output the rest of the paragraphs. A: Seems like a huge hack to me but here's how to do it: {# Split paragraphs using with a limit of 3 #} {% set paragraphs = text|split('</p>', 3) %} {# Get an array containing the first 2 paragraphs, and convert it back to a string, adding missing closing tags #} {% set firstParagraphs = paragraphs|slice(0, -1)|join('</p>') ~ '</p>' %} {{ firstParagraphs|raw }} {# The rest of the text is here, due to the limit in the split filter #} {{ paragraphs|last|raw }} To adjust the number of paragraphs in your first group, just change the limit parameter of the join twig filter (this is a bit counter intuitive, see the Twig documentation to understand the logic).
[ "gaming.stackexchange", "0000144030.txt" ]
Q: How do I calculate necessary Delta-V for circularization burn? I'm trying to write a launch into orbit program. I could use wait until periapsis > x, but this seems inaccurate, because I can't start the burn at the exactly right time, because I don't know how much to burn. How do I calculate necessary Delta-V for circularization burn? A: So the only way to do this without just measuring the periapsis is with lots and lots of math. Luckily, Newton told us everything we need to know (at least for KSP), and Kepler helped out a bit too. But first, a note on how MechJeb handles circularizing an orbit. Or at least used to handle it in version 1.x, since I think it changed after integrating with maneuver nodes. When performing an automated ascent, MechJeb would wait until the apoapsis, and then fire the engine(s) in such a way as to maintain a vertical velocity of 0m/s. Given sufficient thrust (more than 1g local), the ship could "drag" the apoapsis along with it while also raising the periapsis. All MechJeb had to do was maintain a vertical speed of 0m/s until the difference between the apoapsis and periapsis was a few metres. Other than the slightly less than efficient burn pattern, this is how it's done in practice. But since you don't want to do it the easy way (really, the method described above is the easy way), the first thing you need to know is F=ma. That one equation governs everything in KSP. In english, the force acting on a body is equal to the mass of the body multiplied by the acceleration the body is under. But this equation is only the starting point, and actually isn't all that useful to us right now. More useful is a secondary form , which relates the velocity to the radius of the orbit (as measured from the centre of the planet, not the surface, as is commonly displayed). However, we still have that pesky mass term in there, but if we forget about the force acting on the object, then we can relate the first equation to the second: Now all we have to worry about is the acceleration, but we can calculate that, thanks to Newton's law of gravitation. First is the equation: But we don't need to know all that, and can simplify it significantly: Where μ is constant for each planetary body. We already know that a is 9.81m/s at the surface of Kerbin, and that the radius is 600km, so μ must equal 3.5316×1012 m3/s2, which is exactly what we find in the wiki. First sanity check complete. Now, given a target altitude, we merely need to work backwards in order to determine the desired orbital velocity. As an example, we'll work through a 100km orbit. First, determine the acceleration due to gravity at 100km: 7.2m/s2 seems low, but we'll go with it. With that, we can calculate the velocity: 2.25km/s closely agrees with what I've seen in game, so second sanity check complete. Now this won't tell you how much delta-V you'll need to circularize from a sub-orbital trajectory, but it will give you a lower bound at any point in the ascent simply by subtracting the current velocity from the orbital velocity. You'll know the true value required is something larger than this calculated value. However, this is all basically for nought. These calculations all assume perfectly circular orbits, which is never the case. If you just base your burns off of orbital velocity, your eccentricity could be wildly off, causing your spacecraft to plunge back into the atmosphere. You're better off using something similar to the approach MechJeb used in the older version. A: MechJeb's method (thrusting above prograde at apoapsis at the angle necessary to maintain a zero vertical velocity) is completely pragmatic. I wholeheartedly suggest that method. It is easy to implement in code, easy to execute manually, and, usually, only slightly inefficient. However, for anyone who actually does want to calculate the delta-v required to circularize, all you need is the equation for precise orbital speed: μ is the standard gravitational parameter for the planet (for Kerbin, μ equals 3.5316×1012 m3/s2; you can find values for the other bodies on the wiki). r is the distance from the center of the planet to the orbiting vessel at that point in the orbit (i.e. the vessel's altitude plus the radius of the planet). a is the semi-major axis of the orbit (the average of the apoapsis and periapsis altitudes, plus the radius of the planet). To determine the delta-v needed to circularize, just calculate the orbital speed in two cases: When you reach apoapsis in your current orbit. For a vessel in a circular orbit at that same altitude. Subtract the first one from the second one, and that's how much delta-v you need to apply at apoapsis. Example 1. You are in orbit around Kerbin with a periapsis of 75km and an apoapsis of 100km. You want to circularize at 100km. Your current orbit: μ = 3.5316×1012 m3/s2 r = altitude (100000) + Kerbin's radius (600000) = 700000 a = the average of 75000 and 100000, plus 600000 = 687500 Your velocity at apoapsis = SQRT(μ * (2/r - 1/a) ) = 2225.62643 m/s Your target orbit: μ = 3.5316×1012 m3/s2 r = 700000 a = 700000 Velocity of a 100km circular orbit = SQRT(μ * (2/r - 1/a) ) = 2246.13955 m/s The delta-v needed to circularize = 2246.13955 - 2225.62643 = 20.51312 m/s Note that this method works even if your periapsis altitude is negative. Example 2. You are ascending from the surface of Kerbin. You have an apoapsis of 75km and a periapsis of -250km. You want to circularize at 75km. Find your velocity at apoapsis: μ = 3.5316×1012 m3/s2 r = 675000 a = 512500 SQRT(μ * (2/r - 1/a) ) = 1890.25744m/s Find the velocity of a circular orbit at 75km altitude: μ = 3.5316×1012 m3/s2 r = 675000 a = 675000 SQRT(μ * (2/r - 1/a) ) = 2287.35655 m/s The delta-v needed to circularize = 2287.35655 - 1890.25744 = 397.0991 m/s Of course, if you are still in the atmosphere, you will lose some velocity to drag before you reach your apoapsis. This will lower your apoapsis and periapsis, which means you will need to spend some additional delta-v to restore your apoapsis to 75km. If, after you do that, your periapsis is still lower than -250km, you will need a bit more delta-v than this calculation shows. To be certain of the exact delta-v, wait until you reach 70km altitude before making the calculations.
[ "stackoverflow", "0007014532.txt" ]
Q: compiling java from within python I'm making an application where people can upload a java code and do stuff with it. The application i'm making is in Python. I was wondering whether it was possible to call the 'javac' command from within python, in order to compile the uploaded java file I'm also using JPype A: http://docs.python.org/library/subprocess.html But are you sure that allowing people to submit arbitrary code is a good idea? There are security aspects of that to consider...
[ "pt.stackoverflow", "0000375950.txt" ]
Q: Notice: Undefined index: identifier não acho o erro Está dando esse erro em várias parte da minha homepage. Mas não sei como resolver. Segue o erro e a linha de código correspondente. Notice: Undefined index: identifier in /home3/.../helpers-general.php on line 1112 Parte do código que contém a linha 1112: function foodbakery_set_transient_obj($transient_variable, $data_string, $time = 12) { if ( !isset($_COOKIE['identifier']) || $_COOKIE['identifier'] == '' ) { setcookie('identifier', uniqid(), time() + (86400 * 30), "/"); // 86400 = 1 day } $result = ''; $identifier = ''; $identifier = $_COOKIE['identifier']; // <==== linha 1112 $time_string = $time * HOUR_IN_SECONDS; if ( $data_string != '' ) { $result = set_transient($identifier . $transient_variable, $data_string, $time_string); } return $result; } A: Parece que o erro está na má interpretação do protocolo HTTP. O que a função setcookie faz é definir um cabeçalho de resposta Set-Cookie na resposta HTTP que será enviado ao cliente; enquanto $_COOKIE é uma lista de cookies existentes na requisição corrente. Em outras palavras, setcookie não altera o valor de $_COOKIE da própria requisição. A própria documentação oficial diz isso: Uma vez que os cookies foram setados, eles podem ser acessados no próximo carregamento da página através do array $_COOKIE. O erro então acontece quando a requisição atual não possui o cookie identifier. Você definirá o valor dele, mas esse valor existirá somente a partir da próxima requisição. Busque entender a diferença entre os cabeçalhos Set-Cookie e Cookie. O que você pode fazer é algo como: $identifier = $_COOKIE['identifier'] ?? null; // Versões anteriores à 7: // $identifier = isset($_COOKIE['identifier']) ? $_COOKIE['identifier'] : null; if (is_null($identifier)) { $identifier = uniqid(); setcookie('identifier', $identifier, time() + (86400 * 30), "/"); } // Use $identifier
[ "stackoverflow", "0007520320.txt" ]
Q: Problems with incomplete content in forwards from Outlook 2003 I've designed an HTML email (with no css, using tables, etc) that essentially consists of one outer table that contains 3 inner tables. The email renders fine in Outlook 2003 but when the user forwards it, only the top table is preserved in the forward. I've tested this in: Outlook 2003 (11.8330.8341) SP3 Outlook 2003 (11.5608.5606) Any idea what could be going on here? I don't really even know where to start. When I look at the HTML content of the forward, it is mangled beyond belief. UPDATE: There's a setting in MS Outlook 2003 under Tools > Options > Mail Format that says "Use microsoft office word 2003 to edit email messages". When the user does not have Outlook installed (and so the option is unchecked and grayed out) or when this is simply not checked, the forward appears correctly. However, checking this option brings up the composer in an instance of Word. Word completely screws up the HTML - creating actual data loss, not just formatting problems. UPDATE 2: Found this question. Although the answer didn't help me, anyone on this question might want to check it out: HTML E-mail Layouts Breaking When Forwarded - Make it Survive the Word 2003 HTML Editor QUESTION: What is happening here? Is there any information about certain HTML that Word will strip? I'm using only the most basic elements and styles I can find. What is happening here? A: Word stripped everything inside divs. I didn't do robust enough testing to determine whether or not this would be true of any div. I converted them to tables and everything now works.
[ "stackoverflow", "0025953958.txt" ]
Q: Printf not working I started to learn Java programming a while back, but never got very far, now I am starting back up again but have stumbled upon a problem. double c =0.000001; System.out.printf("%4.3f",c); When I type the above code into Eclipse it gives me an error message under printf saying change type c to object. What am I doing wrong? And sorry if this a dumb question however I have looked around the internet and have not found any answers. A: Your code works fine with autoboxing (double is autoboxed to Double under the hood). If you get this error message, it looks like that you're executing your code with a JVM version < 1.5 (without autoboxing).
[ "stackoverflow", "0040319520.txt" ]
Q: Correct terminology for Python imports When I import third-party code in Python, what is the correct terminology to use? For example, in from collections import Counter, what do I call collections and what do I call Counter? Is collections a "module"? Then what to call Counter? A: from collections import Counter Here, collections is indeed a module. Counter is a name. It can be a class, or function, or something else. It is simply a named thing, and you're bringing that name into your global namespace. In this particular case, Counter is a class. We are hinted to this by the fact that it starts with a capital letter. But a look at the documentation tells us for certain that it is a class. So we can say here that we are "importing the Counter class from the collections module".
[ "superuser", "0001094158.txt" ]
Q: What is the total storage for this server? Is it an external or internal? Please help to understand!!!! H/W path Device Class Description ======================================================== system Computer - /0 bus Motherboard /0/0 - memory 141GiB System memory /0/1 - processor Intel(R) Xeon(R) CPU E5645 @ 2.40GHz /0/2 - processor Intel(R) Xeon(R) CPU E5645 @ 2.40GHz /0/100 - bridge 5520 I/O Hub to ESI Port /0/100/1 - bridge 5520/5500/X58 I/O Hub PCI Express Root Port 1 /0/100/1/0 - scsi0 storage Smart Array G6 controllers /0/100/1/0/3.0.0 - generic P410i /0/100/1/0/0.0.0 /dev/sda disk 299GB - LOGICAL VOLUME /0/100/1/0/0.0.0/1 /dev/sda1 volume 268GiB - EXT3 volume /0/100/1/0/0.0.0/2 /dev/sda2 volume 11GiB - Extended partition /0/100/1/0/0.0.0/2/5 /dev/sda5 volume 11GiB - Linux swap / Solaris partition /0/100/1/0/0.0.1 /dev/sdb disk - 200GB LOGICAL VOLUME /0/100/1/0/0.0.1/1 /dev/sdb1 volume - 186GiB Linux filesystem partition /0/100/2 - bridge 5520/5500/X58 I/O Hub PCI Express Root Port 2 /0/100/3 - bridge 5520/5500/X58 I/O Hub PCI Express Root Port 3 /0/100/4 - bridge 5520/X58 I/O Hub PCI Express Root Port 4 /0/100/5 - bridge 5520/X58 I/O Hub PCI Express Root Port 5 /0/100/6 - bridge 5520/X58 I/O Hub PCI Express Root Port 6 /0/100/7 - bridge 5520/5500/X58 I/O Hub PCI Express Root Port 7 /0/100/7/0 - eth0 network NetXtreme II BCM5709 Gigabit Ethernet - /0/100/7/0.1 eth1 network NetXtreme II BCM5709 - Gigabit Ethernet /0/100/8 bridge - 5520/5500/X58 I/O Hub PCI Express Root Port 8 /0/100/8/0 - eth2 network NetXtreme II BCM5709 Gigabit Ethernet - /0/100/8/0.1 eth3 network NetXtreme II BCM5709 - Gigabit Ethernet /0/100/9 bridge - 7500/5520/5500/X58 I/O Hub PCI Express Root Port 9 /0/100/a - bridge 7500/5520/5500/X58 I/O Hub PCI Express Root Port 10 - /0/100/14 generic 7500/5520/5500/X58 I/O - Hub System Management Registers /0/100/14.1 - generic 7500/5520/5500/X58 I/O Hub GPIO and Scratch Pad Registers - /0/100/14.2 generic 7500/5520/5500/X58 I/O - Hub Control Status and RAS Registers /0/100/1c - bridge 82801JI (ICH10 Family) PCI Express Root Port 1 /0/100/1c.4 - bridge 82801JI (ICH10 Family) PCI Express Root Port 5 - /0/100/1c.4/0 generic Integrated Lights-Out - Standard Slave Instrumentation & System Support /0/100/1c.4/0.2 - generic Integrated Lights-Out Standard Management Processor - Support and Messaging /0/100/1c.4/0.4 bus - Integrated Lights-Out Standard Virtual USB Controller /0/100/1d - bus 82801JI (ICH10 Family) USB UHCI Controller #1 /0/100/1d.1 - bus 82801JI (ICH10 Family) USB UHCI Controller #2 /0/100/1d.2 - bus 82801JI (ICH10 Family) USB UHCI Controller #3 /0/100/1d.3 - bus 82801JI (ICH10 Family) USB UHCI Controller #6 /0/100/1d.7 - bus 82801JI (ICH10 Family) USB2 EHCI Controller #1 /0/100/1e - bridge 82801 PCI Bridge /0/100/1e/3 display - ES1000 /0/100/1f bridge 82801JIB (ICH10) - LPC Interface Controller /0/100/1f.2 storage - 82801JI (ICH10 Family) 4 port SATA IDE Controller #1 /0/101 - bridge Intel Corporation /0/102 bridge - Intel Corporation /0/103 bridge Intel - Corporation /0/104 bridge Intel - Corporation /0/105 bridge - 7500/5520/5500/X58 Physical Layer Port 0 /0/106 - bridge 7500/5520/5500 Physical Layer Port 1 /0/107 - bridge Intel Corporation /0/108 bridge - Intel Corporation /0/109 bridge Intel - Corporation /0/10a bridge Intel - Corporation /0/10b bridge Intel - Corporation /0/10c bridge Intel - Corporation /0/10d bridge Xeon 5600 - Series QuickPath Architecture Generic Non-core Registers /0/10e - bridge Xeon 5600 Series QuickPath Architecture System Address - Decoder /0/10f bridge Xeon 5600 Series - QPI Link 0 /0/110 bridge Xeon 5600 - Series QPI Physical 0 /0/111 bridge - Xeon 5600 Series Mirror Port Link 0 /0/112 - bridge Xeon 5600 Series Mirror Port Link 1 /0/113 - bridge Xeon 5600 Series QPI Link 1 /0/114 - bridge Xeon 5600 Series QPI Physical 1 /0/115 - bridge Xeon 5600 Series Integrated Memory Controller Registers - /0/116 bridge Xeon 5600 Series - Integrated Memory Controller Target Address Decoder /0/117 - bridge Xeon 5600 Series Integrated Memory Controller RAS - Registers /0/118 bridge Xeon 5600 - Series Integrated Memory Controller Test Registers /0/119 - bridge Xeon 5600 Series Integrated Memory Controller Channel 0 - Control /0/11a bridge Xeon 5600 Series - Integrated Memory Controller Channel 0 Address /0/11b - bridge Xeon 5600 Series Integrated Memory Controller Channel 0 - Rank /0/11c bridge Xeon 5600 Series - Integrated Memory Controller Channel 0 Thermal Control /0/11d - bridge Xeon 5600 Series Integrated Memory Controller Channel 1 - Control /0/11e bridge Xeon 5600 Series - Integrated Memory Controller Channel 1 Address /0/11f - bridge Xeon 5600 Series Integrated Memory Controller Channel 1 - Rank /0/120 bridge Xeon 5600 Series - Integrated Memory Controller Channel 1 Thermal Control /0/121 - bridge Xeon 5600 Series Integrated Memory Controller Channel 2 - Control /0/122 bridge Xeon 5600 Series - Integrated Memory Controller Channel 2 Address /0/123 - bridge Xeon 5600 Series Integrated Memory Controller Channel 2 - Rank /0/124 bridge Xeon 5600 Series - Integrated Memory Controller Channel 2 Thermal Control /0/125 - bridge Xeon 5600 Series QuickPath Architecture Generic Non-core - Registers /0/126 bridge Xeon 5600 - Series QuickPath Architecture System Address Decoder /0/127 - bridge Xeon 5600 Series QPI Link 0 /0/128 - bridge Xeon 5600 Series QPI Physical 0 /0/129 - bridge Xeon 5600 Series Mirror Port Link 0 /0/12a - bridge Xeon 5600 Series Mirror Port Link 1 /0/12b - bridge Xeon 5600 Series QPI Link 1 /0/12c - bridge Xeon 5600 Series QPI Physical 1 /0/12d - bridge Xeon 5600 Series Integrated Memory Controller Registers - /0/12e bridge Xeon 5600 Series - Integrated Memory Controller Target Address Decoder /0/12f - bridge Xeon 5600 Series Integrated Memory Controller RAS - Registers /0/130 bridge Xeon 5600 - Series Integrated Memory Controller Test Registers /0/131 - bridge Xeon 5600 Series Integrated Memory Controller Channel 0 - Control /0/132 bridge Xeon 5600 Series - Integrated Memory Controller Channel 0 Address /0/133 - bridge Xeon 5600 Series Integrated Memory Controller Channel 0 - Rank /0/134 bridge Xeon 5600 Series - Integrated Memory Controller Channel 0 Thermal Control /0/135 - bridge Xeon 5600 Series Integrated Memory Controller Channel 1 - Control /0/136 bridge Xeon 5600 Series - Integrated Memory Controller Channel 1 Address /0/137 - bridge Xeon 5600 Series Integrated Memory Controller Channel 1 - Rank /0/138 bridge Xeon 5600 Series - Integrated Memory Controller Channel 1 Thermal Control /0/139 - bridge Xeon 5600 Series Integrated Memory Controller Channel 2 - Control /0/13a bridge Xeon 5600 Series - Integrated Memory Controller Channel 2 Address /0/13b -bridge Xeon 5600 Series Integrated Memory Controller Channel 2 - Rank /0/13c bridge Xeon 5600 Series - Integrated Memory Controller Channel 2 Thermal Control /0/3 - scsi1 storage /0/3/0.0.0 /dev/cdrom disk - DVD A DS8A5LH /0/4 scsi3 storage - /0/4/0.0.0 /dev/sdc disk 15GB SCSI Disk - /0/4/0.0.0/1 /dev/sdc1 volume 14GiB Windows FAT volume A: generic P410i /0/100/1/0/0.0.0 /dev/sda disk 299GB /dev/sdb disk - 200GB /dev/sdc disk 15GB SCSI Disk Add it up... 299 + 200 + 15 = 514 GB. Across three separate (apparently) storage devices. From the info you've provided, it's impossible to know: Where the disks are located What type of disks they are (SSD, HDD, USB stick, etc.)
[ "stackoverflow", "0012803174.txt" ]
Q: Regex - dollar sign only matches if another character follows I know there are lot of threads about regex and dollar signs. But the one I read didn't help at all. I have this regex \b(foo bar\$)s?\b which should match foo bar$ and foo bar$s. The thing is, the regex only matches foo bar$s. For \b(foo bar)s?\b it works for foo bar and foo bars The dollar is part of a name, so I can't remove it. Any ideas? A: \b(foo bar\$)(s\b)? \b matches word boundaries, which are defined as a word-character followed by a non-word character, or vice-versa. $ is a non-word character so $\b<space> is a failed match since the \b is surrounded by non-word characters on both sides. The solution is to only look for the second \b if it's after an s.
[ "stats.stackexchange", "0000219576.txt" ]
Q: Derived Distribution from normal distribution \begin{align} X_{1} \sim N(\mu_{1} , \, \sigma_{1}^2 ) \\ X_{2} \sim N(\mu_{2} , \, \sigma_{2}^2 ) \end{align} Assume $X_{1}$ and $X_{2}$ are independent, what is the distribution of $ Y = 1/X_{1} + 1/X_{2} $ ? A: You will not be able to find a closed for solution, but there is a simple trick to see what is happening here. Notice first that \begin{align} Y := \dfrac{1}{X_1} + \dfrac{1}{X_2} = \dfrac{X_1 + X_2}{X_1 \cdot X_2} = \dfrac{W}{R} \end{align} In a second step, observe that it is well known that for independent normal variables, it holds that \begin{align} W = X_1 + X_2 \sim \mathcal{N}(\mu_1 + \mu_2, \sigma_1^2 + \sigma_2^2) \end{align} Also, again due to normality, one can rewrite for $Z_i \sim \mathcal{N}(0,1)$ the variable $X_i$ as \begin{align} X_i = \mu_i + \sigma_iZ_i \end{align} which leads to the conclusion that for $Z_i$ iid as above, \begin{align} R &= (\mu_1 + \sigma_1Z_1)(\mu_2 + \sigma_2Z_2) \\ &= \mu_1\mu_2 + \mu_1\sigma_2Z_2 + \mu_2\sigma_1Z_1 + \sigma_1\sigma_2Z_1Z_2 \\ \end{align} refer to the components of this expression as \begin{align} M&:= \mu_1\mu_2\\ N&:= \mu_1\sigma_2Z_2 + \mu_2\sigma_1Z_1\\ P&:= \sigma_1\sigma_2Z_1Z_2\\ \end{align} Clearly, $M$ is just a constant. $N$ is again normally distributed, and it is not hard to work out what its normal distribution looks like. $P$ is the most interesting expression, and turns out to be a linear combination of two iid-$\mathcal{X}^2$ with one degree of freedom. See this post for the details https://math.stackexchange.com/questions/101062/is-the-product-of-two-gaussian-random-variables-also-a-gaussian In summary, you effectively divide a normal by the sum of a constant, a normal, and a linear combination of chi-square variables.
[ "stackoverflow", "0053620882.txt" ]
Q: LSTM for 1D input - TensorFlow Exception i'm working on a 2-layer RNN (LSTM). I think i have successfully reshaped my train and test set but when i try to run the code, it stops with the Exception: Exception: When using TensorFlow, you should define explicitly the number of timesteps of your sequences. If your first layer is an Embedding, make sure to pass it an "input_length" argument. Otherwise, make sure the first layer has an "input_shape" or "batch_input_shape" argument, including the time axis. I tried several configuration, but no one works well. I don't know how to fix it.. Here it is the code where i create the model and reshape X_train and X_test X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], EMB_SIZE)) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], EMB_SIZE)) print 'Building model...' model = Sequential() model.add(LSTM(input_dim=EMB_SIZE, output_dim=100, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2], 1))) model.add(LSTM(input_dim=EMB_SIZE, output_dim=100, return_sequences=False,input_shape=(X_train.shape[1], X_train.shape[2], 1))) model.add(Dense(2)) model.add(Activation('softmax')) model.compile(optimizer='adam', loss='mse', metrics=['accuracy']) model.fit(X_train, Y_train, nb_epoch=5, batch_size = 128, verbose=1, validation_split=0.1) score= model.evaluate(X_test, Y_test, batch_size=128) print score any help is really appreciated! Thank you in advance <3 A: The number of units in the last layer defines the output shape of the model. The output shape must be the same shape as your targets (Y). Dense(2) -> Output shape = (None, 2) Dense(1) -> Output shape = (None, 1) Y_train -> Target shape = (15015,1) Whoa.... Keras 0.3.3? No wonder everything will be problematic.
[ "stackoverflow", "0005909396.txt" ]
Q: javap doesn't show the type of the Collection public static java.util.List getFoo(java.lang.String) The above method returns a List<String>, but the javap command returns the above (it doesn't show that the List is of type String). Is there a way to show the real type? A: The type is a lie :) Well seriously, that's just compile time information. The entries of the list are casted to Strings when fetched from the collection, the list itself in bytecode format acts as any standard plain old List. http://download.oracle.com/javase/tutorial/java/generics/erasure.html
[ "stackoverflow", "0018702070.txt" ]
Q: Create a Web application - What is the best and easiest way for a newbie in web programming? I have experience developing Desktop application (not Web application) using Visual Studio 2005 to 2010 and C#/VB.NET (Preferably C#). Now, I have to build a web application, this would be my first web application. This web application should be published in a Windows 2008 server machine which uses IIS as a webserver and it has a basic UI where user should select the tests to be passed which are: Pings localy and remotely to other machines Check if a port is opened in another machine (sockets) Check if a Windows service is started and running (status) on another machine. Check if an SQL instance is running and available on another machine The web application must support multilanguage The web application must support authentication, I mean, a login form where user enters username and password. As I am completely new in programming web applications, I have thought in using ASP.NET and C# under VS 2010 (NET Framework 4.0) because Visual Studio IDE is much easier to understand and rapidly program something and there a lot of things automated like login control, multilanguage is relatively easy to implement using resources files, there are specific objects already created to do pings (Ping object), to check a port using sockets (Sockect Object), to check if windows service is running (ServiceController object), etc... I think using other tools and programming languages like PHP or javascript will be more complicated to do those things for a person totaly new in programming web applications. So I think the best choice for me is ASP.NET. Also as far as I know those things are imposible to do using only plain HTML code, right? By taking into account that I have no experience in programing web applications (only desktop ones), my requirements and the technologies I have used, which is the best technology to use? A: Wrong. You can use plain HTML and use HTTP-Post form submit and CGI. But I wouldn't recommend it. When you already have Windows Server + SQL server given, go with ASP.NET. If for some odd reason, you find ASP.NET too unchallenging, you can read this: http://www.codeproject.com/Articles/9433/Understanding-CGI-with-C and go with plain HTML and CGI. If you find ASP.NET too boring and old, you can try something new with ASP.NET MVC3/4 :)
[ "stackoverflow", "0046366899.txt" ]
Q: How to use preferences in tornadofx. I am trying to use preferences in tornadofx . but documentation has very few about it. "unresolved references" to "preferences". From where to import preferences ? Please give and clear example. A: The Preferences API in JavaFX allows you store store arbitrary configuration options in an OS dependent way. It's a direct alternative to the config functionality in TornadoFX. This example retrieves and stores a value from the default Perferences node: class UserEditor : View("User Editor") { val name = SimpleStringProperty() init { preferences { name.value = get("name", "Default Name") } } override val root = form { fieldset { field("Name") { textfield(name) } } button("Save").action { preferences { put("name", name.value) } } } } TornadoFX merely facilitates easier access to the Preferences store available to JavaFX applications. You can also pass a specific node name as parameter to the preferences function.
[ "stackoverflow", "0020547417.txt" ]
Q: Directly call the return functor from bind1st and bind2nd The return values of bind1st and bind2nd are derived from unary_function. By calling them, I think they provide a function object that accepts one argument. But this maybe is wrong. Here is my code. template<typename _T> class fun: public std::unary_function<_T, _T> { public: _T operator()(_T arg1, _T arg2) const {return arg1 + arg2;} }; int main() { bind2nd(fun<int>(),10)(10); //My intention is to directly call the results of bind2nd } A lot of build errors occur. Why is this wrong? A: I believe a unary function operates on one parameter, while a binary function operates on two. For example T operator()(T arg1, T arg2) const {return arg1 + arg2;} is a binary_function. Change the template (and consider not using leading underscroes): template<typename T> class fun: public std::binary_function<T, T, T> // ^^^^^^--- well, it takes two parameters { public: T operator()(T arg1, T arg2) const {return arg1 + arg2;} }; So, fun is a binary functor. After you bind one of its arguments, e.g. by calling std::bind2nd(func<int>(),10) you will then have a unary function. This will not alter the type of the input to the bind2nd call.
[ "serverfault", "0000765663.txt" ]
Q: Static Public IP Address on Amazon EC2 I am running Ubuntu on a Amazon EC2 Server. I have a Public IP Address (52.38.20.76). I am unable to bind the public IP address to UDP Port: udp listen 52.38.20.76:3478: Cannot assign requested address So, I am trying to change ifconfig to show the Public IP Address instead of the Private IP Address. However, the network changes I have tried have not worked. Edit /etc/network/interfaces.d/eth0.cfg # The primary network interface auto eth0 #iface eth0 inet dhcp iface eth0 inet static address 52.38.20.76 netmask 255.255.255.0 gateway 172.31.32.1 dns-nameservers 8.8.8.8 8.8.4.4 The Gateway, I based on the results of a route -n command: Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 172.31.32.1 0.0.0.0 UG 0 0 0 eth0 172.31.32.0 0.0.0.0 255.255.240.0 U 0 0 0 eth0 Current ifconfig settings: eth0 Link encap:Ethernet HWaddr 06:01:36:ee:0f:0d inet addr:172.31.47.199 Bcast:172.31.47.255 Mask:255.255.240.0 inet6 addr: fe80::401:36ff:feee:f0d/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:9001 Metric:1 RX packets:8169768 errors:0 dropped:0 overruns:0 frame:0 TX packets:8126026 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:6143591550 (6.1 GB) TX bytes:6277418496 (6.2 GB) FYI, the Static IP Address (52.38.20.76) is done using Amazon's Elastic IP address. Anyone have a suggestion on how to change add the Public IP Address to the interfaces? A: This is not how EC2 works. All EC2 instances sit behind Amazon's NAT infrastructure. It is not possible to directly assign an EIP or other public IP directly to an EC2 instance.
[ "stackoverflow", "0054177996.txt" ]
Q: Stash/BitBucket prevents from committing if commit does not include JIRA number I'm not going to get a working solution but at least to get an answer if it is possible at all by Stash/Bitbucket. So my request is: We need to deploy some policy for ourselves in the company not to allow engineer to commit if commit comment does not contain (best does not begin with) JIRA issue number. For instance: TEST-1234 (Jira under which I'm doing a commit) Here's my code Thank you in advance! A: tl;dr use the add-on Yet Another Commit Checker to enforce a regex, e.g. [A-Z][A-Z]+-[0-9]+ .* Don't try to install your own script hooks via the on disk git repositories in Bitbucket Server. This can be done, but it's a) painful to audit (people have done this sort of thing, forgotten, and lost weeks trying to troubleshoot Bitbucket not knowing that git repos had been manually tampered with on disk) and b) dangerous, because Bitbucket Server intentionally applies a lot of specialised configuration and expects that end users are not messing around with the raw git repos on disk. For what it's worth, I work for Atlassian's Premier Support team and supported Bitbucket Server for two years. You will be much, much better off with Yet Another Commit Checker.
[ "stackoverflow", "0063587289.txt" ]
Q: Dviding numpy 2d array into equal sections I have a 30*30px image and I converted it to a NumPy array. Now I want to divide this 30*30 image into 9 equal pieces (imagine a tic-tak-toe game). I wrote the code below for that purpose but the problem with my code is that it has two nested loops and in python, that means a straight ticket to lower-performance town (specially for large number of datas). So is there a better way of doing this using NumPy and Numpy indexing? #Factor is saing that the image should be divided into 9 sections 3*3 = 9 (kinda like 3 rows 3 columns) def section(img , factor = 3): secs = [] #This basicaly tests if the image can actually get divided into equal sections if (img.shape[0] % factor != 0): return False #number of pixel in each row and column of the sections pix_num = int(img.shape[0] / factor) ptr_x_a = 0 ptr_x_b = pix_num -1 for i in range(factor): ptr_y_a = 0 ptr_y_b = pix_num - 1 for j in range(factor): secs.append( img[ptr_x_a :ptr_x_b , ptr_y_a : ptr_y_b] ) ptr_y_a += pix_num ptr_y_b += pix_num ptr_x_a += pix_num ptr_x_b += pix_num return np.array(secs , dtype = "int16"‍‍‍‍‍‍‍) P.S: Don't mind reading the whole code, just know that it uses pointers to select different areas of the image. P.S2: See the image below to get an idea of what's happening. It is a 6*6 image divided into 9 pieces (factor = 3) A: If you have an array of shape (K * M, K * N), you can transform it into something of shape (K * K, M, N) using reshape and transpose. For example, if you have K = M = N = 3, you want to transform >>> a = np.arange(81).reshape(9, 9) into [[[ 0, 1, 2], [ 9, 10, 11], [18, 19, 20]], [[ 3, 4, 5], [12, 13, 14], [21, 22, 23]], [[ 6, 7, 8], [15, 16, 17], [24, 25, 26]], ... ]]] The idea is that you need to get the elements lined up in memory in the order shown here (i.e. 0, 1, 2, 9, 10, 11, 18, ...). You can do this by adding the appropriate auxiliary dimensions and transposing: b = a.reshape(K, M, K, N) c = b.transpose(0, 2, 1, 3) d = c.reahape(-1, M, N) As a one-liner: a.reshape(K, M, K, N).transpose(0, 2 1, 3).reshape(-1, M, N) The order of the transpose determines the order of the blocks. The first two dimensions, 0, 2, represent the fact that your inner loop iterates the columns faster than the rows. If you wanted to arrange the blocks by column (iterate the rows faster), you could do c = b.transpose(2, 0, 1, 3) Reshaping does not change the memory layout of the elements, but transposing copies data if necessary. In your particular example, K = 3 and M = N = 10. The code above does not change in any way besides that. As an aside, your loops can be improved by making the ranges directly over the indices you want rather auxiliary quantities, as well as pre-allocating the output: result = np.zeros(factor * factor, pix_num, pix_num) n = 0 for r in range(0, img.shape[0], pix_num): for c in range(0, img.shape[1], pix_num): result[n, :, :] = img[r:r + pix_num, c:c + pix_num] n += 1
[ "stackoverflow", "0052443951.txt" ]
Q: Why does setting a MultiIndex dataframe with a Series give a column of NaNs? The following code illustrates my question: In [2]: idx = pd.date_range('1/1/2011', periods=5) In [3]: idx Out[3]: DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04', '2011-01-05'], dtype='datetime64[ns]', freq='D') In [4]: midx = pd.MultiIndex.from_product([['100', '200'], idx]) In [5]: midx Out[5]: MultiIndex(levels=[['100', '200'], [2011-01-01 00:00:00, 2011-01-02 00:00:00, 2011-01-03 00:00:00, 2011-01-04 00:00:00, 2011-01-05 00:00:00]], labels=[[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]]) In [6]: test_data = pd.DataFrame( 2*[[1, 2], [NaN, 3], [4, NaN], [5, 6], [7, 8]], index=midx, columns=['quant1', 'quant2'] ) In [7]: test_data Out[7]: quant1 quant2 100 2011-01-01 1.0 2.0 2011-01-02 NaN 3.0 2011-01-03 4.0 NaN 2011-01-04 5.0 6.0 2011-01-05 7.0 8.0 200 2011-01-01 1.0 2.0 2011-01-02 NaN 3.0 2011-01-03 4.0 NaN 2011-01-04 5.0 6.0 2011-01-05 7.0 8.0 In [8]: new_data = pd.DataFrame([11, 12, 13, 14, 15], index=idx, columns=['quant1']) In [9]: new_data Out[9]: quant1 2011-01-01 11 2011-01-02 12 2011-01-03 13 2011-01-04 14 2011-01-05 15 In [10]: test_data.loc['100', 'quant1'] = new_data In [11]: test_data Out[11]: quant1 quant2 100 2011-01-01 NaN 2.0 2011-01-02 NaN 3.0 2011-01-03 NaN NaN 2011-01-04 NaN 6.0 2011-01-05 NaN 8.0 200 2011-01-01 1.0 2.0 2011-01-02 NaN 3.0 2011-01-03 4.0 NaN 2011-01-04 5.0 6.0 2011-01-05 7.0 8.0 Why is the ['100', 'quant1'] data segment filled with NaNs instead of the numbers from new_data? I have found that using test_data.loc['100', 'quant1'] = new_data.values does work, but I would like to understand what makes Pandas do this. The sub-slice has the same dimensions and even the same Index as the new data, so even though I do suspect that this has to do with indexing/alignment, I don't really understand how or why - my expectation would be that as long as you're using the exact same index as what you're assigning to, that would work fine. A: Because Pandas aligns the indices of the receiving dataframe and the series providing new data. When it does, it fails to find the relevant index it is looking for. test_data.loc['100', 'quant2'] has an index entry of ('100', '2011-01-01') while new_data has an entry of '2011-01-01'. Those are not the same. Work Around 1 Use the values attribute and skip Pandas trying to align test_data.loc['100', 'quant1'] = new_data.values test_data quant1 quant2 100 2011-01-01 11.0 2.0 2011-01-02 12.0 3.0 2011-01-03 13.0 NaN 2011-01-04 14.0 6.0 2011-01-05 15.0 8.0 200 2011-01-01 1.0 2.0 2011-01-02 NaN 3.0 2011-01-03 4.0 NaN 2011-01-04 5.0 6.0 2011-01-05 7.0 8.0 Work Around 2 Use pd.concat to add an index level test_data.loc['100', 'quant1'] = pd.concat({'100': new_data}) test_data quant1 quant2 100 2011-01-01 11.0 2.0 2011-01-02 12.0 3.0 2011-01-03 13.0 NaN 2011-01-04 14.0 6.0 2011-01-05 15.0 8.0 200 2011-01-01 1.0 2.0 2011-01-02 NaN 3.0 2011-01-03 4.0 NaN 2011-01-04 5.0 6.0 2011-01-05 7.0 8.0
[ "security.stackexchange", "0000157852.txt" ]
Q: Why is generating Certificate Signing Request (CSR) supposed to be platform/machine specific? I've seen questions Is it true that certificates requested with a specific CSR can only be used on the machine where the CSR was generated? and CSR generation origin? and Generate CSR code on local machine ; I've also seen https://serverfault.com/questions/471289/must-csrs-be-generated-on-the-server-that-will-host-the-ssl-certificate - but these answers don't explain why majority of instructions for generating CSRs insist that the generation is performed on the specific platform/machine (e.g., look at https://knowledge.rapidssl.com/support/ssl-certificate-support/index?page=content&id=SO6506 or https://nz.godaddy.com/help/windows-generate-csr-for-code-or-driver-signing-certificate-7282 , and many others). If this were, as I assume, only for convenience sake (i.e., to use specific instructions/tolls available on a platform), it'd be understandable - but, e.g., the godaddy instructions (one of the links above) explicitly says, for a signing certificate, "It's important that you generate the CSR from your local machine and not from the web server you're using to host the file" - why would that matter? As far as I understand, all that matters is the possession of the private key. So - are these platform/box-specific instruction just for convenience sake and to ensure the security of the private key is not compromised while moving it between machines? A: Generating CSR is not platform specific, it's true as you say, that you only need the primary key and private key isn't tied to a specific machine. However, especially in a beginner's tutorial, there are a couple of reasons why this advice can be sensible: It limits the private key to just the machine that will use it. You won't have copies of the key lying around in machines that shouldn't have them, which can become another avenue of key leaks. It increases the likelihood that you'll be generating the key in the right format for the software that's going to use them. If you have openssl on the server, the key generation tool from openssl will generate pem files instead of pkcs12. While it's not too difficult to convert between formats, this reduces friction for less knowledgeable users. Telling people to generate keys at the place it's going to be used achieve these goals while being fairly simple for less knowledgeable customers to follow and produce good security for them.
[ "stackoverflow", "0061928521.txt" ]
Q: Rails: Find users where the user id is stored in a associated table I need to get a list of users from a associated table. From, for example 35 users, i need just these users, like below in the screenshot. class Book < ApplicationRecord has_many :applicants has_many :users, through: :applicants end class User < ApplicationRecord has_many :applicants has_many :books, through: :applicants end class Applicant < ApplicationRecord belongs_to :user belongs_to :book end How is the way to get the user records out of the applicants table? A: Users that have applicants: User.joins(:applicants).all Bonus: Users that have no applicants: User.left_outer_joins(:applicants).where(applicants: { id: nil })
[ "stackoverflow", "0033847744.txt" ]
Q: Calculate Type of the member in a table (Self Join/Case When or any other possible way) Here is the Table : If OBJECT_ID ('tempdb..##SelfCount') Is not null drop table #SelfCount create table #SelfCount (CanID int , CanType int) insert into #SelfCount (CanID, CanType) values (1,0), (2,0), (1,1), (2,1), (1,2), (1,2), (1,0) CanID CanType 1 0 2 0 1 1 2 1 1 2 1 2 1 0 I'm Expecting the result to be like this CanID Self Spouse Dependent 1 2 1 2 2 1 1 0/NULL --It doesn't matter if it's nUll or 0 I wrote this query select CanID, case When CanType = 0 then count(CanType) end as [self], case when CanType = 1 then count(CanType) end as [Spouse], Case When CanType = 2 then count(CanType) end as [Dependent] from #SelfCount Group by CanID, CanType But the Result Set is like this : CanID Self Spouse Dependent 1 2 NULL NULL 2 1 NULL NULL 1 NULL 1 NULL 2 NULL 1 NULL 1 NULL NULL 2 I've tried the Recursive method, If anyone could provide both Recursive as well as Set processing method, it'll be greatly appreciated. A: By including the CanType in the group by clause, you're getting a separate result row per distinct value of CanType (and CanId, since it's also contained in the group by clause). Instead, you should only have CanId in the group by clause, and apply different counts on case expressions: SELECT CanID, COUNT (CASE CanType WHEN 0 THEN 1 END) AS [Self], COUNT (CASE CanType WHEN 1 THEN 1 END) AS [Spouse], COUNT (CASE CanType WHEN 2 THEN 1 END) AS [Dependent], FROM #SelfCount GROUP BY CanID
[ "ru.stackoverflow", "0000450142.txt" ]
Q: Умные указатели (unique_ptr) и вызов функций-членов класса Собственно, ковыряю то, что написано в теме вопроса. Проблема возникла, когда я намеренно написал косячный код, а он, блин не упал. Собственно, код: #include <iostream> #include <memory> struct cdmem { cdmem() { std::cout << this << " :: cdmem::cdmem()" << std::endl; }; cdmem(const cdmem&) { std::cout << this << " :: cdmem::cdmem(const cdmem&)" << std::endl; }; cdmem(const cdmem*) { std::cout << this << " :: cdmem::cdmem(const cdmem*)" << std::endl; }; void testf() { std::cout << this << " :: testf()" << std::endl; }; ~cdmem() { std::cout << this << " :: cdmem::~cdmem()" << std::endl; }; }; int main() { std::unique_ptr<cdmem> pd(new cdmem); if(!pd) { std::cout << "\n ERR1 " << std::endl; return 1; } pd->testf(); auto pd1(std::move(pd)); pd->testf(); // Вот тут указатель уже нулевой return 0; } Вывод: 0x801c06058 :: cdmem::cdmem() 0x801c06058 :: testf() 0x0 :: testf() // this равен 0x0 0x801c06058 :: cdmem::~cdmem() Получается, что обращения к самому объекту не происходит? A: Это классическое UB, (обращение к более невалидному указателю), которое в данном случае выражается в нормальной работе. Это частный случай, который в другой ситуации (навскидку - виртуальный метод и вырубленная оптимизация) выстрелит вам в ногу. Не делайте так. A: Тут играет роль неопределённое поведение. #include <iostream> struct A { void foo() { std::cout << "A::foo()\n"; } }; int main() { A * a = nullptr; a->foo(); } Вывод: A::foo() Это работает в MinGW 5.1.0, но далеко не факт что это будет работать в других версиях и в других компиляторах.
[ "math.stackexchange", "0000841096.txt" ]
Q: uniform convergence of a functional sequence Is this sequence of functions $$f_n(x)=n^3x(1-x)^n$$ converges uniformly for $x\in[0,1]$. I need some help on this. A: Pointwise $f_{n}(x_0)\rightarrow 0 $ in $[0,1]$. So in order to show that it converges uniformly you just need to show that $$\sup_{x\in[0,1]}|f_n(x)-0|\rightarrow0$$ Now take the $x-$derivative $$f'_{n}(x)=n^3(1-x)^n-n^4x(1-x)^{n-1}=n^3(1-x)^{n-1}(1-x-nx)$$ You can easily find that the maximum point is $$x_{max}=\frac{1}{n+1}\ ,$$ so $$\sup_{x\in[0,1]}|f_n(x)-0|=\max_{x\in[0,1]}|f_n(x)|=|f_n(x_{max})|=n^3\frac{1}{n+1}\left(\frac{n}{n+1}\right)^n\sim \frac{n^2}{e}$$ that is divergent.
[ "stackoverflow", "0050954204.txt" ]
Q: How to read an Object in a Bucket with pluses and spaces in its name I've set up an event handler on a Bucket (in AWS). The event handler is supposed to read the file and process it. And I have a problem with the files that have space in their filename. When I upload a file with name + .txt, on the event handler I receive ++.txt. I understand that spaces are replaced with + but how can I differentiate between spaces and actual pluses? How can I read such a file on the event handler? A: S3 treats + and %20 identically. They are both represented internally as +. There is no differentiation. An unescaped space in a URI is a protocol violation, so your original upload must have had %20 for the space. foo+bar and foo%20bar refer to exactly the same object, whose key is foo bar. To get the correct object key from an event, you need this: const real_key = decodeURIComponent(event.s3.object.key.replace(/\+/g, ' ')); This is the result of a very old bug in S3, and the current incorrect behavior is too entrenched in existing libraries to allow it to be fixed without widespread collateral damage. Note also that %2B is not considered equivalent to + by S3, but since browsers don't eacape URLs that way, storing objects with %2B in the key does not interoperate well.
[ "stackoverflow", "0026907590.txt" ]
Q: Mysql update query with multiple order by? How can I get the following query to work as expected? MySQL gives me an error for the multiple ORDER BY UPDATE user_list SET user_code = $code WHERE user_id = $id AND country = $country AND ((d = $d) OR (c = $c ORDER BY c ASC LIMIT 1) OR (b = $b ORDER BY b ASC LIMIT 1)) The idea is the following: If there is a user with user_id = $id AND country = $country AND d = $d then SET user_code = $code If the above is false, then go and take THE 1st user ordered by c with user_id = $id AND country = $country AND c = $c and then do SET user_code = $code If the above is false, then go and take THE 1st user ordered by b with user_id = $id AND country = $country AND b = $b and then do SET user_code = $code A: You seem to want to update the row where the maximum value of c or b equals some value. You can do this with joins: UPDATE user_list u CROSS JOIN (select max(c) as maxc, max(b) = maxb from user_list where user_id = $id AND country = $country ) uu SET user_code = $code WHERE user_id = $id AND country = $country AND ((d = $d) OR (c = maxc and c = $c) or (b = maxb and b = $b)) A: You can use a nested sql to find the first user ordered by c or b, I modified your original command. UPDATE user_list SET user_code = $code WHERE user_id = $id AND country = $country AND ((d = $d) OR ( $c = (select c from user_list order by c asc limit 1)) OR ( $b = (select b from user_list order by b asc limit 1)))
[ "math.stackexchange", "0000286774.txt" ]
Q: $x \sim y \implies \log x \sim \log y$? Does $x \sim y \implies \ln x \sim \ln y$? I would have thought not, but the following has almost persuaded me otherwise: Assume $x \sim y.$ Does this imply that $$\tag{1}I = \frac{\int_{1}^{x}\frac{dt}{t}}{\int_{1}^{y}\frac{dt}{t}}\sim 1?$$ WLOG let $(y - x) = d, d > 0.$ At worst the difference of the integrals will be less than $(1/x)(y-x).$ Then $$ I = \frac{\ln x}{\ln x + (y-x)(\frac{1}{x})} = \frac{\ln x }{\ln x + \frac{y}{x} -1}. $$ Since $\frac{y}{x}\sim 1,$ $$ \lim_{x \to \infty} I = 1.$$ Is this correct (and if so is there a better proof)? Thanks. A: That follows only if $y\to \infty$ (or, more precisely, if $\log(y)$ does not tend to zero). Under this assumption (that you implicitely used in your last formula), we get: $$\frac{x}{y} \to 1 \implies \log\left(\frac{x}{y}\right)=\log(x)-\log(y)\to 0 \implies \frac{\log(x)}{\log(y)}\to 1$$ BTW, the last implication is not reversible, and the converse is not true. A: I took the question to mean: if $x(t)/y(t) \to 1$ as $t \to \infty$, does it follow that $\log(x(t))/\log(y(t))\to 1$ also? Then, as leonbloy hints, we can get a counterexample, $$ x(t) = 1+\frac{1}{t},\qquad y(t) = 1+\frac{1}{t^2} . $$ As the other answers show, there is no such counterexample if also $x(t) \to \infty$. A: By the definition, $y/x\to 1$ as $x\to\infty$, you get that for any $\epsilon>0$ there is an $N$ such that if $x>N$ $y/x\in (1-\epsilon,1+\epsilon)$, or $y\in ((1-\epsilon)x,(1+\epsilon)x)$. Taking the log of both sides gives you: $$\log (1-\epsilon) + \log x < \log y < \log(1+\epsilon) +\log x$$ Dividing by $\log x$, you get, for $x>N$: $$1+\frac{\log (1-\epsilon)}{\log x} < \frac {\log y}{\log x} < 1 + \frac{\log(1+\epsilon)}{\log x}$$ Now show that this implies your condition.
[ "stackoverflow", "0042327187.txt" ]
Q: Angular Filter based on Multiselect-Dropdown I use nya-bootstrap-select directive (http://nya.io/nya-bootstrap-select/) for a Multiselect-Dropdown ( Angular 1.5.8 ). Now I would like to filter a collection based on the selected options. Example: https://jsfiddle.net/mrtzdev/2z6xfo5w/18/ <ol id="dynamic-options" class="nya-bs-select" ng-model="model2" multiple > <li nya-bs-option="(key,value) in companyList" > <a>{{ value.name}}</a> </li> </ol> Filtered Collection: <tbody> <tr ng-repeat="client in clients | filter:{ name: model1.name, company: { name: model2.name } } "> <td>{{$index + 1}}</td> <td><em>{{client.name}}</em> </td> <td>{{client.designation}}</td> <td>{{client.company.name}}</td> </tr> </tbody> This obviously does not work for the multiselect. How can use a custom filter, to filter on multi-selected options ? A: I modified your fiddle and make it work. This filter is not good in dynamic handling but it will allow you to filter your data by the exact filter attribute name. View <tr ng-repeat="client in clients | filter:{ name: model1.name} | inArrayExact : { myArray: model2, searchKey: 'name', filterKey: 'company' }"> <td>{{$index + 1}}</td> <td><em>{{client.name}}</em> </td> <td>{{client.designation}}</td> <td>{{client.company.name}}</td> </tr> AngularJS custom filter App.filter('inArrayExact', function($filter){ return function(list, arrayFilter, element){ if((angular.isArray(arrayFilter.myArray) && arrayFilter.myArray.lenght > 0) && || angular.isObject(arrayFilter.myArray)){ var itemsFound = {}; angular.forEach(list, function (listItem, key) { angular.forEach(arrayFilter.myArray, function (filterItem) { if (angular.isDefined(filterItem[arrayFilter.searchKey]) && angular.isDefined(listItem[arrayFilter.filterKey]) && angular.isDefined(listItem[arrayFilter.filterKey][arrayFilter.searchKey])) { if (angular.isUndefined(itemsFound[key]) && listItem[arrayFilter.filterKey][arrayFilter.searchKey] == filterItem[arrayFilter.searchKey]) { itemsFound[key] = listItem; } } }); }); return itemsFound; } else { return list; } }; });
[ "russian.stackexchange", "0000019533.txt" ]
Q: Grammatical case of "каждый" I believe you should use the accusative for the expression 'each week' каждую неделю. However 'each car' is каждая машина in the nominative. Is this correct and, if so, why? A: No, it's not quite right. Depending on context каждую машину is correct and каждая неделя is correct as well. The thing is неделю in accusative stands for a period of time, so it's just should be memorized that in phrase like: Всю неделю я пил. всю неделю stands for whole week. Correspondingly каждую неделю stands for "every week" as a period during which something happens. However, in phrase like: Тут всегда происходит что-то новое, и каждая неделя особенная. каждая неделя is also translated as every week but the difference is that here we are not talking about something that happens every week but about the week as a concept itself - "every week is special". You confusion is quite understandable, because not all common periodization falls under the same pattern - it's all about nouns in feminine - well, strictly speaking it's just that for non-feminine accusative and nominative are coinciding. Here's more or less full list: Каждую секунду, каждую минуту (yep, same pattern) Каждую ночь (actually yep, it's just that ночь in accusative does not change) Каждый час, каждый день, каждый месяц, каждый год, каждый век (nope, well, again, in that sense that actually nominative and accusative are equivalent) By the way, another important form worth to mention is неделями - it translated "for weeks", so "он квасил неделями" is "he's been binging for weeks". Unlike the single accusative, this plural instrumental pattern works for a bigger set of nouns, so секундами, минутами, часами, годами, днями, месяцами, годами, столетиями, веками are also all valid.
[ "stackoverflow", "0006059032.txt" ]
Q: Rhino Mocks: stubbing value used in assertion? First my question, and then some details: Q: Do I need to stub the value of a property when making sure its value is used in a subsequent assignment? Details: I'm using Rhino Mocks 3.5's AAA syntax in MSpec classes. I've trimmed the code below to keep it (hopefully) easy to grok. *Not Stubbing _fooResultMock's Property Value:* [Subject("Foo")] public class when_foo { Establish context = () => { _fooDependencyMock.Stub(x => x.GetResult()).Return(_fooResultMock); _foo = new Foo(_fooDependencyMock); }; Because action = () => { _foo.Whatever(); }; It should_set_the_name_field = () => { _fooTargetMock.AssertWasCalled(x => x.Name = _fooResultMock.Name); }; } *Stubbing _fooResultMock's Property Value:* [Subject("Foo")] public class when_foo { Establish context = () => { _fooDependencyMock.Stub(x => x.GetResult()).Return(_fooResultMock); _fooResultMock.Stub(x => x.Name).Return(_theName); // _theName! _foo = new Foo(_fooDependencyMock); }; Because action = () => { _foo.Whatever(); }; It should_set_the_name_field = () => { _fooTargetMock.AssertWasCalled(x => x.Name = _theName); // _theName! }; } The important thing to my test is that the value found in _fooResultMock's Name property gets assigned to _fooTargetMock's property. So, does the first code block adequately test that, or is second code block (which stubs the value of _fooResultMock's Name property) necessary? Is the second block undesirable for any reason? A: Some questions, which will indicate the correct answer: Is _fooResultMock a PartialMock of a concrete class? If so, then if you don't stub Name, you'll get the value of the real class's Name property. If _fooResultMock is NOT a PartialMock and you don't stub it, you'll get the default for Name's type (probably null). What's _fooTargetMock? It's not specified anywhere in this test. Is that supposed to be _foo instead? I'm assuming that the results mock is not a partial mock; the main case for partial mocks is to isolate some methods of a single class from others in the same class (mocking a file-writing method, for instance, so you can test the calculation method that calls the file-writing method). In this case, the first code block is basically comparing null to null, whether the target mock got its Name field from the results mock or not. So, the second code block is a better test of whether an assignment occurred.
[ "apple.stackexchange", "0000012055.txt" ]
Q: Print to pdf with Adobe Reader I'm filling out a PDF form that doesn't work with Preview so I have to use Adobe Reader (ugh). After I fill out the form, I want to print it to PDF so that it is finalized. Unfortunately, Adobe disables the Mac print to PDF and tells me I have to save as PDF instead, but if I save as PDF then other people can still edit it. My current annoying solution is to print it to paper and then scan it. Anyone know a way to circumvent Adobe's disabling of the Mac print to PDF feature? A: I had the same problem and this is what I did after reading this question and answer I installed a network printer localhost, I chose HP Laserjet Series PCL 4/5 as the driver Print a document from adobe reader Open Terminal.app and type the following: sudo -s cd /private/var/spool/cups ls -lh Total 1048 -rw------- 1 root _lp 1.6K Jan 18 16:24 c00001 -rw------- 1 root _lp 1.7K Jan 18 16:40 c00002 Drwxrwx--- 10 root _lp 340B Jan 18 16:40 cache -rw-r----- 1 root _lp 259K Jan 18 16:23 d00001-001 -rw-r----- 1 root _lp 254K Jan 18 16:39 d00002-001 Drwxrwx--T 3 root _lp 102B Jan 18 16:39 tmp Looking at the timestamp and size, easy to see that d00001-001 and d00002-001 are the postscript files I just printed from Adobe Reader. pstopdf d00002-001 And you have a d00002-001.pdf file, Change the owner of this file then move this file out to desktop (replace username with your actual username) chgrp username d00002-001.pdf mv d00002-001.pdf ~username/Desktop And there you have it, without having to install any thirdparty pkg or drivers. You can remove the documents from the print queue manually. just tested on osx 10.11.1 el capitan A: Adobe Reader 10.x does go out of it's way to hide the normal print options from OS X but you can still get to them by clicking on the Printer... button at the bottom of the Adobe Print Dialog and clicking through the warning not to change things behind Adobe's back. I don't have a form like you mentioned in red, but try setting all the print options in Adobe to make your form appear as desired (with or without stamps, annotations, sticky notes and summaries, etc...) and then get to the Apple print dialog to attempt a print to PDF. If Adobe isn't preparing the file for print until after you hit print in the Adobe dialog - then your only recourse is faking it out by defining a new virtual printer. That way adobe is forced to send the data to the mac which will then pop it into a plainer PDF file for you with just the data filled out. I've not resorted to this, but CUPS-PDF and this tip on making it work with Snow Leopard's sandboxing security looks to be promising. I hope you don't have to resort to that hacky of a solution to save paper waste and time. A: As an alternative if you cannot get reader working, the process of printing and scanning your document seems laborious, have you thought of just a screenshot of the document? This should be digitally exactly the same, and you could even open it in preview and "Print to PDF" as you wanted. This would also be not editable in the fashion you said.
[ "stackoverflow", "0055366068.txt" ]
Q: How can i merge three ordered arrays in one ordered array? In O(n) My code should pick three arrays and return a combination of the three, the arrays can have different length. The code should do the combination in O(n). Example: a[] = {1,2} b[] = {1,4,5} c[] = {2,4,5,6} My result should be: d[] = {1,1,2,2,4,4,5,5,6} A: One approach (and I am sure there are many others) would be: Create the output array based on the sum of the input array lengths: int[] output = new int[a.length + b.length + c.length]; Create an index pointer for each of the input arrays: int aIndex = 0; int bIndex = 0; int cIndex = 0; Loop once for each position in the output array, and fill it with the lowest value at the current index of each input array (checking that we haven't used that array up): for(int outputIndex = 0; outputIndex < output.length; outputIndex++) { if (aIndex < a.length && (bIndex >= b.length || a[aIndex] <= b[bIndex]) && (cIndex >= c.length || a[aIndex] <= c[cIndex])) { output[outputIndex] = a[aIndex]; aIndex++; } else if (bIndex < b.length && (aIndex >= a.length || b[bIndex] <= a[aIndex]) && (cIndex >= c.length || b[bIndex] <= c[cIndex])) { output[outputIndex] = b[bIndex]; bIndex++; } else { output[outputIndex] = c[cIndex]; cIndex++; } } Edit: Here's my compiled and tested code: public class Join { public static void main(String[] args) { int[] a = {1, 2}; int[] b = {1, 4, 5}; int[] c = {2, 4, 5, 6}; int[] output = new int[a.length + b.length + c.length]; int aIndex = 0; int bIndex = 0; int cIndex = 0; for(int outputIndex = 0; outputIndex < output.length; outputIndex++) { if (aIndex < a.length && (bIndex >= b.length || a[aIndex] <= b[bIndex]) && (cIndex >= c.length || a[aIndex] <= c[cIndex])) { output[outputIndex] = a[aIndex]; aIndex++; } else if (bIndex < b.length && (aIndex >= a.length || b[bIndex] <= a[aIndex]) && (cIndex >= c.length || b[bIndex] <= c[cIndex])) { output[outputIndex] = b[bIndex]; bIndex++; } else { output[outputIndex] = c[cIndex]; cIndex++; } } } } Verified in debugger with a breakpoint at the end of the method.
[ "academia.stackexchange", "0000003503.txt" ]
Q: Is it true that it is easier to obtain a PhD in Europe than the US on average? I am a physics undergrad, and plan to pursue a PhD in mathematical physics (string theory?). I have heard from a lot of people, who have personally seen the research scenario at universities both in the US and Europe, that it is much easier to get a PhD from a European university, that it takes about 3-4 years in a good university in Europe, while more than 5 years in American universities. Another thing I have been told is that in Europe you get your PhD after 4 years atmost by default, even if you have not done any original research. Is it true? A: Short answer: No. Long answer: Determining the minimum bar for which a PhD can be awarded is a bad exercise. If you are merely working towards the minimum you will not successfully complete a PhD. One thing to note is that PhDs in the US tend to be open ended (to the extent you can continue to get funding) while in Europe they tend to have fixed durations. This means in Europe the bar comes whether you are ready or not while in the US you get to chose when you defend. Neither is easier, just different. A: The duration between US and Europe are not usually the same, mostly because in the US, you only need to have a Bachelor degree to enrol for a PhD (and you can get a Master during the PhD), while in Europe, it's usually required to have a Master degree before enrolling for a PhD. Since it can take two years to get a Master, you also need about 5 years after your Bachelor to get your PhD. I don't know if you always get your PhD after a number of years, no matter what, but the point in Europe is that a PhD is not necessarily an advantage on the market, with respect to a Master (at least, that's true in France), and is mostly required for working in Academia. In Academia, nobody cares that you have a PhD (because, well, almost everybody got one), so your publications, references, contacts, your CV in general will make a difference, not your degree. Hence, it might be possible that you can get the degree after a while, knowing that it's useless anyway if you haven't done any original research (although in many places, it's now required to have a given number of publications before being able to submit a PhD thesis). But I wouldn't claim in any way that it's a common practice, and I know several persons who have dropped (or been suggested to drop ...) their PhD program. As for your main question, I don't know if one can tell whether it's easier to get a PhD in Europe than in the US, because it's hard to define what is "easier". If your question is whether you can come to Europe, enrol to any PhD, just wait 4 years and get your PhD, the answer is no. A: Remember that Europe is a big place, comprised of lots of different countries. It doesn't make sense to talk about a European "PhD". The mechanism and typical PhD lengths between countries can be completely different. The next few comments relate to the UK PhD system. You don't get a PhD automatically after 4 years. I can introduce you to a few people who will testify to this! In the UK, a PhD doesn't involve a "taught" aspect. I believe that in the US, the first two(?) years typically involve examinations. In most Universities I'm familiar with, PhD students do not have a heavy teaching load. In my department, PhD students are allowed to take some tutorials/marking for additional money, but this is on top of there usual PhD working week. The number of hours a PhD student can work is closely monitored. In particular, it's incredibly rare for a PhD student to take undergraduate lectures. I believe it is common in the US for PhD student to run a lecture course.
[ "stackoverflow", "0030181160.txt" ]
Q: Multiple service processes (System.ServiceProcess.ServiceBase) in one Windows Service I've got two service processes (derived from System.ServiceProcess.ServiceBase) MyService1 and MyService2. I'm trying to run them both in the Main() of a Windows Service's Programm.cs. static void Main() { ServiceBase[] servicesToRun = { new MyService1(), new MyService2() }; ServiceBase.Run(servicesToRun); } In the OnStart methods of both MyService1 and MyService2 I write to a log file so I can tell they are running. The system builds fine and I can install the service. But only MyService1 runs. MyService2 doesn't do a thing (i.e. no start-up log entry). When I change the order in the array: ServiceBase[] servicesToRun = { new MyService2(), new MyService1() } only MyService2 runs. To try to get to the bottom of this, I'm using a little tool AndersonImes.ServiceProcess.ServicesLoader (https://windowsservicehelper.codeplex.com/) to get around the limitation that you cannot directly debug a windows service in Visual Studio. With this tool I can get both services MyService1 and MyService2 to start and run next to each other. But I still don't know why Windows is running only the first item in the ServiceBase[] servicesToRun array. Any ideas? A: I finally found the answer here: http://www.bryancook.net/2008/04/running-multiple-net-services-within.html. A well hidden resource, thanks 'bryan'! Hopefully this helps the next developer to save time... The explanation there around ServicesDependedOn isn't quite matching what I see in my project though. It's not about starting them but making sure they are started. Check out https://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.servicesdependedon%28v=vs.110%29.aspx as well. I don't need this because they do not depend on each other.
[ "stackoverflow", "0021735468.txt" ]
Q: Parse indented text tree in Java I have an indented file that I need to parsed using java, I need some way to place this in a Section class as shown below root root1 text1 text1.1 text1.2 text2 text2.1 text2.2 root2 text1 text1.1 text1.2 text2 text2.1 text2.2.2 I have the class for putting the indented stuff it looks like public class Section { private List<Section> children; private String text; private int depth; public Section(String t) { text =t; } public List<Section> getChildren() { if (children == null) { children = new ArrayList<Section>(); } return children; } public void setChildren(List<Section> newChildren) { if (newChildren == null) { children = newChildren; } else { if (children == null) { children = new ArrayList<Section>(); } for (Section child : newChildren) { this.addChild(child); } } } public void addChild(Section child) { if (children == null) { children = new ArrayList<Section>(); } if (child != null) { children.add(child); } } public String getText() { return text; } public void setText(String newText) { text =newText; } public String getDepth() { return depth; } public void setDepth(int newDepth) { depth = newDepth; } } I need some way to parse the file and place it in expected result which us a Section object which would look like below Section= Text="Root" Children Child1: Text= "root1" Child1: "text1" Child1="Text 1.1" Child2="Text 1.2" Child2: "text2" Child1="Text 2.1" Child2="Text 2.2" Children Child2: Text= "root2" Child1: "text1" Child1="Text 1.1" Child2="Text 1.2" Child2: "text2" Child1="Text 2.1" Child2="Text 2.2" Here is some code that I have started int indentCount=0; while(String text = reader.readline() { indentCount=countLeadingSpaces(String word); //TODO create the section here } public static int countLeadingSpaces(String word) { int length=word.length(); int count=0; for(int i=0;i<length;i++) { char first = word.charAt(i); if(Character.isWhitespace(first)) { count++; } else { return count; } } return count; } A: Surprisingly complex problem... but here's a pseudocode intialize a stack push first line to stack while (there are more lines to read) { S1 = top of stack // do not pop off yet S2 = read a line if depth of S1 < depth of S2 { add S2 as child of S1 push S2 into stack } else { while (depth of S1 >= depth of S2 AND there are at least 2 elements in stack) { pop stack S1 = top of stack // do not pop } add S2 as child of S1 push S2 into stack } } return bottom element of stack where depth is the # leading whitespaces. You might have to either modify or wrap the Section class to store the depth of the line. A: I added a parent pointer as well. Maybe the text can be parsed without it, but parent pointers make it easier. First of all, you need to have more constructors: static final int root_depth = 4; // assuming 4 whitespaces precede the tree root public Section(String text, int depth) { this.text = text; this.depth = depth; this.children = new ArrayList<Section>(); this.parent = null; } public Section(String text, int depth, Section parent) { this.text = text; this.depth = depth; this.children = new ArrayList<Section>(); this.parent = parent; } Then, when you start parsing the file, read it line by line: Section prev = null; for (String line; (line = bufferedReader.readLine()) != null; ) { if (prev == null && line begins with root_depth whitespaces) { Section root = new Section(text_of_line, root_depth); prev = root; } else { int t_depth = no. of whitespaces at the beginning of this line; if (t_depth > prev.getDepth()) // assuming that empty sections are not allowed Section t_section = new Section(text_of_line, t_depth, prev); prev.addChild(t_section); } else if (t_depth == prev.getDepth) { Section t_section = new Section(text_of_line, t_depth, prev.getParent()); prev.getParent().addChild(t_section); } else { while (t_depth < prev.getDepth()) { prev = prev.getParent(); } // at this point, (t_depth == prev.getDepth()) = true Section t_section = new Section(text_of_line, t_depth, prev.getParent()); prev.getParent().addChild(t_section); } } } I have glossed over some finer points of the pseudo-code, but I think you get the overall idea of how to go about this parsing. Do remember to implement the methods addChild(), getDepth(), getParent(), etc. A: An implementation in C# Based on this answer, I've created a C# solution. It allows for multiple roots and assumes an input structure like: Test A B C C1 C2 D Something One Two Three An example usage of the code would be: var lines = new[] { "Test", "\tA", "\tB", "\tC", "\t\tC1", "\t\tC2", "\tD", "Something", "\tOne", "\tTwo", "\tThree" }; var roots = IndentedTextToTreeParser.Parse(lines, 0, '\t'); var dump = IndentedTextToTreeParser.Dump(roots); Console.WriteLine(dump); You can specify the root indention (zero by default) and also the idention character (a tab \t by default). The full code: namespace MyNamespace { using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; public static class IndentedTextToTreeParser { // https://stackoverflow.com/questions/21735468/parse-indented-text-tree-in-java public static List<IndentTreeNode> Parse(IEnumerable<string> lines, int rootDepth = 0, char indentChar = '\t') { var roots = new List<IndentTreeNode>(); // -- IndentTreeNode prev = null; foreach (var line in lines) { if (string.IsNullOrEmpty(line.Trim(indentChar))) throw new Exception(@"Empty lines are not allowed."); var currentDepth = countWhiteSpacesAtBeginningOfLine(line, indentChar); if (currentDepth == rootDepth) { var root = new IndentTreeNode(line, rootDepth); prev = root; roots.Add(root); } else { if (prev == null) throw new Exception(@"Unexpected indention."); if (currentDepth > prev.Depth + 1) throw new Exception(@"Unexpected indention (children were skipped)."); if (currentDepth > prev.Depth) { var node = new IndentTreeNode(line.Trim(), currentDepth, prev); prev.AddChild(node); prev = node; } else if (currentDepth == prev.Depth) { var node = new IndentTreeNode(line.Trim(), currentDepth, prev.Parent); prev.Parent.AddChild(node); prev = node; } else { while (currentDepth < prev.Depth) prev = prev.Parent; // at this point, (currentDepth == prev.Depth) = true var node = new IndentTreeNode(line.Trim(indentChar), currentDepth, prev.Parent); prev.Parent.AddChild(node); } } } // -- return roots; } public static string Dump(IEnumerable<IndentTreeNode> roots) { var sb = new StringBuilder(); foreach (var root in roots) { doDump(root, sb, @""); } return sb.ToString(); } private static int countWhiteSpacesAtBeginningOfLine(string line, char indentChar) { var lengthBefore = line.Length; var lengthAfter = line.TrimStart(indentChar).Length; return lengthBefore - lengthAfter; } private static void doDump(IndentTreeNode treeNode, StringBuilder sb, string indent) { sb.AppendLine(indent + treeNode.Text); foreach (var child in treeNode.Children) { doDump(child, sb, indent + @" "); } } } [DebuggerDisplay(@"{Depth}: {Text} ({Children.Count} children)")] public class IndentTreeNode { public IndentTreeNode(string text, int depth = 0, IndentTreeNode parent = null) { Text = text; Depth = depth; Parent = parent; } public string Text { get; } public int Depth { get; } public IndentTreeNode Parent { get; } public List<IndentTreeNode> Children { get; } = new List<IndentTreeNode>(); public void AddChild(IndentTreeNode child) { if (child != null) Children.Add(child); } } } I've also included an method Dump() to convert the tree back to a string in order to better debug the algorithm itself.
[ "stackoverflow", "0035632849.txt" ]
Q: Kendoui bar chart set series on click of a button I am working with KendoUI bar chart. Please check this fiddle. In this fiddle I am setting series config at the design time. I want to add series to the chart at run time on click of a button. How can I add series to kendo chart on click of a button. Currently series is assigned at the design time, i want to do the same at the run time on click of a button. Code: <!DOCTYPE html> <html> <head> <base href="http://demos.telerik.com/kendo-ui/bar-charts/grouped-stacked-bar"> <style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style> <title></title> <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.112/styles/kendo.common-material.min.css" /> <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.112/styles/kendo.material.min.css" /> <script src="//kendo.cdn.telerik.com/2016.1.112/js/jquery.min.js"></script> <script src="//kendo.cdn.telerik.com/2016.1.112/js/kendo.all.min.js"></script> </head> <body> <div id="example"> <div class="demo-section k-content wide"> <div id="chart"></div> </div> <script> function createChart() { $("#chart").kendoChart({ title: { text: "World population by age group and sex" }, legend: { visible: false }, seriesDefaults: { type: "column" }, series: [{ name: "0-19", stack: "Female", data: [854622, 925844, 984930, 1044982, 1100941, 1139797, 1172929, 1184435, 1184654] }, { name: "20-39", stack: "Female", data: [490550, 555695, 627763, 718568, 810169, 883051, 942151, 1001395, 1058439] }, { name: "40-64", stack: "Female", data: [379788, 411217, 447201, 484739, 395533, 435485, 499861, 569114, 655066] }, { name: "65-79", stack: "Female", data: [97894, 113287, 128808, 137459, 152171, 170262, 191015, 210767, 226956] }, { name: "80+", stack: "Female", data: [16358, 18576, 24586, 30352, 36724, 42939, 46413, 54984, 66029] }, { name: "0-19", stack: "Male", data: [900268, 972205, 1031421, 1094547, 1155600, 1202766, 1244870, 1263637, 1268165] }, { name: "20-39", stack: "Male", data: [509133, 579487, 655494, 749511, 844496, 916479, 973694, 1036548, 1099507] }, { name: "40-64", stack: "Male", data: [364179, 401396, 440844, 479798, 390590, 430666, 495030, 564169, 646563] }, { name: "65-79", stack: "Male", data: [74208, 86516, 98956, 107352, 120614, 138868, 158387, 177078, 192156] }, { name: "80+", stack: "Male", data: [9187, 10752, 13007, 15983, 19442, 23020, 25868, 31462, 39223] }], seriesColors: ["#cd1533", "#d43851", "#dc5c71", "#e47f8f", "#eba1ad", "#009bd7", "#26aadd", "#4db9e3", "#73c8e9", "#99d7ef"], valueAxis: { labels: { template: "#= kendo.format('{0:N0}', value / 1000) # M" }, line: { visible: false } }, categoryAxis: { categories: [1970, 1975, 1980, 1985, 1990, 1995, 2000, 2005, 2010], majorGridLines: { visible: false } }, tooltip: { visible: true, template: "#= series.stack #s, age #= series.name #" } }); } $(document).ready(createChart); $(document).bind("kendo:skinChange", createChart); </script> </div> </body> </html> A: Ageonix gave a good answer! If you do not want to use a global variable for the chart options, you can get the chart instance from the DOM data-attribute, add the series to the chart instance and then tell the chart to redraw: var newseries = { name: "100+", stack: "Female", data: [654622, 625844, 784930, 844982, 900941, 39797, 72929, 118435, 118454] }; //Get the chart var chart = $("#chart").data("kendoChart"); //add the series chart.options.series.push(newseries); //refresh the chart chart.redraw(); Updated DOJO A: If you set the chart options as a global variable, you can then modify options.series and set it to your updated series data source in the button click event and call createChart() again, which will update (recreate) the chart with the updated series. Create a global chartOptions variable: var chartOptions = { title: { text: "World population by age group and sex" }, legend: { etc. etc. Then create the chart with the options stored in the variable: $("#chart").kendoChart(chartOptions); Finally, update the options.series with the updated data and recreate the chart: click: function() { chartOptions.series = updatedSeries; $("#chart").kendoChart(chartOptions); } I updated your Dojo and added a button that populates a new series on click. http://dojo.telerik.com/oTeTi/3
[ "stackoverflow", "0057345808.txt" ]
Q: Setting default value to dropdown of antdesign I am using dropdown of ant design but I am not able to active one value from the dropdown list. How to give default value? <Dropdown value="1st menu item" trigger={["click"]} className={css` background-color: #0a3150; height: 65px; display: flex; justify-content: space-between; padding: 0px 28px; font-size: 17px; color: white; align-items: center; cursor: pointer; `} overlay={this.renderList()} > <div> CLick me <Icon type="down" /> </div> </Dropdown> it do not take the value that is assigned. In renderList() <Menu> <Menu.Item>1st menu item</Menu.Item> <Menu.Item>2nd menu item</Menu.Item> <SubMenu title="sub menu"> <Menu.Item>3rd menu item</Menu.Item> <Menu.Item>4th menu item</Menu.Item> </SubMenu> <SubMenu title="disabled sub menu" disabled> <Menu.Item>5d menu item</Menu.Item> <Menu.Item>6th menu item</Menu.Item> </SubMenu> </Menu> //that value is in the list A: As it was pointed out, usually you will rather go for the Select component of antD in order to have a default value option. (https://ant.design/components/select) Nevertheless, it is possible to achieve what you want with the Dropdown component. You just need to make sure that you are saving the current selected value after you clicked on the item and render it instead of a static value: import React from "react"; import ReactDOM from "react-dom"; import "antd/dist/antd.css"; import "./index.css"; import { Menu, Dropdown, Icon } from "antd"; const menuItems = [ { key: 1, value: "1st menu item" }, { key: 2, value: "2nd menu item" }, { key: 3, value: "3rd menu item" } ]; const CustomDropdown = () => { const [selected, setSelected] = React.useState("Select value"); const handleMenuClick = e => { console.log(e.key); const newSelected = menuItems.find(item => item.key === parseInt(e.key, 10)) .value; setSelected(newSelected); }; const menu = ( <Menu onClick={handleMenuClick}> {menuItems.map(item => ( <Menu.Item key={item.key}>{item.value}</Menu.Item> ))} </Menu> ); return ( <Dropdown overlay={menu} trigger={["click"]}> <a className="ant-dropdown-link" href="#"> {selected} <Icon type="down" /> </a> </Dropdown> ); }; ReactDOM.render(<CustomDropdown />, document.getElementById("container")); Please see it working here: https://codesandbox.io/s/loving-beaver-nxbys
[ "stackoverflow", "0018263433.txt" ]
Q: How to pre-select a drop down option list based on the parent key I have two entities Rack and Server. Where each server has a foreign key to the parent rack. Currently I am assigning a server to a Rack, using a drop down list as follow inside the server create view. The Server Create action method looks as follow:- public ActionResult Create() { PopulateViewBagData(); return View(new ServerJoin() { IsIPUnique = true, IsMACUnique = true}); } Part of the server create view which include a drop down list to select the Rack as follow:- @model TMS.ViewModels.ServerJoin <div> <span class="f"> Rack</span> @Html.DropDownListFor(model =>model.Server.RackID, ((IEnumerable<TMS.Models.TMSRack>)ViewBag.Racks).Select(option => new SelectListItem { Text = (option == null ? "None" : option.Technology.Tag), Value = option.TMSRackID.ToString(), Selected = (Model.Server != null) && (option.TMSRackID == Model.Server.RackID) }), "Choose...") @Html.ValidationMessageFor(model =>model.Server.RackID) </div> What I am trying to implement , is that Inside the rack view I want to add a link to add a server, and to force the Rack drop down list to select the current Rack , something such as:- @HTML.Actionlink(“Create Server under this rack”, “Create”,”Server”, new {rackID = Model.RackID},null) But I am not sure how to force the drop down list to select the rackID passed, baring in mind that the user can still create a server without going to a Rack, the rackID will be null?? Any idea how to implement this ? BR A: Here is how you should do it: public ActionResult Create(int? rackID) { var model = new ServerJoin() { IsIPUnique = true, IsMACUnique = true}; if(rackID.HasValue) { model.RackID = rackID.Value; } PopulateViewBagData(); return View(model); } Then, in your View, you can use an if clause to replace the DropDownList with a Hidden input if the Model has a RackID. The ActionLink in your Rack View is correct.
[ "stackoverflow", "0022953913.txt" ]
Q: How to repaint my JTable So I have this application with a JTable in it. The JTable is inside of a JScrollPane and JScrollPane is painted on a JFrame. Now in my application I open a new windows to add a new row to that table and after I click a button to save the changes, the new window closes. Now I have tried adding these lines after the new window is closed: askTableInfo(); //a method to save the info in database to table and then save the table to variable 'table' table.repaint(); scrollPane.repaint(); And of course repaint(); by it self. But it still does not seem to update my table in the JFrame. What could be the issue here? public class AppWindow extends JFrame implements ActionListener { String user = ""; JLabel greetText = new JLabel(); JPanel panel = new JPanel(); JPanel panel2 = new JPanel(new GridLayout(1, 3)); JScrollPane scrollPane; JTable tabel; JButton newBook = new JButton("Add a book"); JButton deleteBook = new JButton("Remove a book"); JButton changeBook = new JButton("Change a book"); int ID; public AppWindow(String user, int ID) { this.ID = ID; this.user = user; setSize(500, 500); setTitle("Books"); setLayout(new BorderLayout()); greetText.setText("Hi "+user+" here are your books:"); add(greetText, BorderLayout.NORTH); askData(); panel.add(scrollPane); add(panel, BorderLayout.CENTER); panel2.add(newBook); panel2.add(deleteBook); panel2.add(changeBook); add(paneel2, BorderLayout.SOUTH); newBook.addActionListener(this); setVisible(true); } private void askData() { DataAsker asker = null; try { asker = new AndmeKysija(ID); } catch (SQLException e) { e.printStackTrace(); } table = asker.giveTable(); scrollPane = new JScrollPane(tabel); } public static void main(String[] args){ AppWindow window = new AppWindow("Name", 2); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == newBook){ new BookAdded(ID); panel.revalidate(); panel.add(scrollPane); panel.repaint(); repaint(); } } } A: Not the best method, but it will get you across the line... public AppWindow(String user, int ID) { this.ID = ID; this.user = user; setSize(500, 500); setTitle("Books"); setLayout(new BorderLayout()); greetText.setText("Hi "+user+" here are your books:"); add(greetText, BorderLayout.NORTH); JTable table = askData(); scrollPane.setViewportView(table); panel.add(scrollPane); add(panel, BorderLayout.CENTER); panel2.add(newBook); panel2.add(deleteBook); panel2.add(changeBook); add(paneel2, BorderLayout.SOUTH); newBook.addActionListener(this); setVisible(true); } private JTable askData() { DataAsker asker = null; try { asker = new AndmeKysija(ID); } catch (SQLException e) { e.printStackTrace(); } return asker.giveTable(); } public static void main(String[] args){ AppWindow window = new AppWindow("Name", 2); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == newBook){ new BookAdded(ID); JTable table = askData(); scrollPane.setViewportView(table); } } What you should be doing is creating a new TableModel from the results of AndmeKysija, AndmeKysija should have idea or concept of the UI. You would then simply need to use JTable#setModel to update the view... Swing uses a varient of the Model-View-Controller paradigm
[ "math.stackexchange", "0001218329.txt" ]
Q: Scale invariant Image Moments - not scale variant? I came across a problem working with image moments [1]. It is stated that $\eta_{ij} = \frac{\mu_{ji}}{\mu_{00}^{k}}$ where $k = 1 + \frac{i+j}{2}$ is scale invariant. However, if I try to reproduce this, it does not appear scale invariant at all. Consider a simple example: In a binary image, we calculate $\eta_{20}$ of a 2x2 block of 4 pixels: ☐☐ ☐☐ $\mu_{20} = 0.5^2 + 0.5^2 + (-0.5)^2 + (-0.5)^2 = 4 \cdot 0.25 = 1$ $\mu_{00} = 4$ $k = 1 + \frac{2+0}{2} = 1+1 = 2$ $\eta_{20} = \frac{1}{4^2} = \frac{1}{16} = 0.0625$ Now, let's scale this block by the factor two: ☐☐☐☐ ☐☐☐☐ ☐☐☐☐ ☐☐☐☐ $\mu_{20} = 4 \cdot 1.5^2 + 4 \cdot 0.5^2 + 4 \cdot (-0.5)^2 + 4 \cdot (-1.5)^2 = 8 \cdot 2.25 + 8 \cdot 0.25 = 18 + 2 = 20$ $\mu_{00} = 16$ $k = 1 + \frac{2+0}{2} = 1+1 = 2$ $\eta_{20} = \frac{20}{16^2} = \frac{20}{256} = 0.078125$ Why do we have a different result after scaling the object if $\eta_{ij}$ is supposedly scale invariant? Is there any formal proof of the scale invariance of $\eta$? [1] https://en.wikipedia.org/wiki/Image_moment A: The invariance is exact in the continuous domain. Your problem here is how you scale, which is limited by the discrete grid. Scaling by a factor 2 of your original 4 squares would result in 4 squares, centered at (-1,-1), (-1,1), (1,-1) and (1,1), each with a weight of 4: $$ \mu_{20} = 4 \cdot 1^2 + 4 \cdot 1^2 + 4 \cdot (-1)^2 + 4 \cdot (-1)^2 = 16 $$ $$ \mu_{00} = 4 \cdot 4 = 16 $$ $$ \eta_{20} = \frac{16}{16^2} = 0.0625 $$ On the discrete grid, the invariances are approximate.
[ "pt.stackoverflow", "0000083080.txt" ]
Q: Javascript - Populando um campo com parágrafo Estou elaborando um javascript para popular uma caixa de texto, porém me deparei com uma situação que está me gerando dificuldade. Preciso popular com essa mensagem por exemplo: TESTE TESTE TESTE Porém não estou conseguindo trazer as quebras de linha quando populo o campo, tentei com /n,<br>, </ br>, vbCrLf, porém não obtive êxito. Alguém poderia me ajudar. Ressaltando que minha caixa de texto em html está assim: <td colspan="2"> <textarea id="teste" class="CaixaTexto" runat="server" style="width: 600px; height: 90px;" cols="97" rows="5"></textarea> </td> Att, A: Usa .replace(/\r?\n/g, '<br />'), exemplo: var txtBox = $('textarea'); txtBox.keydown(function(e){ var that = this; setTimeout(function(){ var html = that.value.replace(/\n/g,"<br/>"); $("div").html(html); },10); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea></textarea> <div>
[ "stackoverflow", "0027313400.txt" ]
Q: Copy data from a JSON file to Redshift using the COPY command I'm trying to load a JSON file into Redshift using the COPY command together with a JSONPath. From what I understood, for each record in the JSON file, the COPY command generates one record to SQL. I need to generate multiple records to SQL from one record in JSON, but I am unclear how to do that. Here is an example. Say we have following JSON file: { { "id": 1, "value": [1, 2, 3, 4], "other": "ops" }, { "id": 2, "value": [5, 6, 7, 8] } } I want to generate following rows to store in SQL: id value 1 1 1 2 1 3 1 4 2 5 2 6 2 7 2 8 What the should the JSONPath file should look like? Is it doable or not? In a related SO post, the solution is to somehow generate data with right schema before it loading into Redshift. I could preprocess the JSON file to flatten it out somehow and store it back to S3. But that complicates things a lot. Another related question is, how could I set a default value if one field is missing in one record (e.g. the "other" field in the second record of the aforementioned example)? A: You can't perform transformation in copy command. Use ETL tools instead of direct copy to RedShift. Once you use JSON format the default value will be assigned on basis of table DDL.
[ "stackoverflow", "0040117869.txt" ]
Q: Set HTML elements to random object key:value pairs I'm trying to use the "database" I have made to cycle through some the quotes at random when the button is clicked and changing the existing quote in the HTML to the random quote and the existing author in the same way var myDatabase = [ {quote:"I have learned silence from the talkative...", author:"Khalil Gibran"}, {quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"}, {quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"} ]; var newQuote = document.getElementById('displayedQuote'); var newAuthor = document.getElementById('author'); $("#quoteButton").click(function() { var rand = Math.floor(Math.random()*database.length) newQuote = myDatabase.[rand].quote; newAuthor = myDatabase.[rand].author; }); A: Firstly your "Database" has syntax errors. It should read: var myDatabase = [{ "quote": "I have learned silence from the talkative...", "author": "Khalil Gibran" }, { "quote": "One of the blessings of old friends that you can afford to be stupid with them.", "author": "Ralph Waldo Emmerson" }, { "quote": "Once we accept our limits, we go beyond them.", "author": "Albert Einstein" }]; Secondly, you're mixing vanilla JS with Jquery. Whilst this isn't technically wrong it's much easier to read if you just stick to one or the other var newQuote = $('#displayedQuote'); var newAuthor = $('#newAuthor'); Lastly, the syntax in your click method is incorrect. You're assigning a value to the newQuote and newAuthor variables rather than manipulating the element. What you want to do is use the .text() method to add the object values to the DOM. Also, you don't need the dot notation before the [rand] integer and you want myDatabase.length not database.length $("#quoteButton").click(function() { var rand = Math.floor(Math.random() * myDatabase.length) newQuote.text(myDatabase[rand].quote) newAuthor.text(myDatabase[rand].author) }); Here's a working example: https://codepen.io/mark_c/pen/pExxQA
[ "stackoverflow", "0014144603.txt" ]
Q: Magento: Category product design update not applied to search result products I'm using a design update XML applied to all products under specific categories. The update is applied successfully to those products when browsed to them from those categories, but not when those products are opened from search results. How can I make the design update affect those products when opened from search results? A: You need to add a layout handle that you can "grab" for each one of these products and modify the layout through layout xml files. The key to this process is in the initProductLayout method of Mage_Catalog_Helper_Product_View. This method is where custom layout handles are added based on the product model. You can grab the layout update object from the controller and call addHandle() on it with a string to add that handle. So you'll want to rewrite this method and do something like this: $update = $controller->getLayout()->getUpdate(); foreach ($product->getCategoryIds() as $categoryId) { $update->addHandle('PRODUCT_IN_CATEGORY_' . $categoryId); } Now, in a layout xml file you can target the <PRODUCT_IN_CATEGORY_##> handle for the ID of your category(ies) and any layout updates you put here will be applied to the product view page no matter how it is accessed. Depending on the specifics of your installation, it may make more sense to key the handle with some other category identifier, like the name or URL key, instead of the numeric ID. For this, use $product->getCategoryCollection() and iterate through the collection to grab what you need. You may also want to use $product->getAvailableinCategories() if you want to include only category IDs that the product belongs to directly (instead of including categories of higher parentage).
[ "ru.stackoverflow", "0000285889.txt" ]
Q: Как скрыть элемент? Доброго времени друзья!Есть вот такая форма: <div class="box"><div class="podbox"><div class="podpodbox"><table><th>Мы позвоним вам сами</th><tr><td>Ваше имя :</td></tr><tr><td><input type="text" id="obratName" /></td></tr><tr><td>Ваш номер :</td></tr><tr><td><input type="text" id="obratPhone" /></td></tr><tr><td><input type="button" value="Готово" id="obratBut"/></td></tr></table></div><p><a href="'+link+'">Заказать обратный звонок</a></p></div></div> Вот ее стили: .box{ width:220px; height:40px; position:absolute; left:0px; border-top-right-radius:5px; border-bottom-right-radius:5px; box-shadow:0 8px 13px rgba(0,0,0,.2); background:linear-gradient(#6044dd,#aaa8f9); font-size:12px; font-family:Verdana, Helvetica, sans-serif; } .podbox{ width:90%; height:100%; margin:0 auto; padding:0px 5%; text-align:center; position:relative; } .podpodbox{ position:absolute; width:98%; height:200px; margin-left:-11px; background:#aaa8f9; z-index:-5; overflow:hidden; } .podpodbox table{ margin:50px auto; } .podbox p{ margin:0; padding:0; line-height:40px; width:100%; } .podbox a { text-decoration:none; color:#FFF; } Вот скрипт который по нажатию на class="box" показывает .podpodbox $(document).ready(function(){ //Ссылка var link = "#"; $('.podpodbox').hide(); $('.box').click(function (){ $('.podpodbox').fadeTo(300, 1); }); $('#obratBut').click(function(){ $('.podpodbox').hide(); }); }); Там есть кнопка #obratBut по нажатию на нее элемент должен исчезать а он исчезает и появляется! собственно в этом загвоздка. A: Может так: $('#obratBut').click(function(e){ $('.podpodbox').hide(); e.stopPropagation(); }); Я имею в веду, может он появляется от того, что click на родителе происходит.
[ "stackoverflow", "0013767011.txt" ]
Q: carry forms authentication cookie over from HttpClient (webapi call) to WebView I have created an android app that is using a custom-rolled authentication method by calling a web service (webapi on .net mvc 4) with HttpClient. When the user is authenticated, the action method on the server is setting the forms authentication cookie and then returns a user model back to the android client. That user model contains the internal user id and a few other properties. After the user is authenticated, I'm opening up a WebView on android to serve up a viewport for some simple navigation elements. That WebView needs to be handed the authentication cookie from the webapi call in the previous step. I assume that the forms authentication cookie is being held in the HttpClient (though I can't confirm this) and if so, is there a way to pass that cookie over to the WebView so the web page that is served up in the WebView knows who the user is based on the first step? If this isn't possible, can someone guide me with some steps to make this work. TIA A: This looks like a very similar problem. Set a cookie to a webView in Android. Hopefully this can assist you.
[ "stackoverflow", "0058114697.txt" ]
Q: How to fix the problem with generated from scrollmagic with grid? I saw a tutorial on how to make a nice sticky scroll effect with CSS flex. So I wanted to give it a shot and tried this with CSS grid. but it won't work properly. I already fixed some major problems but I'm not very happy with the fixes. and there is still a major problem with the grid columns. there are 2 columns. the left is only one div and the right are a couple of divs. left should stick so that the right column is scrolling. but as soon as the scroll function triggers the right column changes the width. I can't find a solution here. the rest works but I'm sure there is a more elegant way to achieve what I want. I appreciate any help a lot! thanks!Here also a CodePen Link: https://codepen.io/roottjk/pen/QWLPwxZ already tried to fix the width problem with some CSS width properties but that didn't work out at all. HTML <div class="product-title"> <h3>TEST</h3> </div> </div> <div class="sugar"> </div> <div class="private-label"> </div> <div class="adventkalender"> </div> <div class="sweets"> </div> <div class="ads"> </div> </section> CSS section.products { display: grid; grid-template-areas: 'title sugar' 'title private-label' 'title adventkalender' 'title sweets' 'title ads'; margin-bottom: 100vh !important; } .gridhuelle { display: grid; grid-area: title; background-color: transparent !important; z-index: -1; width: 100% !important; } .gridhuelle h3 { color: white; z-index: 10; } .product-title { background-color: black !important; z-index: 1; height: 300vh; padding-top: 10.1875px !important; } .sugar { display: grid; grid-area: sugar; background-color: red; z-index: 5; padding: 1em; margin: 0 !important; } .private-label { display: grid; grid-area: private-label; background-color: green; padding: 1em; } .adventkalender { display: grid; grid-area: adventkalender; background-color: blue; padding: 1em; } .sweets { display: grid; grid-area: sweets; background-color: yellow; padding: 1em; } .ads { display: grid; grid-area: ads; background-color: orange; padding: 1em; } JS function splitScroll() { const controller = new ScrollMagic.Controller(); new ScrollMagic.Scene({ duration: '200%', triggerElement: '.product-title', triggerHook: 0 }) .setPin('.product-title') .addIndicators() .addTo(controller); } splitScroll(); A: This is because of scroll. it's adding inline css and overriding position that's why it's moving: I have added width: 100% and position: sticky to class .product-title .product-title { width: 100%!important; position: sticky!important; } /* Parallax Products */ function splitScroll() { const controller = new ScrollMagic.Controller(); new ScrollMagic.Scene({ duration: '200%', triggerElement: '.product-title', triggerHook: 0 }) .setPin('.product-title') .addIndicators() .addTo(controller); } splitScroll(); /* PRODUCTS */ section.products { display: grid; grid-template-areas: 'title sugar' 'title private-label' 'title adventkalender' 'title sweets' 'title ads'; margin-bottom: 100vh !important; } .gridhuelle { display: grid; grid-area: title; background-color: transparent !important; z-index: -1; width: 100% !important; } .gridhuelle h3 { color: white; z-index: 10; } .product-title { background-color: black !important; z-index: 1; height: 300vh; padding-top: 10.1875px !important; width: 100%!important; position: sticky!important; } .sugar { display: grid; grid-area: sugar; background-color: red; z-index: 5; padding: 1em; margin: 0 !important; } .private-label { display: grid; grid-area: private-label; background-color: green; padding: 1em; } .adventkalender { display: grid; grid-area: adventkalender; background-color: blue; padding: 1em; } .sweets { display: grid; grid-area: sweets; background-color: yellow; padding: 1em; } .ads { display: grid; grid-area: ads; background-color: orange; padding: 1em; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Products Test Page</title> <link rel="stylesheet" href="products.css" class="ref"> </head> <body> <!-- PRODUCTS START--> <header class="productsite"> <h2>Products</h2> </header> <!-- START Grid Section --> <section class="products"> <div class="gridhuelle"> <div class="product-title"> <h3>TEST</h3> </div> </div> <div class="sugar"> </div> <div class="private-label"> </div> <div class="adventkalender"> </div> <div class="sweets"> </div> <div class="ads"> </div> </section> <!-- END GRID SECTION --> <!-- PRODUCTS END--> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/debug.addIndicators.min.js"></script> <script src="main.js"></script> </body> </html>
[ "ru.stackoverflow", "0000954111.txt" ]
Q: The process cannot access the file Всем добрый вечер. Когда файл уже создан, всё хорошо. Но если программа сначала создаёт его, вылезает ошибка, что файл используется. Но почему? Процесс тут один, к записи в поток программа переходит после того, как файл создаст. Вот сама ошибка: "The process cannot access the file 'C:\Users\Tpoc3\Source\Repos\Bachelor-s-Project\TextEditorServer\bin\Debug\files\dd.txt' because it is being used by another process." public void CreateFile(string fileName, string data) { DirectoryInfo currentDirectory = new DirectoryInfo(filePath); if (!currentDirectory.Exists) currentDirectory.Create(); filePath += @"\" + fileName; if (!File.Exists(filePath)) File.Create(filePath); using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8)) { sw.WriteLine(data); } } A: Ресурс (FileStream), который возвращается вызовом File.Create, должен быть освобожден: if (!File.Exists(filePath)) using (File.Create(filePath)) { }
[ "math.stackexchange", "0002690978.txt" ]
Q: $v(x)\cdot \nabla_y \delta(x-y)\rightarrow \nabla_y\cdot\ v(y)\delta(x-y)$ Justification In (non-equilbrium) physics it is common to see the following transfromation done $$v(x)\cdot \nabla_y \delta(x-y)\rightarrow \nabla_y\cdot\left\{ v(y)\delta(x-y)\right\}$$ even without the presence of integrals. What is the mathematical justification for this and why don't we have: $$v(x)\cdot \nabla_y \delta(x-y)\rightarrow v(y)\cdot \nabla_y \delta(x-y)$$ A: In maths, distributions (say on $\mathbb{R}^n$) are viewed as linear functionals $T\colon \phi \mapsto T(\phi)\in \mathbb{C}$, defined on a suitable space of "test functions" $\phi\colon \mathbb{R}^n\rightarrow \mathbb{C}^{m}$. Given a suitably nice function $f$, there is an associated distribution $T_f\colon \phi \mapsto \int f \cdot \phi$. One commonly choses the test functions to be compactly supported, which allows for the following partial integration: $$ T_{\nabla f}(\phi)= \int \nabla f \cdot \phi = -\int f \mathrm{div}\phi = T_f(-\mathrm{div} \phi) $$ Since distributions are meant to generalize functions, one uses this as a definition for an aritrary distribution: $$ \nabla T(\phi):=T(-\mathrm{div}\phi) $$ In general it is not possible to multiply two distributions, but you can define the product of (nice) functions and a distribution by: $$ vT({\phi)=T(v\phi)} $$ Fix $x\in \mathbb{R}^n$. Then what you write as $\delta(x-y)$ can be interpreted as the functional $T \colon \phi \mapsto \phi(x)$. Then $$ \nabla(vT)(\phi)=vT(-\mathrm{div}\phi)=T(-v\mathrm{div}\phi)=v(x) \cdot (-\mathrm{div}\phi(x)) = v(x) \cdot T(-\mathrm{div}\phi)=v(x) \nabla T (\phi). $$ Note that $x$ is fixed, hence $v(x)$ is just a number. This works for an arbitrary test function $\phi$, hence we can say that $\nabla(v T)$ and $v(x) \nabla T$ coincide as distributions. In that sense your equation is mathematically justified.
[ "stackoverflow", "0029128337.txt" ]
Q: Is there an Excel function to count occurrences of a certain characters in a cell? A client has an Excel file that needs to have some names scrubbed. In particular, we're trying to isolate suffixes on names (e.g., Jr., Sr., III, etc.) Names are ALWAYS formatted LastName, FirstName, Suffix in the cell, and I am trying to count the number of commas in a cell. If the cell has more than one comma in it, I can identify that cell as having a name suffix. However, all of the COUNT functions in Excel count instances of CELLS, not characters within cells. Is there a function that counts occurrences of specific characters in a cell and returns that count? A: You can get the number of characters in the cell and then compare that to the number of characters in the cell if you substituted out all the commas with empty spaces: =LEN(A1)-LEN(SUBSTITUTE(A1,",","")) This is also a neat way to get word counts in excel by counting the number of spaces.
[ "cs.stackexchange", "0000023204.txt" ]
Q: Polynomial Hierarchy --- polynomial time TM Consider, for example, the definition for $\Sigma_2^p$ complexity class. $$ x \in L \Leftrightarrow \exists u_1 \forall u_2 \;M(x, u_1, u_2) = 1, $$ where $u_1, u_2 \in \{0,1\}^{p(|x|)}$, for some polynomial $p$. Here, $M$ must be polynomial time. But polynomial in the size of what exactly? For example, if we choose (guess) some $u_1$, do I consider it to be fixed size when talking about time complexity of $M$? More precisely, should $M$ be polynomial only in the size of $x$? An example. Consider the problem whether, given a graph $A$, there exists a graph $B$ such that $B$ is subgraph isomorphic to $A$. $$A \in L \Leftrightarrow \exists B \; \text{SubGraphIsomorphic}(A, B) = 1 $$ Now, subgraph isomorphism is NP-complete. If $B$ is fixed, then there is a TM that implements $\text{SubGraphIsomorphic}$ in deterministic polynomial time. If $B$ is not fixed, then I cannot claim such a thing unless I know $\sf P=NP$. Is this problem in $\Sigma_{1}^{p}$, i.e. $\sf NP$? (Ok, this problem has trivial solutions, but I hope it helps to pinpoint my confusion.) My confusion generalizes for all $\Sigma_{i}^p$. A: Your definition of $\Sigma_2^P$ is a bit misleading. Both $u_1$ and $u_2$ have to be bounded in length by some polynomial in $|x|$, and this usually forms part of the formula rather than part of the descriptive text. The predicate $M$ has to be polynomial time in the combined input length, which is the same as being polynomial time in $|x|$ since both $u_1$ and $u_2$ have length polynomial in $|x|$. You have not described the predicate SubgraphIsomorphic correctly. You are given two graphs $A,B$, and you have to decide whether $B$ is isomorphic to a subgraph of $A$. We write it as an NP-predicate as follows: $$(A,B) \in \mathrm{SubgraphIsomorphic} \leftrightarrow \exists |P| \leq |(A,B)| \mathrm{Isomorphic}(A,B,P), $$ where $\mathrm{Isomorphic}(A,B,P)$ is true if $P$ encodes an injection from the vertex set of $B$ to the vertex set of $A$, and $(x,y)$ is an edge of $B$ iff $(P(x),P(y))$ is an edge of $A$. This is a polytime predicate. Moreover, the injection can be coded in length polynomial in the input $(A,B)$ (for simplicity, I'm assuming that the encoding is such that $|P| \leq |(A,B)|$).
[ "stackoverflow", "0039930636.txt" ]
Q: SSL_get_verify_result returns Error 20 for irc.freenode.net I'm trying to verify the certificate of an IRC server against the UTN_USERFirst_Hardware CA. I'm running into error code 20 from SSL_get_verify_result (which if I'm correct means that it failed to get the peer cert?). Also, I'm not all too sure what the precedence of 'steps' is in the process. Here is what I've cobbled together: int tallis_ssl_verify(tallis_t *tallis, X509 *cert) { int rv; X509_VERIFY_PARAM_set_hostflags( tallis->param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); SSL_CTX_set_default_verify_paths(tallis->ssl_context); ERR_clear_error(); rv = SSL_CTX_load_verify_locations( tallis->ssl_context, "/etc/ssl/certs/AddTrust_External_Root.pem", "/etc/ssl/certs"); if (!rv) { fprintf(stderr, ERR_error_string(ERR_get_error(), NULL)); return 1; } X509_VERIFY_PARAM_set1_host(tallis->param, tallis->host, 0); SSL_CTX_set_verify(tallis->ssl_context, SSL_VERIFY_PEER, NULL); SSL_set_verify(tallis->ssl_connection, SSL_VERIFY_PEER, NULL); ERR_clear_error(); rv = SSL_get_verify_result(tallis->ssl_connection); if (rv != X509_V_OK) { printf("%d\n", rv); fprintf(stderr, ERR_error_string(ERR_get_error(), NULL)); return 1; } ERR_clear_error(); X509_STORE_CTX *ctx = X509_STORE_CTX_new(); if (!ctx) { fprintf(stderr, ERR_error_string(ERR_get_error(), NULL)); return 1; } ERR_clear_error(); X509_STORE *store = X509_STORE_new(); if (!store) { X509_STORE_free(store); fprintf(stderr, ERR_error_string(ERR_get_error(), NULL)); return 1; } ERR_clear_error(); rv = X509_STORE_CTX_init(ctx, store, cert, NULL); if (!rv) { X509_STORE_free(store); fprintf(stderr, ERR_error_string(ERR_get_error(), NULL)); return 1; } X509_STORE_set_flags(store, X509_V_FLAG_CB_ISSUER_CHECK); X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); X509_STORE_load_locations( store, "/etc/ssl/certs/AddTrust_External_Root.pem", NULL); X509_STORE_set_default_paths(store); X509_LOOKUP_load_file( lookup, "/etc/ssl/certs/AddTrust_External_Root.pem", X509_FILETYPE_PEM); X509_STORE_add_cert(store, cert); ERR_clear_error(); rv = X509_verify_cert(ctx); if (rv != 1) { X509_STORE_free(store); fprintf( stderr, "%s\n%s\n", ERR_error_string(ERR_get_error(), NULL), X509_verify_cert_error_string(ctx->error)); return 1; } return 0; } And the calling routine for context: int main(int argc, char *argv[]) { tallis_t *tallis = malloc(sizeof(tallis_t)); tallis->host = "irc.freenode.net"; tallis->port = "6697"; tallis->bio = NULL; tallis->ssl_connection = NULL; ssl_init(tallis->ssl_connection); tallis->ssl_context = SSL_CTX_new(TLSv1_2_client_method()); tallis->ssl_connection = SSL_new(tallis->ssl_context); tallis->param = SSL_get0_param(tallis->ssl_connection); int rv; rv = tallis_connect(tallis); if (rv) DIE("%s\n", "connection failed"); ERR_clear_error(); X509 *cert = SSL_get_peer_certificate(tallis->ssl_connection); if (!cert) DIE("%s\n", ERR_error_string(ERR_get_error(), NULL)); rv = tallis_ssl_verify(tallis, cert); X509_free(cert); if (rv) DIE("%s\n", "certificate verificiation failed"); else printf("%s\n", "certificate verification succeeded"); rv = tallis_loop(tallis); if (rv) DIE("%s\n", "socket connection terminated"); rv = ssl_shutdown(tallis); if (rv) DIE("%s\n", "ssl shutdown failed"); } So, as it stands my flow is this: Establish connection at the socket (BIO) level -> call SSL_get_peer_certificate -> do certificate verification, is this correct? What's the difference between SSL_get_verify_result and X509_verify_cert and which one should be used first? Sorry if this is too general, I need a little guidance and the docs are just manual pages with not much correlative information, I find it hard to get an organized view of OpenSSL. How about 'How do I verify a peer certificate in OpenSSL as simply as possible?' A: I'm trying to verify the certificate of an IRC server against the UTN_USERFirst_Hardware CA I believe that's the wrong Root CA. How about 'How do I verify a peer certificate in OpenSSL as simply as possible?' I think you are just about where you need to be. You only need a few tweaks. When I examine the topmost Issuer in the chain (s: indicates Subject, while i: indicates Issuer): $ openssl s_client -connect irc.freenode.net:6697 -servername irc.freenode.net -tls1_2 CONNECTED(00000005) depth=2 C = US, ST = New Jersey, L = Jersey City, O = The USERTRUST Network, CN = USERTrust RSA Certification Authority verify error:num=20:unable to get local issuer certificate Server did acknowledge servername extension. --- Certificate chain 0 s:/OU=Domain Control Validated/OU=Gandi Standard Wildcard SSL/CN=*.freenode.net i:/C=FR/ST=Paris/L=Paris/O=Gandi/CN=Gandi Standard SSL CA 2 1 s:/C=FR/ST=Paris/L=Paris/O=Gandi/CN=Gandi Standard SSL CA 2 i:/C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust RSA Certification Authority 2 s:/C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust RSA Certification Authority i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root ... <skip certificate and lots of other stuff> ... Start Time: 1475924259 Timeout : 7200 (sec) Verify return code: 20 (unable to get local issuer certificate) It looks like you want your root of trust at CN=AddTrust External CA Root; not UTN_USERFirst_Hardware_Root_CA. You can find it at Comodo's site at [Root] AddTrust External CA Root. The file addtrustexternalcaroot.crt is in PEM format. You only need to specify the -CAfile option to make the command complete successfully (X509_V_OK): $ openssl s_client -connect irc.freenode.net:6697 -servername irc.freenode.net -tls1_2 -CAfile addtrustexternalcaroot.crt CONNECTED(00000005) depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root verify return:1 depth=2 C = US, ST = New Jersey, L = Jersey City, O = The USERTRUST Network, CN = USERTrust RSA Certification Authority verify return:1 depth=1 C = FR, ST = Paris, L = Paris, O = Gandi, CN = Gandi Standard SSL CA 2 verify return:1 depth=0 OU = Domain Control Validated, OU = Gandi Standard Wildcard SSL, CN = *.freenode.net verify return:1 Server did acknowledge servername extension. --- Certificate chain 0 s:/OU=Domain Control Validated/OU=Gandi Standard Wildcard SSL/CN=*.freenode.net i:/C=FR/ST=Paris/L=Paris/O=Gandi/CN=Gandi Standard SSL CA 2 1 s:/C=FR/ST=Paris/L=Paris/O=Gandi/CN=Gandi Standard SSL CA 2 i:/C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust RSA Certification Authority 2 s:/C=US/ST=New Jersey/L=Jersey City/O=The USERTRUST Network/CN=USERTrust RSA Certification Authority i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root ... <skip certificate and lots of other stuff> ... Start Time: 1475924761 Timeout : 7200 (sec) Verify return code: 0 (ok) Extended master secret: no Now that you know how to test it and what the good test case looks like, here's how to fix it in your code: rv = SSL_CTX_load_verify_locations( ssl_context, ".../addtrustexternalcaroot.crt", NULL; Here's what the CA Root looks like: $ cat addtrustexternalcaroot.crt | openssl x509 -text -noout Certificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption Issuer: C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root Validity Not Before: May 30 10:48:38 2000 GMT Not After : May 30 10:48:38 2020 GMT Subject: C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:b7:f7:1a:33:e6:f2:00:04:2d:39:e0:4e:5b:ed: 1f:bc:6c:0f:cd:b5:fa:23:b6:ce:de:9b:11:33:97: a4:29:4c:7d:93:9f:bd:4a:bc:93:ed:03:1a:e3:8f: cf:e5:6d:50:5a:d6:97:29:94:5a:80:b0:49:7a:db: 2e:95:fd:b8:ca:bf:37:38:2d:1e:3e:91:41:ad:70: 56:c7:f0:4f:3f:e8:32:9e:74:ca:c8:90:54:e9:c6: 5f:0f:78:9d:9a:40:3c:0e:ac:61:aa:5e:14:8f:9e: 87:a1:6a:50:dc:d7:9a:4e:af:05:b3:a6:71:94:9c: 71:b3:50:60:0a:c7:13:9d:38:07:86:02:a8:e9:a8: 69:26:18:90:ab:4c:b0:4f:23:ab:3a:4f:84:d8:df: ce:9f:e1:69:6f:bb:d7:42:d7:6b:44:e4:c7:ad:ee: 6d:41:5f:72:5a:71:08:37:b3:79:65:a4:59:a0:94: 37:f7:00:2f:0d:c2:92:72:da:d0:38:72:db:14:a8: 45:c4:5d:2a:7d:b7:b4:d6:c4:ee:ac:cd:13:44:b7: c9:2b:dd:43:00:25:fa:61:b9:69:6a:58:23:11:b7: a7:33:8f:56:75:59:f5:cd:29:d7:46:b7:0a:2b:65: b6:d3:42:6f:15:b2:b8:7b:fb:ef:e9:5d:53:d5:34: 5a:27 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: AD:BD:98:7A:34:B4:26:F7:FA:C4:26:54:EF:03:BD:E0:24:CB:54:1A X509v3 Key Usage: Certificate Sign, CRL Sign X509v3 Basic Constraints: critical CA:TRUE X509v3 Authority Key Identifier: keyid:AD:BD:98:7A:34:B4:26:F7:FA:C4:26:54:EF:03:BD:E0:24:CB:54:1A DirName:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root serial:01 Signature Algorithm: sha1WithRSAEncryption b0:9b:e0:85:25:c2:d6:23:e2:0f:96:06:92:9d:41:98:9c:d9: 84:79:81:d9:1e:5b:14:07:23:36:65:8f:b0:d8:77:bb:ac:41: 6c:47:60:83:51:b0:f9:32:3d:e7:fc:f6:26:13:c7:80:16:a5: bf:5a:fc:87:cf:78:79:89:21:9a:e2:4c:07:0a:86:35:bc:f2: de:51:c4:d2:96:b7:dc:7e:4e:ee:70:fd:1c:39:eb:0c:02:51: 14:2d:8e:bd:16:e0:c1:df:46:75:e7:24:ad:ec:f4:42:b4:85: 93:70:10:67:ba:9d:06:35:4a:18:d3:2b:7a:cc:51:42:a1:7a: 63:d1:e6:bb:a1:c5:2b:c2:36:be:13:0d:e6:bd:63:7e:79:7b: a7:09:0d:40:ab:6a:dd:8f:8a:c3:f6:f6:8c:1a:42:05:51:d4: 45:f5:9f:a7:62:21:68:15:20:43:3c:99:e7:7c:bd:24:d8:a9: 91:17:73:88:3f:56:1b:31:38:18:b4:71:0f:9a:cd:c8:0e:9e: 8e:2e:1b:e1:8c:98:83:cb:1f:31:f1:44:4c:c6:04:73:49:76: 60:0f:c7:f8:bd:17:80:6b:2e:e9:cc:4c:0e:5a:9a:79:0f:20: 0a:2e:d5:9e:63:26:1e:55:92:94:d8:82:17:5a:7b:d0:bc:c7: 8f:4e:86:04
[ "stackoverflow", "0011940379.txt" ]
Q: treepanels drag and drop default behavior I have two treepanels which I want to drag and drop between. I understand there is a plugin for this, however I want it to behave a certain way. In my treepanels, I am showing the root node of the tree, and then all its children. The default DD allows the user to drop items at different levels on the tree(i.e. sibling of root, child of root) where I want all items to be a child of root for consistency. How can I make it so that any drag into the treepanel associates the item as a child of the root and not a sibling of the root. Why: For a user who doesn't understand how this functionality works, one millimeter in either direction can change the item from being a sibling to child or vice versa. Also, I would like it so I can only drag away those children and the root can't be moved, if at all possible. A: Yes it is possible. You can listen to the 'beforedrop' event on the target Tree panel's tree view and achieve what you want. Something like this http://jsfiddle.net/EYtnk/1/ .. One of the arguments of the beforedrop event is the node being dragged. You can check if it is a root node of source tree and just 'return false;' P.S: In the example, i just used the same store for both the trees.. so the nodes get added on either side.
[ "stackoverflow", "0015148544.txt" ]
Q: Visual Studio 2012: LNK2028 and LNK2019 build errors I'm getting two errors and cannot figure out how to resolve, here they are: error LNK2028: unresolved token (0A0003A0) "void __cdecl polygon(int,int,int,int,unsigned int)" (?polygon@@$$FYAXHHHHI@Z) referenced in function "void __cdecl vox_texture_cube(unsigned int,unsigned int)" (?vox_texture_cube@@$$FYAXII@Z) error LNK2019: unresolved external symbol "void __cdecl polygon(int,int,int,int,unsigned int)" (?polygon@@$$FYAXHHHHI@Z) referenced in function "void __cdecl vox_texture_cube(unsigned int,unsigned int)" (?vox_texture_cube@@$$FYAXII@Z) The only thing I have tried is going into the General Options in the Project properties and changing the Common Language RunTime Support to /clr pure as per another question on here, however, that causes more problems. Here is my code: //This Function creates a Polygon Face using Vertice Array //It is the Method for creating each face of a cube void **polgon**(int a, int b, int c, int d, GLuint texture) { glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, whiteSpecularMaterial); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mShininess); glBindTexture(GL_TEXTURE_2D, texture); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3fv(vertices[a]); glTexCoord2f(1.0, 0.0); glVertex3fv(vertices[b]); glTexCoord2f(1.0, 1.0); glVertex3fv(vertices[c]); glTexCoord2f(0.0, 1.0); glVertex3fv(vertices[d]); glEnd(); } A: Well, you declare a function called void polygon(int a, int b, int c, int d, GLuint texture); And then you implement a function called void polgon(int a, int b, int c, int d, GLuint texture) { ... } So the problem is that the linker is trying to find the function polygon which you promised you would implement but didn't. Solution: Rename polgon to polygon and you should be good to go.
[ "wordpress.stackexchange", "0000213677.txt" ]
Q: Woocommerce Variable Product - Please choose product options… Running my own designed custom theme "mdbootstrap" designed by myself. Integrating WooCommerce 2.4.12. and upon testing there is an issue adding variable products to the cart. Basically the add to cart button is hidden and doesn't appear once a variant is selected . If I switch to the TwentyEleven theme, the issue resolves itself. I can force button to show by adding to css .single_variation_wrap{display:block !important;} but even then when I submit "Add to card" page is reloading and when I move to cart page I am getting error: Please choose product options… Variable product: http://mdb.nomadflow.com/product/ecommerce-homepage-template/ Normal products works like a charm: http://mdb.nomadflow.com/product/blog-homepage-template/ You have to be logged in: username: test password: test A: I'm not sure why but you have form tag inside a form tag.. and chrome is making it as one... view source and look for <form class="cart" method="post" enctype='multipart/form-data'> and <form class="variations_form cart" method="post" <form class="variations_form cart" method="post" was removed by the browser which is the one needed by woocommerce.
[ "math.stackexchange", "0001156917.txt" ]
Q: How to prove the convergence of the series $\sum\frac{(3n+2)^n}{3n^{2n}}$ I need to prove the convergence of this series: $$\sum\limits_{n=1}^\infty\frac{(3n+2)^n}{3n^{2n}}$$ I've tried using Cauchy's criterion and ended up with a limit of $1$, but I already know it does converge. How am I suppose to prove it? Note that I've also tried the integral test and was not able to solve. A: hint: $\dfrac{(3n+2)^n}{n^{2n}} = \left(\dfrac{3n+2}{n^2}\right)^n< \left(\dfrac{4}{n}\right)^n< \dfrac{16}{n^2}$ A: The root test applies nicely here. Taking $\displaystyle a_n=\left(\frac{3\,n+2}{n^2}\right)^n$ gives $$ \lim_{n\to\infty}\lvert a_n\rvert^{1/n} = \lim_{n\to\infty}\frac{3\,n+2}{n^2} =0<1 $$ This proves that $\sum a_n$ converges so your series $\frac{1}{3}\sum a_n$ converges. A: Let's use the $n$th root test. $$ \left|\frac{(3n+2)^n}{3n^{2n}}\right|^{1/n} = \frac{3n+2}{3^{1/n}n^2} \to 0. $$ Since $0<1$, the series converges absolutely.
[ "stackoverflow", "0029292963.txt" ]
Q: Spring Data (JPA) - using generics in @Query I wonder if it's possible to use generics in the named queries in spring data (using jpa myself), is it possible to do anything like this? @NoRepositoryBean public interface EnumerationRepository<T extends Enumeration> extends JpaRepository<T,Integer> { @Query("Select t.type from T t") public List<String> selectTypes(); } Enumeration class being this @MappedSuperclass public abstract class Enumeration { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", length = 3) private int id; @Column(name = "type", nullable = false, unique = true, length = 30) private String type; // getters / setters .. etc } I ommitted some fields in the Enumeration class for the sake of simplicity. Tried this but obviously it complains cause class T is not mapped. The point is because i have like 20+ tables that share some basic structure, and since i need queries to extract only data from columns, not the whole entity, would be nice to find a way to get the query in the "parent" repository and not having to replicate the code 20+ times. A: If using Spring Data JPA 1.4 or higher, the following will work: @Query("Select t.type from #{#entityName} t")
[ "stackoverflow", "0001436577.txt" ]
Q: Error Binding Gridview: "The current TransactionScope is already complete" I am doing cascading deletes in an event sent from a Gridview. The deletes are in a Transaction. Here is the simplified code: protected void btnDeleteUser_Click(object sender, EventArgs e) { DataContext db; db = new DataContext(); using (TransactionScope ts = new TransactionScope()) { try { //delete some data db.SubmitChanges(); ts.Complete(); } catch (Exception ex) { // handle error } finally { db.Dispose(); BindGridView(); } } } private void BindGridView() { DataContext db; db = new DataContext(); GridView.DataSource = <my query> GridView.DataBind(); <========Exception db.Dispose(); } The call to the grid's DataBind() method fails with this exception: "The current TransactionScope is already complete." Why? Of course is the TransactionScope complete at that point, and it should. When I remove the TransactionScope, it works. A: Move BindGridView() outside of the transaction scope. using (TransactionScope ts = new TransactionScope()) { try { //delete some data db.SubmitChanges(); ts.Complete(); } catch (Exception ex) { // handle error } finally { db.Dispose(); } } BindGridView();
[ "stackoverflow", "0013865095.txt" ]
Q: Two way syncing from local xml file up to sql server db I know when it comes to syncing, a lot of people would say to use a sqlCE and sync it up to the central db. My app is made already using raw xml to save my data(lightweight). My wpf app stores data locally not needing internet on a raw xml file. I'm trying to find the best way (approach) to sync local xml up to my sql server. My goal is to sync the local xml file up with the central db and update the central dbs data, as well as pulling down updated data and updating to my local xml. Hopefully I'm being clear with my question. I've never used web services before so any help or point of direction would be appreciated. Would using the Sync framework work for this? A: Synchronizing data is not a trivial task. Have a look at the Sync Framework. I don't know if it supports XML out of the box but you could probably implement a suitable provider. One word of warning - even synchronizing several SQL Server [Express|CE] databases, something supported out of the box, requires quite a bit of work to get it working.
[ "stackoverflow", "0056533246.txt" ]
Q: Unable to render anything but default Rails page I am following a tutorial (https://blog.teamtreehouse.com/static-pages-ruby-rails) to render a page using Rails routes. The problem is I get an error instead of the page that should render. I don't know what I'm doing wrong since there are literally only a few steps. The only difference my code has from the tutorial is trivial. I'm using Videos rather than Pages. In config/routes.rb: Rails.application.routes.draw do # This means that all paths following the pattern: # /videos/about, /videos/home, /videos/features # will route here! get "/videos/:video" => "videos#show" end In app/controllers/videos_controller.rb": class VideosController < ApplicationController def show render template: "videos/#{params[:page]}" end end Finally, I have a static page filled with gibberish stored in app/views/videos/videos.html.erb. However, when I run my server and go to 0.0.0.0:3000/videos/ I get the following error: No route matches [GET] "/videos" Rails.root: /home/mightu/Desktop/portal_rails When I try 0.0.0.0:3000/videos/pizza, I get: Missing template /videos with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in: * "/home/mightu/Desktop/portal_rails/app/views" It tells me the problem is this line: render template: "videos/#{params[:page]}" Please help thx A: Start by doing: Rails.application.routes.draw do resources :videos end Which will give you: videos GET /videos(.:format) videos#index POST /videos(.:format) videos#create new_video GET /videos/new(.:format) videos#new edit_video GET /videos/:id/edit(.:format) videos#edit video GET /videos/:id(.:format) videos#show PATCH /videos/:id(.:format) videos#update PUT /videos/:id(.:format) videos#update DELETE /videos/:id(.:format) videos#destroy Then, rename app/views/videos/videos.html.erb to app/views/videos/show.html.erb. And modify your show action on your VideosController to: class VideosController < ApplicationController def show end end And now 0.0.0.0:3000/videos/pizza will render the show.html.erb template and you'll have a params[:id] with a value of pizza.
[ "travel.meta.stackexchange", "0000001340.txt" ]
Q: Creating Hyperlinks When Writing A Comment? So last week I finally figured out how to create hyperlinks to a website when writing an answer and obviously it looks much more neat, tidy and professional than just providing the raw url. How do I therefore create a hyperlink when writing a comment ? A: Easy: [link text](http://www.example.com/) When writing a comment, you can also click the "help" link on the right of the comment box and receive further tips on writing and formatting with Markdown (the markup language used to format all posts on SE sites). See more formatting tips on the full editing guide for SE sites.
[ "stackoverflow", "0009824706.txt" ]
Q: Batch-file to run executable on time interval I'm trying to create a .bat file to execute a flash video on a 10 s time interval in an infinite loop. So far I have... ECHO OFF :TOP START /d "path" program.exe SLEEP 10 TASKKILL /F /IM program.exe GOTO TOP It needs to restart the video after 10 seconds, but it just turns it on and that's it. Help! A: Try this instead: @echo off :TOP PathDir\program.exe ping 127.0.0.1 -n 11 taskkill /im program.exe /f goto :TOP Haven't changed much but I haven't used SLEEP so not sure if that's causing the issue.
[ "serverfault", "0000089611.txt" ]
Q: OpenSUSE 10.2 two network adapters, one problem Actually several problems. Let me explain what we are trying to accomplish first: We have a server that sits in two subnets, by having a network adapter plugged into each network. 192.168.10.x and 192.168.20.x are the subnets. The 20.x subnet in intended for external access (outside the office, our 'DMZ' of sorts), and 192.168.20.1 is the gateway to the outside world. If a user or app on the server tries to access yahoo.com, for example, it should be routed through the 20.x subnet. The 10.x subnet is internal only and traffic to outside sites should not be routed through here. First problem is that I'm not a Linux Guru in this area. Second problem is that with two physical adapters, OpenSUSE 10.2 seems only able to run one at a time. Third problem, pending resolution of the Second, is actually getting OpenSUSE 10.2 to work the way we want it. UPDATE: Here is the way we actually want this to work: eth0 - (externally-facing adapter) Static IP: 192.168.20.5 Default Gateway: 192.168.20.1 eth1 - (internally-facing adapter) Static IP: 192.168.10.5 Default Gateway: should be null Routing information: Destination: 192.168.10.0 Gateway: 192.168.10.5 Netmask: 255.255.255.0 This works fine in CentOS. We are able to access the CentOS box using the internal IP address, and it is also exposed outside on the 20. The CentOS box can also access both internal and external resources via IP and domain name. That said I realize that given my limited knowledge of Linux this may not be the best approach. We have been able to get CentOS 5.3 working (an altogether wonderful OS, by the way). However, the GUI in OpenSUSE is not only completely different, it's also more complicated and confusing. ANY help would be appreciated! A: PROBLEM SOLVED. This was a misunderstanding to be certain, however unrelated to my routing configuration! The fact is, when I switched from DHCP to static IP addresses, apparently I also need to add at least a primary DNS in the hosts / domain area. I used the new public Google DNS (8.8.8.8) and now everything is working as it should.
[ "stackoverflow", "0010322742.txt" ]
Q: In R, what command do I use to generate a dataset consisting of the means of all column vectors in a dataset? Some background: First, I wanted to generate multiple sets of samples (each of sample size n) from a uniform (0,1) distribution in [R]. I know that the command for generating from a uniform distribution is runif(n=x) for some sample size x, e.g. if I wanted sample size 20 the command would be runif(n=20) Next, I used the command replicate( 100, runif(n=20)) This generated a double matrix of values which I could then convert into a dataset with 100 columns and 20 rows. Is it possible for me to generate a dataset consisting of the sample means of all the column vectors (the sample means of the 100 sets taken from the uniform distribution)? Thank you for your help. A: You can use colMeans. data <- replicate(100, runif(n=20)) means <- colMeans(data) A: Generate data: data <- replicate(100, runif(n=20)) Means of columns, rows: col_mean <- apply(data, 2, mean) row_mean <- apply(data, 1, mean) Standard deviation of columns, rows col_sd <- apply(data, 2, sd) row_sd <- apply(data, 1, sd)
[ "stackoverflow", "0011890565.txt" ]
Q: Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive I have just uploaded a website to my server. And it works perfectly locally, but after I uploaded, the online version displays this: Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. Parser Error Message: Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. Source Error: Line 37: </buildProviders> Line 38: </compilation> Line 39: <httpRuntime targetFramework="4.0" encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> Line 40: <machineKey compatibilityMode="Framework45" /> Line 41: </system.web> Source File: D:\HostingSpaces\o\o.com.au\wwwroot\web.config Line: 39 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272 According to other answers on this site, its because the account on the server is set to use .NET Framework 2.0. BUT that's not the case with mine, I've made sure that it's set to 4.0 and I've even tried 4.0 Integrated. But it still displays this error. What could be causing this? How can I fix it? A: The application is trying to use features that are new to ASP.NET 4.5 (see in particular the <httpRuntime> and <machineKey> elements), but the server only has ASP.NET 4.0. Remove the <httpRuntime> and <machineKey> elements from Web.config to solve the issue. (Fun fact: the <httpRuntime/targetFramework> attribute didn't exist until 4.5. So even though the value says "4.0," the server still fails since it's not expecting to see this attribute at all.) A: This issue can be fixed by going to IIS, click Application Pools and set Version to 4.0 (Integrated)(the one that is running the site). The accepted answer says HttpRunTime/targetFrameWork> does not exists until in 4.5. This is incorrect. For reference, this is HttpRuntime V2 Doc. TargetFrameWork is new to Version 4. The problem in the OP question is, he set the .NET version of the site to 4 but on remote server, 2.0 was running hence the error. In that case since he has no control over remote server (assuming), changing .NET version to 2.0 locally would fix the problem, without fiddling with web.config. A: i think you application pool in IIS is not setup correctly, you must set your apllication pool to ASP.NET v4.0. hope this help
[ "stackoverflow", "0004403865.txt" ]
Q: Which browsers allow cross domain ajax calls with Access-Control-Allow-Origin: *? Which browsers allow cross domain ajax calls with Access-Control-Allow-Origin: *? I am setting a REST service and trying to decide if I need to support JSONP to allow cross domain javascript access or if it is good enough to set the Access-Control-Allow-Origin header. A: Here's one reference suggesting that support in modern browsers is reasonable (but see the note at the end of this answer), assuming client-side code handles the IE issue on purpose. (IE8 and IE9 support CORS, but not via XMLHttpRequest —you have to use XDomainRequest instead, and it's worth noting that neither jQuery nor Prototype does that for you in their ajax wrappers — I don't know about other libraries. IE10 finally gets it right.) That page says, in essence, that CORS is supported in the desktop versions of: IE8+ (via XDomainRequest), IE10+ (properly) Firefox 3.6+ Safari 4.0+ Chrome 6+ Opera 12.1+ ...as well as iOS Safari 3.2+ Android browser 2.1+ You have to ask yourself what your target market is and whether they're likely to still be using older versions of IE, because it matters quite a lot who you're targeting. But overall, you still (for the moment) probably want to look at a JSONP interface — even in the U.S. mostly-home market, IE6+IE7 = about 20% of the users. I don't know many sites that can just ignore a fifth of the market. :-) And if you look at corporate users, or users in Asia or Africa or Central America, that number goes up markedly. The foregoing was true in 2010. Here in 2013, China is really the only holdout using IE6 (>24% there). Worldwide, IE6 and IE7 users have moved on to IE8 and IE9, and even big corporate and government users have finally "got it" about the security risks. IE8 will be with us for a while (as that's has high as IE goes on Windows XP), but you can bet the nearly 20% using IE9 will be on IE10 soon.
[ "stackoverflow", "0015275298.txt" ]
Q: Back button missing in KDE system-settings In the kde system-settings there was a back button, if you clicked a category to edit, you could press back to return to the root category. Just a few minutes ago this button disappeared. I would like to get it back. There are no buttons, tool-bars or menus. There are, in the root view, two tabs “general” and “Advanced”, then rows of icons with words under them (one for each category). So how can I get my back button back? A: This is a bit heavy handed as it may have other effects, and needs use of command-line. sed -i.backup -re "/State=.*/ d" ~/.kde/share/config/systemsettingsrc It removes line starting State= from the config-file