text
stringlengths
64
89.7k
meta
dict
Q: Styling child elements using global CSS in Angular 2 I'm starting to use Angular 2 and I am using an admin template from Themeforest for styling. I want my component to take the styles defined on the index.html, which should be global. The problem is that the elements inside a components html file are not finding these styles, and I think that it is because somehow the parent-child relationship is broken. Here's an example: In the index.html file, I have the following: ... <!-- This is my Component --> <sidebar-menu></sidebar-menu> <!-- This is coded directly on the index.html --> <li class="m-t-30"> <a href="#" class="detailed"> <span class="title">Page 1</span> <span class="details">234 notifications</span> </a> <span class="icon-thumbnail "><i class="pg-mail"></i></span> </li> ... My <sidebar-menu> component has this on it's .html file: <li class="m-t-30"> <a href="#" class="detailed"> <span class="title">Page 1</span> <span class="details">234 notifications</span> </a> <span class="icon-thumbnail "><i class="pg-mail"></i></span> </li> Which is exactly the same as what is present on the index.html file. So, I should see the two items displayed in the same way. But this is what I see: Clearly, the styling is broken, even though that both the component's html and the element's html are the same. Using the inspector, I can see that the component's html is not using the same styling as the second element: Component's inspected title: Second element's inspected title: I tried defining encapsulation: ViewEncapsulation.None on my Component, but it doesn't do anything. Any ideas on how to solve this? Thanks! A: The way I managed to work around this limitation was to change the way my component's directive is called. Normally, you would define the selector like this: @Component({ moduleId: module.id, selector: 'sidebar-menu', ... }) And call it using <sidebar-menu></sidebar-menu>. Instead, I defined the selector like this: @Component({ moduleId: module.id, selector: '[sidebar-menu]', ... }) And call it as a directive inside a div, a li or any DOM element for that matter. <ul class="menu-items" sidebar-menu></ul> This way, I can still use the styling from my Themeforest template and use components. I figured that it broke because normally I would have something like this: <div class="parent-class"> <div class="child-class"> ... styles applied to ".parent-class.child-class" </div> </div> And with components, I got something like this: <div class="parent-class"> <sidebar-menu> <div class="child-class"> ... CSS can't find ".parent-class.child-class" anymore, as it has a sidebar-menu element in the middle! </div> </sidebar-menu> </div> With the workaround, you end up with this: <div class="parent-class"> <div class="child-class" sidebar-menu> ... CSS can still find ".parent-class.child-class", all good! </div> </div> Hopefully this will help someone. Thanks for your answers!
{ "pile_set_name": "StackExchange" }
Q: AFRAME screen to world position I'm trying to convert Mouse position to world coordinates in Three via Aframe Using something like let mouse = new three.Vector2() let camera = document.querySelector('#camera') let rect = document.querySelector('#sceneContainer').getBoundingClientRect() mouse.x = ( (event.clientX - rect.left) / rect.width ) * 2 - 1 mouse.y = - ( (event.clientY - rect.top) / rect.height ) * 2 + 1 let vector = new three.Vector3( mouse.x, mouse.y, -1 ).unproject( camera ) However it doesn't seem to be able to handle the camera, I get TypeError: Cannot read property 'elements' of undefined From Matrix4.getInverse 9550 | 9551 | // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm 9552 | var te = this.elements, > 9553 | me = m.elements, 9554 | 9555 | n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], 9556 | n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], I presume it's not reading the camera properly, any ideas on how to get the three camera out of the aframe camera if that's the problem? A: Using Piotr's info about accessing the camera and fixing up the 'three' to 'THREE' seems to work: https://glitch.com/edit/#!/aframe-mouse-to-world AFRAME.registerComponent('mouse-to-world', { init: function () { document.addEventListener('click', (e) => { let mouse = new THREE.Vector2() let camera = AFRAME.scenes[0].camera let rect = document.querySelector('body').getBoundingClientRect() mouse.x = ( (e.clientX - rect.left) / rect.width ) * 2 - 1 mouse.y = - ( (e.clientY - rect.top) / rect.height ) * 2 + 1 let vector = new THREE.Vector3( mouse.x, mouse.y, -1 ).unproject( camera ) console.log(vector) }) } });
{ "pile_set_name": "StackExchange" }
Q: Why was Kryten asked to check his chair? In series 8, episode 1 of Red Dwarf, Back in the Red, pt. 1 the counsellor is evaluating Kryten and keeps asking him if his seat is screwed down. I have no idea why. COUNSELLOR Right! I was alive, died, and then started living again..? KRYTEN You have been most fortunate, sir! [The COUNSELLOR laughs along with the percieved joke, obviously uncomfortable ] COUNSELLOR I have, haven't I? Golly! Your chair is screwed down, isn't it, Kryten? [KRYTEN dutifully checks, puzzled, and nods confirmation] Taken from this website. Why does the counsellor (repeatedly) ask whether the seat is screwed down? A: My take on it was that the Counsellor was concerned that Kryten was displaying some quite bizarre and truly irrational behaviours. After speaking to him for just a few seconds, he formed the conclusion that the most likely outcome of the meeting is that he would be recommending that Kryten be... Restored to Factory Settings ...which is essentially a death-sentence for a droid that has developed sentience. As his behaviour becomes more and more irrational and the interview comes to a head, he asks him again a couple of times to check the chair because he's worried that Kryten (an insane android who's just about to be told that he's going to be mind-wiped) will use it to beat him to death.
{ "pile_set_name": "StackExchange" }
Q: php-curl script that saves images---actually captcha images I have a curl class, called Curl. Let's presume i have this code: $url = 'http://www.google.com' $fields = array('q'=>'search term'); //maybe some other arguments. but let's keep it simple. $curl = new Curl(); $page = $curl->post($url,$fields); $page will have some images wich curl doesn't load them by default. I need to know how i can save a specific image without using curl. Once I use $page = $curl->post(..) I need to know how I can have that image saved without using another $curl->post(_image_location_) to get that file. The reason why need this is to save a captcha image from a form. I need to access the form and get that specific image that's being loaded. If i try to access the URL of the image, it will be a different captcha image. A: What you are describing isn't possible. For every external resource inside a web page (ie anything that's not part of the HTML content itself, such as images, scripts, stylesheets, etc), you have to make a separate request to retrieve it. This is how all browsers operate. Many captchas work on a session basis. You initial request to the HTML page is likely creating a session cookie which would be sent back as part of the response headers. This cookie will be expected when the image is requested. If you just do a plain curl request for the image, you won't be sending that cookie, and thus you'll get a different image. You will have to analyze the page and determine exactly what kind of session management is going on, and modify your Curl request appropriately, but as I mentioned, I suspect it'll be cookie based. You'll probably want to look at the CURLOPT_COOKIEJAR curl_setopt() parameter to get things started. You can google for pretty straightforward examples as well.
{ "pile_set_name": "StackExchange" }
Q: Overridden doDML() in EntityImpl does not refresh attributes I am using an Oracle ADF page to update data in a table. My entity object is based on the table, but I want the DML (inserts, updates, deletes) to go through a package procedure in the database instead of using the default DML generated by the ADF framework. To accomplish this, I am following Oracle's documentation, found here: http://docs.oracle.com/cd/E23943_01/web.1111/b31974/bcadveo.htm#ADFFD1129 This all works fine. The problem is, the default ADF DML processing will automatically refresh the entity row after writing it, either with a RETURNING INTO clause or with a separately issued SELECT statements (depending on the value of isUseReturningClause() in the EntityDefImpl object). This is done so that the application front end gets updated in case the row was modified by the database during the DML process (e.g., a BEFORE ROW trigger changes values). But, when I overwrite doDml() to replace the default framework DML with a call to my package procedure, it no longer automatically refreshes, even if isUseReturningClause() returns false. I tried adding code to my doDml() implementation to requery afterwards, but it didn't work (maybe I didn't do it correctly). But, Oracle's documentation doesn't say anything about having to do that. Does anyone know how to accomplish this? Update I went back to my attempt to have doDml() refresh afterwards by calling doSelect() and it works. My original attempt didn't work because doSelect() wasn't sending notifications of its changes. Still, I'm concerned that this isn't how Oracle's documentation says to do it so I have no idea if this is correct or a kludge or a plain bad idea. So, my original question still stands. A: I logged an SR with Oracle. Their response was that if you override doDML() and do not call super.doDML() then you lose the automatic refresh functionality of the framework. They wouldn't comment on my solution, which was to call doSelect(false) after any inserts or updates in my doDML() override. Their policy is that if you want advice on customizations, you should engage Oracle Consulting.
{ "pile_set_name": "StackExchange" }
Q: Python: Turning arrays into text files I have this processed data in the format of: x = [1,2,3,4,5,6] and so on. How could I take this list and turn it into a .txt file? A: In python, you can write to a file using the write command. write() writes the contents of a string into the buffer. Don't forget to close the file as well using the close() function. data = [1,2,3,4,5,6] out = open("output.txt", "w") for i in data: out.write(str(i) + "\n") out.close()
{ "pile_set_name": "StackExchange" }
Q: hadoop: In which format data is stored in HDFS I am loading data into HDFS using spark. How is the data stored in HDFS? Is it encrypt mode? Is it possible to crack the HDFS data? how about Security for existing data? I want to know the details how the system behaves. A: HDFS is a distributed file system which supports various formats like plain text format csv, tsv files. Other formats like parquet, orc, Json etc.. While saving the data in HDFS in spark you need to specify the format. You can’t read parquet files without any parquet tools but spark can read it. The security of HDFS is governed by Kerberos authentication. You need to set up the authentication explicitly. But the default format of spark to read and write data is - parquet
{ "pile_set_name": "StackExchange" }
Q: Disparadores vs Procedimientos Almacenados Luego de buscar en internet encontré varios tutoriales sobre el tema, pero lo que aún no me queda claro es cuando usar un disparador y cuando un procedimiento almacenado. Muchas gracias por cualquier posible orientación!!! Atentamente, Miguel Angel A: La principal diferencia entre los triggers y stored procedures: Es que los triggers son procedimientos que se ejecutan automáticamente, cuando se produce un evento sobre el que se quiere trabajar. Para esto existen tres tipos de eventos que pueden disparar un trigger: INSERT, DELETE y UPDATE. El trigger se programa para realizar una tarea determinada que se debe hacer siempre que se produzca uno de los eventos antes mencionados. No requiere intervención humana o programática y no se puede detener. Tiene algunas características: No recibe parámetros de entrada o salida. Los únicos valores de entrada son los correspondientes a los de las columnas que se insertan, y sólo son accesibles por medio de ciertas pseudovariables (NEW y OLD). No se puede ejecutar una operación INSERT/UPDATE/DELETE sobre la misma tabla donde el TRIGGER se está ejecutando. No se puede ejecutar una tarea sobre otra tabla, si la segunda tiene un trigger que afecte a la tabla del primer trigger en ejecución (circularidad). No se puede invocar procedures desde un TRIGGER. No se puede invocar un SELECT que devuelva una tabla resultado en el TRIGGER. Otros Un stored procedure es un procedimiento almacenado que debe ser invocado para ejecutarse. Puede recibir parámetros y devolver parámetros. Puede manejar cualquier tabla, realizar operaciones con ellas y realizar iteraciones de lectura/escritura. Puede devolver una tabla como resultado. también valores dentro de los parámetros del prototipo si los mismos son también de salida. Existen en la base donde se crean, pero no dependen de ninguna tabla. Pueden aceptar recursividad (pero no es recomendable). Otros ---–--------- En resumen si vas a realizar una auditoría de las tablas de tu base de datos utiliza triggers. Si quieres utilizar procedimientos almacenados puede ser para sacar un listado de clientes. Esa acción será repetida en el sistema pero el trabajo lo realiza directamente la base de datos
{ "pile_set_name": "StackExchange" }
Q: 固定widthの親要素内の子要素でmin-width指定 固定widthの親要素内で、子要素のmin-widthを指定してmin-width〜親のwidth内でスケールさせたいのですが、以下のコードだと子要素がmin-widthを無視して親要素と同じ幅になってしまいます。 どなたか解決策をご存知の方いらっしゃいましたら、ご教示ください。 <div class="parent"> <div class="child"></div> </div> .parent { width: 500px; } .child { min-width: 300px; max-width: 500px; } A: div 要素の標準は display: block なので、何も指定しないと幅は親要素一杯に広がります。display プロパティを inline-block や table などにすると、中身に応じて幅が伸縮します。 .parent { width: 500px; background-color: darkblue; } .child { display: inline-block; min-width: 300px; max-width: 500px; font-size: 16px; background-color: yellow; } <div class="parent"> <div class="child">child 1</div> <div class="child">child 2 ##################################</div> <div class="child"> child 3 ===================================================== </div> </div>
{ "pile_set_name": "StackExchange" }
Q: MVVM: Notifying property change in the UI I am building a logger. The UI(LoggerView) binds to three properties of LogItem: the DateTime, Status, and the Message. When I run the program, the logging events do get created and logged into the UI properly. However, when I close the UI, log more additional events, and open the UI once more, the additional events do get logged into events but they do not appear in the UI. The problem is that the UI is not being notified when new LogItems are being added to the collection. How can I notify the UI when additional LogItems is being added? LoggerViewModel: [Export] [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.Shared)] public class LoggerViewModel : ViewModelBase { protected static readonly ILog log = LogManager.GetLogger(typeof(LoggerViewModel)); private Hierarchy h = LogManager.GetRepository() as Hierarchy; [ImportingConstructor] public LoggerViewModel() { LogItems = new ObservableCollection<LogItem>(); foreach (var customLog in CustomLogger.GetLogItems()) { var logItem = new LogItem(customLog.TimeStamp, customLog.Status, customLog.Message); LogItems.Add(logItem); } } private ObservableCollection<LogItem> _logItems; public ObservableCollection<LogItem> LogItems { get { return _logItems; } set { _logItems = value; } } private DateTime _timeStamp; public DateTime TimeStamp { get { return _timeStamp; } set { if (value == _timeStamp) return; _timeStamp = value; NotifyPropertyChanged("TimeStamp"); } } private Level _status; public Level Status { get { return _status; } set { if (value == _status) return; _status = value; NotifyPropertyChanged("Status"); } } private string _message; public string Message { get { return _message; } set { if (value == _message) return; _message = value; NotifyPropertyChanged("Message"); } } } LoggerView XAML: <ListView Grid.Row="1" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" VerticalContentAlignment="Bottom" ItemsSource="{Binding LogItems}"> <ListView.View> <GridView> <GridViewColumn Width="150" Header="Date And Time" DisplayMemberBinding="{Binding Path=DataContext.TimeStamp, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock TextWrapping="WrapWithOverflow" TextAlignment="Center"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Width="50" Header="Status" DisplayMemberBinding="{Binding Path=DataContext.Status, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock TextWrapping="WrapWithOverflow" TextAlignment="Center"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Width="1800" Header="Message"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock TextWrapping="WrapWithOverflow" Text="{Binding Path=DataContext.Message, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> LoggerView Logic: [Export] [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)] public partial class LoggerView : Window { private LoggerViewModel _viewModel; protected static readonly ILog log = LogManager.GetLogger(typeof(LoggerView)); private Hierarchy h = LogManager.GetRepository() as Hierarchy; [ImportingConstructor] public LoggerView(LoggerViewModel viewModel) { _viewModel = viewModel; this.DataContext = _viewModel; InitializeComponent(); } CustomLogger: LogItems is being created from events public class CustomLogger { protected static readonly ILog log = LogManager.GetLogger(typeof(CustomLogger)); static MemoryAppender memoryAppender = new MemoryAppender(); private Hierarchy h = LogManager.GetRepository() as Hierarchy; public CustomLogger() { log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(@"C:\Users\username\Documents\GitHub\MassSpecStudio\MassSpecStudio 2.0\source\MassSpecStudio\Core\app.config")); memoryAppender = h.Root.GetAppender("MemoryAppender") as MemoryAppender; } public static ObservableCollection<LogItem> GetLogItems() { var events = memoryAppender.GetEvents(); ObservableCollection<LogItem> LogItems = new ObservableCollection<LogItem>(); foreach (LoggingEvent loggingEvent in events) { DateTime TimeStamp = loggingEvent.TimeStamp; Level Status = loggingEvent.Level; string Message = loggingEvent.RenderedMessage; LogItems.Add(new LogItem(TimeStamp, Status, Message)); } return LogItems; } } LogItem: public class LogItem : INotifyPropertyChanged { private DateTime _datetime; private Level _status; private string _message; public LogItem(DateTime datetime, Level status, string message) { this._datetime = datetime; this._status = status; this._message = message; } public enum LogLevel { Debug = 0, Info = 1, Warn = 2, Error = 3, Fatal = 4, } public DateTime TimeStamp { get { return _datetime; } set { if (_datetime != value) { _datetime = value; RaisePropertyChanged("DateTime"); } } } public Level Status { get { return _status; } set { if (_status != value) { _status = value; RaisePropertyChanged("Status"); } } } public string Message { get { return _message; } set { if (_message != value) { _message = value; RaisePropertyChanged("Error"); } } } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } } LoggerMenuItem: [Export] public partial class LoggerMenuItem : MenuItem { protected static readonly ILog log = LogManager.GetLogger(typeof(LoggerMenuItem)); private readonly IServiceLocator _serviceLocator; [ImportingConstructor] public LoggerMenuItem(IServiceLocator serviceLocator) { _serviceLocator = serviceLocator; InitializeComponent(); } private void MenuItem_Click(object sender, RoutedEventArgs e) { LoggerView window = _serviceLocator.GetInstance<LoggerView>(); window.Owner = Application.Current.MainWindow; window.Show(); } } UPDATE: I noticed that my static method GetLogItems() from CustomLogger is only execute when the UI is opened during the first time. GetLogItems() does not execute after when the events get updated. Is there a way to notify property change in the events? To solve this problem, I think it will be best to get the setters for LogItems, DateTime, Status, and Message to fire whenever the UI is being fired. The MenuItem_Click method is responsible for firing the UI. Is it possible to call NotifyPropertyChanged right before window.Show()? A: I think you are replacing the LogItems ObservableCollection after the binding has been resolved and you are not calling NotifyPropertyChanged to inform the UI. Try changing the LogItems property to call NotifyPropertyChanged: private ObservableCollection<LogItem> _logItems; public ObservableCollection<LogItem> LogItems { get { return _logItems; } set { _logItems = value; NotifyPropertyChanged("LogItems"); } } I think you need to change the columns like this: <GridView> <GridViewColumn Width="150" Header="Date And Time" DisplayMemberBinding="{Binding TimeStamp}"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock TextWrapping="WrapWithOverflow" TextAlignment="Center" Text="{Binding}"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Width="50" Header="Status" DisplayMemberBinding="{Binding Status}"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock TextWrapping="WrapWithOverflow" TextAlignment="Center" Text="{Binding}"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Width="1800" Header="Message" DisplayMemberBinding="{Binding Message}"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock TextWrapping="WrapWithOverflow" Text="{Binding}"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView>
{ "pile_set_name": "StackExchange" }
Q: Function Redefinition of the Same Pattern for Every Argument Type I had to synchronize a thread-unsafe output function so that it doesn't crash when multiple threads try to interact with the standard output at the same time. I have done some C, but I am quite new to C++ programming. In C there aren't usually that much generic functions, but in C++ I can see one method or overloaded operator having even ten or more versions with different argument types. In my program below I locked operator<< of QTextStream by making another function print() calling QTextStream::operator<<. I would like to change my code that whenever I call QTextStream::operator<<, it is automatically the mutex locked version. How can this be done? Also, one little subquestion is that why doesn't my code work when I put the QMutex global variable in as a local variable of print()? QTextStream qout(stdout); QMutex mutex; template<typename T> void print(T t) { QMutexLocker locker(&mutex); qout << t << flush; } class my_thread : public QThread { public: int n; my_thread() { n = 0; } void run() { while(n < 10) { print(n++); msleep(500); } } }; int main() { enum { N_THREADS = 10 }; std::array<my_thread, N_THREADS> thread_array; for (auto& thread : thread_array) { thread.start(); } for (auto& thread : thread_array) { thread.wait(); } return 0; } A: How about this (not tested)? class LockedTextStream { private: QMutex mutex; QTextStream textStream; public: template <class... Args> LockedTextStream(Args&&... args) : textStream(std::forward<Args>(args)...) {} template <class T> LockedTextStream& operator<<(const T& t) { QMutexLocker locker(&mutex); textStream << t; return *this; } }; LockedTextStream sharedStream(stdout); ... sharedStream << n++; .... This wrapper should take any constructor arguments and forward them to QTextStream, and should lock any call to operator<<(). The reason QMutex can't be a local variable inside a function is that then the mutex is allocated in the context of that function. The whole point of a mutex is that you are operating on the same mutex in every thread.
{ "pile_set_name": "StackExchange" }
Q: KeyError: 0 in Python I'm trying to get the values of the first object's direction and station returned in this JSON, but I'm getting the following error KeyError: 0 Here's my code: print(json.dumps(savedrequest, indent=4)) savedstation = savedrequest[0]['station'] saveddirection = savedrequest[0]['direction'] And this is what it's returning in the print: { "-bas": { "email_address": "[email protected]", "direction": "Southbound", "station": "place-har" }, "-bus": { "email_address": "[email protected]", "direction": "Southbound", "station": "place-su" } } I don't know what -bas or -bus is going to be when it gets returned, I need to select the first object in the array. A: Your JSON was decoded into an "object" (called a dict in python), it's not an array. As such, it has no particular "order". What you think is the "first" element may not actually be stored that way. There's no guarantee that the same object will be first each time. What you could try, however, is to convert these dicts into OrderedDicts by using the object_pairs_hook parameter of json.loads (and json.load). An OrderedDict is like a dict, but it remembers the that order elements were inserted into it. import json from collections import OrderedDict savedrequest = json.loads(data, object_pairs_hook=OrderedDict) # Then you can get the "first" value as `OrderedDict` remembers order #firstKey = next(iter(savedrequest)) first = next(iter(savedrequest.values())) savedstation = first['station'] saveddirection = first['direction'] (This answer is thanks to https://stackoverflow.com/a/6921760 and https://stackoverflow.com/a/21067850)
{ "pile_set_name": "StackExchange" }
Q: Application exe icon not displayed ... because it is in a dll My application is build in C#4, using Prism (CAL) and WPF. We have the application (the .exe). The splash screen and the icon are in a .dll that serves as the branding dll. So, we have different dll for different branding flavor of our application. The problem is the following: When pinning the EXE on the task bar, the icon is the generic one from MFC (and not the one in the branding dll) When accessing the EXE from the start menu, the problem is the same. Any idea on how to solve this? Regard, A: You must set the icon property of the shortcut to something like "C:\blah\my.dll". This can be done manually or through your MSI packaging software.
{ "pile_set_name": "StackExchange" }
Q: With solid-state equipment, when would one use a dummy load? With vacuum-tube-based transmitters, you'd need to tune the output finals to achieve maximum power output, and this was commonly done into some sort of dummy load (either a purpose-made dummy load or something simple like a light bulb) while aiming for maximum power output on or near the desired operating frequency. However, solid state equipment doesn't need the finals tuned to the operating frequency. On the other hand, they are much more sensitive to antenna impedance mismatches. Seeing that antenna impedance mismatches are not caught or solved by first tuning into a dummy load, in what situations is a dummy load useful with a purely solid-state transmitter (where any external amplifier is considered part of the transmitter)? A: Any time you don't want to transmit RF. For example, if you have an oscilloscope and spectrum analyzer and would like to test the output of your transmitter (e.g. to make sure it's on frequency, that the waveform is OK and not getting cut off, that you don't have any spurious signals being transmitted) you might want to transmit into a dummy load rather than an antenna to prevent interfering with another transmittion and taking up bandwidth that you don't really need. It can also be helpful to test your transmitter's power output in the absence of any SWR mismatch or reflected signal.
{ "pile_set_name": "StackExchange" }
Q: ImageMagick: Transparent Backgrounds for JPEG, not PNG I'm using ImageMagick to convert PDF files to PNGs. (Lots of text, so I'd rather use PNG over JPEG.) I'm doing this on OS X, 10.8.2. I tried using Ghostscript, then ImageMagick, as was done here and I got a gray background. I shortened it to one line, since ImageMagick can work with PDFs and tried this: convert -background transparent -transparent white \ Background-Page01.pdf TestClearX1.png I've tried that with PNG files and JPEG files. (And with and without -transparent white as well.) If it's a JPEG, I can get a white background (which is probably clear, but in my viewer, I can't tell), but with a PNG, I always get a dark background. I thought about, as a test, trying to generate a BMP, then converting that to PNG, but it won't generate BMP files. How can I get a transparent background for a PNG file? And if that's not possible, since JPEG files are not good for text, is there a better alternative? A: There's two ways to export a PDF in LibreOffice, and one way does not provide any warnings. The other way provides a warning that PDF/A cannot have transparent objects. The problem is you're using PDF/A files that don't support transparent objects—this results in your PNG always having a background colour.
{ "pile_set_name": "StackExchange" }
Q: How to verify a number similar to WhatsApp? I know this question has been asked before, however, what has not been answered yet is, an sms is sent to your cellphone and WhatsApp automatically reads the token/authentication code from the sms, without requiring the user to enter the authentication code, then WhatsApp automatically enters the authentication code in the EditText area and then the installation of the App starts automatically. Similarly, how can my App automatically read the authentication code from the message and enters this authentication code in the EditText area automatically followed by the installation of the App automatically. Any help or guidance regarding this would be highly appreciated. A: WhatsApp reads your inbox and finds the message sent from it only, After that Whatsapp fetches the authentication code and display it to the view. To implement such feature you need to write a Broadcast received which get the details when any SMS received and then you can filter that message to fetch your authentication code. Refer this article. http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87
{ "pile_set_name": "StackExchange" }
Q: Which field to study to learn & create a.i generated simulations? I wasn't sure how to title this question so pardon me please. You may have seen at least one video of those "INSANE A.I created simulation of {X} doing {Y & Z} like the following ones: A.I learns how to play Mario A.I swaps faces of {insert celebrity} in this video after 16hrs. etc... I want to know what I have to learn to be able to create for example a program that takes xyz-K images of a person as training data and changes it with another person's face in a video. Or create a program that on a basic level creates a simulation of 2 objects orbiting /attracting each other /colliding like this: What field/topic is that? I suspect deep learning but I'm not sure. I'm currently learning machine learning with Python. I'm struggling because linear regression & finances /stock value prediction is really not interesting compared to teaching objects in games to do archive something or create a program that tries to read characters from images. A: You need to define "simulation" more specific. Playing Mario, Swapping face on image/video, or generating simulation of objects that are orbiting use different techniques. Playing Mario or "AI that playing game": the AI agent trained on available environment (Mario game, so the environment is not generated) and learn the best sequential actions to achieve the goal. It runs the game thousand times, when it did a wrong action then it gets "penalties" that improve its knowledge. The algorithm that can be used is Reinforcement Learning, but some earlier paper use Genetic Algorithm to generate the best action Face swap: It's close to computer vision area, some methods that I know use Style Transfer principle (Convolutional Neural Network) to make transformation of face of one image to another image. You can read the basic of style transfer here. Generating physical movement: I don't know too much about this topic but I know there are some papers talk about this, Fluid Net from Google workers and this paper from TU Munchen. At a glance they also use CNN to improve the result but the main simulation came from Euler Fluid Equation. So if you need to generate object that orbiting, I think you need to find equations that models that movement. Hope it helps!
{ "pile_set_name": "StackExchange" }
Q: Creating flashcards for grammatical rules that requires a few steps of thought, such as SPOCK versus WEIRDO If there's grammar rule that requires a couple of steps of thought in order to create the correct output, how do I put it into flashcards? For example, Spanish has (as well as imperative) the subjunctive and indicative moods where subjunctive is used by Wishes, Emotions, Impersonal expressions, Recommendations, Doubts and denial, and Ojalá (collectively WEIRDO), and indicative is used by Speech, Perceptions, Occurrences, Certainty, and Knowledge (SPOCK). If I was being super methodical in doing the grammar of a sentence, I'd look at a sentence like "Espero que vengas a la fiesta." and do the following steps to determine the grammar of "vengas": "Espero" is a Wish about the verb "vengas". A Wish is a WEIRDO WEIRDO uses the subjunctive. The second person subjunctive present tense of venir is vengas What approach should I take for putting all of this into my brain? Should I just create a grammar cloze card that basically says The sentence is "Espero que ____ a la fiesta.", the verb in the blank is venir in the second person present Or should I create additional flash cards for parts of the process, and if so, how would that work? The spaced repetition software I'm using is Anki, if that's relevant. A: The purpose of grammar flash cards is to "acquire" grammar rules rather than "learning" them. I am borrowing this distinction from Stephen Krashen (see Stephen Krashen's Theory of Second Language Acquisition by Ricardo E. Schütz). Learning grammar means that you consciously learn the grammar rules and apply them in exercises. Language acquisition refers increasing your language skills by means of "comprehensible input". Of course, any self learner will want to speed up the process, which is why many use flash cards, and flash cards force production of language (through spaced testing as opposed to simply spaced viewing). So the question becomes how you can "acquire" grammar rules faster than simply through comprehensible input. The answer is being exposed to "patterns". For example, the use of the subjunctive after "esperar" in "Espero que vengas a la fiesta" would be such a pattern. Grammar rules try to capture those patterns, but Krashen is skeptical about the effectiveness of learning those rules. So here is what I would do with flash cards that help you acquire "grammar patterns", using the sentence from the question as an example: On the "front", I would just put Espero que [(tu) venir] a la fiesta. On the "back", I would put the full sentence, with the solution (vengas) highlighted or in bold. Below the solution, you can put the rule, e.g. "Esperar is a WEIRDO and requires the subjunctive" (or the same in Spanish). The idea is that you have multiple cards that exercise the same rule, so each card exposes you to the same pattern in two ways: first by testing you on it (front of the card), and second by reminding you of the rule, which is mentioned on the back. This means I would remove all the English content from the front ("The sentence is (...), , the verb in the blank is venir in the second person present") for two reasons: (1) it is not in your native language and (2) it makes the "prompt" too long, or at least longer than it needs to be. I would also translate the rule on the back into Spanish (which in this case requires finding an alternative to "WEIRDO"), so the flash cards are entirely in the target language. The downside to this approach in Anki is that, as far as I can remember, you can't use Anki's built-in cloze card type for this, since this card type does not allow you to add additional notes that appear only with the solution. Instead, you need to use a basic card type, and manually add the solution and the grammar note to the back.
{ "pile_set_name": "StackExchange" }
Q: How to bind a Python socket to a specific domain? I have a Heroku application that has a domain moarcatz.tk. It listens for non-HTTP requests using Python's socket. The documenatation states that if I bind a socket to an empty string as an IP address, it will listen on all available interfaces. I kept getting empty requests from various IP addresses, so I assume that setting the socket to only listen for connections to moarcatz.tk would fix the problem. But I don't know how to bind a socket to a domain name. I tried 'moarcatz.tk' and gethostbyname('moarcatz.tk'), but both give me this error: OSError: [Errno 99] Cannot assign requested address What's up with that? A: You can't control this via your code, but you can control this via Heroku. Heroku has a pretty nifty DNS CNAME tool you can use to ensure your app ONLY listens to incoming requests for specific domains -- it's part of the core Heroku platform. What you do is this: heroku domains:add www.moarcatz.tk Then, go to your DNS provider for moarcatz.tk and add a CNAME record for: www <heroku-app-name>.herokuapp.com This will do two things: Point your DNS to Heroku. Make Heroku filter the incoming traffic and ALLOW it for that specific domain.
{ "pile_set_name": "StackExchange" }
Q: Qlikview Substring and charindex equivalent to show values after the - character I have a field which has the values field good - examplea good - exampleb bad - examplep ugly - examplet ugly - exampley I want to only show values after the - character. My example output would be field examplea exampleb examplep examplet exampley In SQL it would be simply SUBSTRING('ugly - exampley',CHARINDEX('- ', 'ugly - exampley', 1)+2,250) AND SUBSTRING(field,CHARINDEX('- ', field, 1)+2,250) What is the equivelant in Qlikview A: You can either use mid (with index) or subfield as follows: Mid & Index The equivalent of your statement would be: mid(field, index(field,'- ', 1) + 2, 250) Here, mid is the equivalent of SUBSTRING and index equivalent of CHARINDEX. However, in QlikView, mid's third parameter (number of characters to return) is optional, so you could instead use mid(field, index(field,'- ', 1) + 2) which would return the remainder of the field value after the -. Subfield Subfield allows you to delimit your input string with another string and then return a specific delimited substring. In your case, the below would do the trick: subfield(field, ' - ' , 2) For example, for the string good - examplea, this breaks it down by looking for the delimiter -. This results in two strings, good and examplea. The last parameter, 2, tells subfield to return examplea (rather than good which could be obtained by using 1 as the third parameter). The good thing about subfield in your case is that you do not need to specify how many characters to return as subfield will return all characters to the end of the string.
{ "pile_set_name": "StackExchange" }
Q: How to subtract from numbers following a string in VIM? I am trying to subtract from numbers following a string in VIM, for example this (searched) input: CustomModelData: 1 And my preferred (replaced) output: CustomModelData: -2147483647 The number that I am trying to subtract from the numbers is 2147483648. I tried using this in VIM, but it doesn't work since there is a string in the expression, I want to keep the string while also subtracting from the number that follows: :%s/CustomModelData: \d\+/\=/CustomModelData: submatch(0)-2147483648/g A: You can use following minor adjustment to have the match start at the number so the replacement only sees the number to adjust %s/\vCustomModelData: \zs\d+/\=submatch(0)-2147483648/g \zs anything, sets start of match
{ "pile_set_name": "StackExchange" }
Q: How to exclude data in sql when a particular combination of columns determine its duplicativeness? I have a dataset which as far as I know is correct. It looks as below. enter image description here QuoteStatus Quoteid batchID EffDate Iteration Months Revenue 1 Block Ready 275576 900265 3/1/2019 1 1096 635791 2 Block Ready 275654 900265 3/1/2019 1 1096 635791 3 Sold 275654 900265 3/1/2019 2 1096 635791 However, I have a requirement that when a certain combination of columns put together, each record has to be unique. From the resultset – I see this as a duplicate record because the combination of QuoteStatus = ‘Block Ready’ and Iteration = ‘1’ repeats more than once. (Even though QuoteID is distinct) I do not want row 1 to appear and I cannot simply remove “QuoteID” from Select statement because I want it to display . I have tried ROW_NUMBER ( ) OVER ( PARTITION BY QuoteId Order by QuoteID ) as ROW_Partition. However the result is not what i am looking for. I cannot exlclude ROW_Partition = '1' because that would still leave row 2. QuoteStatus Quoteid batchID EffDate Iteration ROW_Partition Months Revenue 1 Block Ready 275576 900265 3/1/2019 1 1 1096 635791 2 Block Ready 275576 900265 3/1/2019 1 2 1096 635791 3 Block Ready 275576 900265 3/1/2019 1 3 1096 635791 4 Block Ready 275576 900265 3/1/2019 1 4 1096 635791 5 Block Ready 275654 900265 3/1/2019 1 1 1096 635791 6 Block Ready 275654 900265 3/1/2019 1 2 1096 635791 7 Block Ready 275654 900265 3/1/2019 1 3 1096 635791 8 Block Ready 275654 900265 3/1/2019 1 4 1096 635791 9 Sold 275654 900265 3/1/2019 2 5 1096 635791 10 Sold 275654 900265 3/1/2019 2 6 1096 635791 11 Sold 275654 900265 3/1/2019 2 7 1096 635791 12 Sold 275654 900265 3/1/2019 2 8 1096 635791 I want to remove row 1 without explicitly excluding the QuoteID = ‘275576’ because this could happen to many other Quotes. A: I think you want to calculate the row number based on the columns you want to be distinct, keeping in mind that to filter on ROW_NUMBER you'll need to wrap it in a subquery or CTE (SQL Row_Number() function in Where Clause): ROW_NUMBER() OVER (PARTITION BY QuoteStatus, Iteration ORDER BY QuoteID) as seqnum You can then filter on this value.
{ "pile_set_name": "StackExchange" }
Q: How to accept a query and return an async task? I am getting the following exception: Cannot create an EDM model as the action 'Get' on controller 'Accounts' has a return type 'System.Web.Http.IHttpActionResult' that does not implement IEnumerable<T>. When attempting to query my endpoint: http://localhost:8267/api/accounts The AccountsController that is doing the work: public async Task<IHttpActionResult> Get(ODataQueryOptions options) { var query = options.Request.RequestUri.PathAndQuery; var client = new HttpClient(); var crmEndPoint = @"HTTPS://MYCRMORG.COM/API/DATA/V8.1/"; HttpResponseMessage response = await client.GetAsync(crmEndPoint+query); object result; if (response.IsSuccessStatusCode) { result = await response.Content.ReadAsAsync<object>(); return Ok(result); } return NotFound(); } What am I doing wrong? How do I simply add the PathAndQuery to my crmEndPoint and return the result? A: The OData framework provides extra response formatting/querying rules on top of plain Web API. Using ODataQueryOptions parameter requires that the action method returns either IQueryable<T> or IEnumerable<T>. ODataQueryOptions just helps to parse the incoming OData request url making parameters such as $filter and $sort accessible through properties. Your code doesn't need this service because all it does is just redirect the request to the crmEndPoint. So, instead of using options.Request you can access the request object through the Request property of the controller and drop the parameter altogether. Here's the code: public async Task<IHttpActionResult> Get() { var query = Request.RequestUri.PathAndQuery; var client = new HttpClient(); var crmEndPoint = @"HTTPS://MYCRMORG.COM/API/DATA/V8.1/"; HttpResponseMessage response = await client.GetAsync(crmEndPoint + query); object result; if (response.IsSuccessStatusCode) { result = await response.Content.ReadAsAsync<object>(); return Ok(result); } return NotFound(); }
{ "pile_set_name": "StackExchange" }
Q: At runtime, when is the std library completely initialized for it to be used without breaking the code? I am working on a project which includes startup code prior to the call to main. I am however unaware of the std library initializations. I know that the following code will throw a segmentation fault. #include <iostream> void foo(void) __attribute__((constructor)); void foo() { std::cout << "foo" << std::endl; } int main() { std::cout << "Simple program to throw a segmentation fault" << std::endl; } The above code can be made to work by force initializing the ostream buffer (not sure if it's exactly ostream) by using std::ios_base::Init mInitializer;. This would mean that the std library was not completely initialized at this point (that is my inference of the above example). So when can I use std functions without actually breaking the code? Is there a way to force initialize complete std library? A: The documentation for the constructor attribute says this: However, at present, the order in which constructors for C++ objects with static storage duration and functions decorated with attribute constructor are invoked is unspecified. This means that ELF constructors and static objects (as the one used for initialization of std::cout) do not mix well. On the other hand, std::cout is a historical exception because it does not rely on a constructor in the C++ standard library. On ELF systems, ELF constructors run in topological order. This means that the dynamic linker looks at the library dependencies (the DT_NEEDED entries) and delays initialization of libraries before their dependencies are initialized. As a result, C++ code can assume that the C++ run-time library is fully initialized when ELF constructors run and global objects defined by the application are constructed. The only exception is a C++ library which preempts routines used by the standard C++ standard library itself (via ELF symbol interposition), and if there are cyclic dependencies among the libraries, so that there is no correct initialization order. Both cases are not common, and unless you write a custom malloc or something like that, can be avoid with proper application design.
{ "pile_set_name": "StackExchange" }
Q: How to show/hide animated component in Aurelia I have a sub-component which I'd like to show/hide in an animated way, just like Bootstrap's collapse component. The button which triggers visiblity is located in the outer view (not inside the sub-view). When using the basic syntax <compose view-model="edit-x" model.bind="x" show.bind="shouldShow"></compose> (or the corresponding syntax with custom html element name), it works, but it just appears (not animated). Suggestion 1 - use Aurelia animation I did try to add a class='au-animate' with no effect (also included the aurelia-animator-css in the main.js for that). Suggestion 2 - Use Bootstrap Another possible solution could be perhaps to utilize Bootstrap, and pass in a second parameter (visible) to the component, then have the component in some way monitor that variable and call $('.collapse').collapse('toggle'). How would I then pass in two variables in model.bind? And how to monitor it? Can one use @bindable on a setter? Suggestion 3 - Use Bootstrap from the outside component Maybe the easiest would be to call $('#subcomponentName .collapse').collapse('toggle') from the outside view? It this ugly? I do reference elements in the sub-view from the outer view, which is maybe crossing some boundaries, but code will be small? A: (Answering my own question here, as there was more to do to get it working) Got this to work: First by following @Gusten's comment about if.bind instead of show.bind. Then by adding CSS classes for animation. It also seems like the animated element (the one with au-animate css class) must be the first element below the root <template> element. So in my CSS: div.test.au-enter-active { -webkit-animation: fadeInRight 1s; animation: fadeInRight 1s; } and then the element: <template> <div class="test au-animate"> ... (notice the au-animate + my own test class, the latter just there for easy selection of the element) The fadeInRight CSS animation is defined elsewhere in the CSS file.
{ "pile_set_name": "StackExchange" }
Q: Error creating bean with name 'hibernate4AnnotatedSessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.programcreek.helloworld.controller.CountryService com.programcreek.helloworld.controller.CountryController.countryService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'countryService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.programcreek.helloworld.controller.CountryDAO com.programcreek.helloworld.controller.CountryService.countryDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'countryDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.programcreek.helloworld.controller.CountryDAO.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernate4AnnotatedSessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.lang.Class[]' for property 'annotatedClasses'; nested exception is java.lang.IllegalArgumentException: Cannot find class [org.arpit.java2blog.model.Country] Pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>test</groupId> <artifactId>test</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>test Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.1.6.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Spring dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.1.6.RELEASE</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.24</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.0.1.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> </dependencies> <build> <finalName>test</finalName> </build> </project> dispatcher-servlet.xml : <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <context:component-scan base-package="com.programcreek.helloworld.controller" /> <annotation-driven /> <resources mapping="/resources/**" location="/resources/" /> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix"> <beans:value>/WEB-INF/views/</beans:value> </beans:property> <beans:property name="suffix"> <beans:value>.jsp</beans:value> </beans:property> </beans:bean> <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" /> <beans:property name="url" value="jdbc:mysql://localhost:3306/nstoreb2cbeta" /> <beans:property name="username" value="root" /> <beans:property name="password" value="root" /> </beans:bean> <beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <beans:property name="dataSource" ref="dataSource" /> <beans:property name="annotatedClasses"> <beans:list> <beans:value>org.arpit.java2blog.model.Country</beans:value> </beans:list> </beans:property> <beans:property name="hibernateProperties"> <beans:props> <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect </beans:prop> <beans:prop key="hibernate.show_sql">true</beans:prop> </beans:props> </beans:property> </beans:bean> <tx:annotation-driven transaction-manager="transactionManager" /> <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" /> </beans:bean> </beans:beans> web.xml : <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// A: To solve Spring dependency issues, navigate to the root Nested Exception. Typically, auto-wiring will be a slew of nested exceptions that dependencies cannot be autowired, so the specific bean failure will be hidden at the bottom of the original exception log. In this case... Cannot find class [org.arpit.java2blog.model.Country] As this is not listed as a possible orp.arpit.java2blog dependency in the pom.xml, it must reside within the src/main/java directory or any other defined source directories within the Maven project itself. Either the class is incorrectly typed in the servlet, or the file is incorrectly placed in the project.
{ "pile_set_name": "StackExchange" }
Q: Looping through all the pages in Python web scrapping error I am trying to scrape a webpage and looping through all the pages within a link. When I am looping through all the pages below code gives many duplicates lst = [] urls = ['https://www.f150forum.com/f118/2019-adding-adaptive-cruise-454662/','https://www.f150forum.com/f118/adaptive-cruise-control-module-300894/'] for url in urls: with requests.Session() as req: for item in range(1,33): response = req.get(f"{url}index{item}/") soup = BeautifulSoup(response.content, "html.parser") threadtitle = soup.find('h1',attrs={"class":"threadtitle"}) for item in soup.findAll('a',attrs={"class":"bigusername"}): lst.append([threadtitle.text]) for div in soup.find_all('div', class_="ism-true"): try: div.find('div', class_="panel alt2").extract() except AttributeError: pass try: div.find('label').extract() except AttributeError: pass result = [div.get_text(strip=True, separator=" ")] comments.append(result) Modification to the code as below doesnot give duplicates but skips last page of the url comments= [] for url in urls: with requests.Session() as req: index=1 while(True): response = req.get(url+"index{}/".format(index)) index=index+1 soup = BeautifulSoup(response.content, "html.parser") if 'disabled' in soup.select_one('a#mb_pagenext').attrs['class']: break posts = soup.find(id = "posts") threadtitle = soup.find('h1',attrs={"class":"threadtitle"}) for item in soup.findAll('a',attrs={"class":"bigusername"}): lst.append([threadtitle.text]) for div in soup.find_all('div', class_="ism-true"): try: div.find('div', class_="panel alt2").extract() except AttributeError: pass # sometimes there is no 'panel alt2' try: div.find('label').extract() except AttributeError: pass # sometimes there is no 'Quote' result = [div.get_text(strip=True, separator=" ")] comments.append(result) removing " if 'disabled' in soup.select_one('a#mb_pagenext').attrs['class']: break" this code gives infinite loop. How can I loop through pages without getting duplicates A: Just change the order of the if condition to bottom of the loop so that once all the items grab then this will check disabled or not.If you provide at top this will break without capturing the values from last page. comments= [] for url in urls: with requests.Session() as req: index=1 while(True): response = req.get(url+"index{}/".format(index)) index=index+1 soup = BeautifulSoup(response.content, "html.parser") posts = soup.find(id = "posts") threadtitle = soup.find('h1',attrs={"class":"threadtitle"}) for item in soup.findAll('a',attrs={"class":"bigusername"}): lst.append([threadtitle.text]) for div in soup.find_all('div', class_="ism-true"): try: div.find('div', class_="panel alt2").extract() except AttributeError: pass # sometimes there is no 'panel alt2' try: div.find('label').extract() except AttributeError: pass # sometimes there is no 'Quote' result = [div.get_text(strip=True, separator=" ")] comments.append(result) if 'disabled' in soup.select_one('a#mb_pagenext').attrs['class']: break
{ "pile_set_name": "StackExchange" }
Q: My relative layout hides another relative layout I am working on an application which is like a menu and my relative layout for the menu with options is covered by another relative layout that contains an image. Could you guys tell me where am I going wrong? Realistically, I would want the menu to be at the top with options in the middle and the image to be at the bottom. Here's my xml code: <RelativeLayout android:id="@+id/RelativeLayout02" android:layout_width="match_parent" android:layout_height="wrap_content" android > <ImageView android:id="@+id/imageView3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentTop="false" android:contentDescription="@string/desc" android:scaleType="fitEnd" android:src="@drawable/half" /> </RelativeLayout> <RelativeLayout android:id="@+id/RelativeLayout01" android:layout_width="match_parent" android:layout_height="247dp" > <ImageView android:id="@+id/imageView1" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:contentDescription="@string/desc" android:src="@drawable/paranoid_android" /> <TextView android:layout_width="200dp" android:layout_height="50dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_centerInParent="true" android:text="@string/menu" android:textColor="@color/white" android:textSize="@dimen/titlefont" /> <ImageView android:id="@+id/imageView2" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:contentDescription="@string/desc" android:src="@drawable/paranoid_android" /> </RelativeLayout> Thanks. A: Just put it all in one relative layout - that's what relative layouts are for. Add the image before or after the rest of the components to have it below or above them. Relative layouts are designed such that moving one view around in them has no effect on the positioning of other views in the layout, so you can layer views on top of each other.
{ "pile_set_name": "StackExchange" }
Q: Nested hierarchy of arrays in javascript How do I create a dynamic set of arrays in javascript, to form a hierarchy of arrays? I would like this to work dynamically. How to create a root array, that will always be there, and each new array dynamically created, will be nested in the previous array to form a hierarchy. A: ...do you know what's going in these arrays, or have any idea how big or deep they go? And are you talking about only indexed arrays, or objects with named properties, as well? If all you want is arrays: var rootArr = [], rootArr[0] = [[],[]], rootArr[1] = [[ [],[],[ [] ], ]]; So now you've got arrays nested like: [ [ [], [] ], [ [ [], [], [ [] ] ] ] ]; As you can probably see, you can happily go on building deeper and deeper arrays. If you wanted to do this dynamically, you could create them in a for loop, if you know your values, or a recursive function, if you've got checks... Keep in mind, though, accessing data inside of these will suck. To get at the deepest array, you'd have to go: rootArr[1][0][2][0]; //just to access the array //then you'd need the index of whatever was inside...
{ "pile_set_name": "StackExchange" }
Q: how to pass message from asytask to activite I want to send some message from asytask to me main activity. I want to do this with message object (handler). in my main activity I created this final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { msg.toString(); } }; the object that I pass to asytask new splash(first.this,mHandler).execute(); and the asytask that send message to activity from this method protected void onPostExecute(String result) { Message msg = new Message(); Bundle bundle = new Bundle(); bundle.putString("ActivityName",this.newActivity); msg.setData(bundle); mHandler.sendMessage(msg); Dialog.dismiss(); the logcat 09-29 11:55:41.631: E/AndroidRuntime(473): FATAL EXCEPTION: main 09-29 11:55:41.631: E/AndroidRuntime(473): java.lang.NullPointerException 09-29 11:55:41.631: E/AndroidRuntime(473): at tools.splash.onPostExecute(splash.java:109) 09-29 11:55:41.631: E/AndroidRuntime(473): at tools.splash.onPostExecute(splash.java:1) 09-29 11:55:41.631: E/AndroidRuntime(473): at android.os.AsyncTask.finish(AsyncTask.java:417) 09-29 11:55:41.631: E/AndroidRuntime(473): at android.os.AsyncTask.access$300(AsyncTask.java:127) 09-29 11:55:41.631: E/AndroidRuntime(473): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429) 09-29 11:55:41.631: E/AndroidRuntime(473): at android.os.Handler.dispatchMessage(Handler.java:99) 09-29 11:55:41.631: E/AndroidRuntime(473): at android.os.Looper.loop(Looper.java:123) 09-29 11:55:41.631: E/AndroidRuntime(473): at android.app.ActivityThread.main(ActivityThread.java:3683) 09-29 11:55:41.631: E/AndroidRuntime(473): at java.lang.reflect.Method.invokeNative(Native Method) 09-29 11:55:41.631: E/AndroidRuntime(473): at java.lang.reflect.Method.invoke(Method.java:507) 09-29 11:55:41.631: E/AndroidRuntime(473): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 09-29 11:55:41.631: E/AndroidRuntime(473): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 09-29 11:55:41.631: E/AndroidRuntime(473): at dalvik.system.NativeStart.main(Native Method) A: According to your comments above the application crashes on Dialog.dismiss(). Dialog variable is correctly declared and instatiated? Are you making it null somewhere? (I suppose Dialog is a variable and not a class, right?) EDIT: OK, but the problem still remains the same. Have you checked that the mHandler object is properly declared instatiated and it is not null? You are passing it as a param in the AsyncTask. Can you post the code where you take the mHandler and you store it "somewhere"? Is the AsyncTask in the same scope of the Handler?
{ "pile_set_name": "StackExchange" }
Q: Applying a Power on a Sum of Gaussians to Enhance Resolution There is so-called Power Transform technique in signal processing where the unresolved signal is sharpened by raising each data to a constant positive power. The example shown below is a sum of two Gaussians, $G_1$ and $G_2$ plotted against time. In order to resolve the peaks one can apply a power of 5 to each data point. The result is the resolved pair as shown in the bottom figure. The above operating is equivalent to raising the sum of Gaussians $G_1$ and $G_2$ to the power 5, i.e., $(G_1 + G_2)^5$ then according to the binomial theorem, we should get 6 peaks, because not only we have the first and the second peak raised to power 5, we will have a "mixture" of the two peaks as well- the other terms of the binomial theorem. No matter how well we zoom, we cannot see the missing $G_1^4$$G_2$, $G_1^3$$G_2^2$ peaks? If power transform of 5 is applied to two peaks, we are left with two peaks not six. Where do the peaks corresponding to the other binomial terms go? Thanks. A: The binomial theorem is not necessarily involved: the top waveform is simply pointwise raised to the 5-th power, as others have noted, and there are no missing peaks that should be seen. To illustrate, consider the following crude hand-drawn figure: I drew this in my simulation software, so it was automatically "digitized" as I drew it. Obviously, I am poor at freehand drawing with a computer mouse, but I was only trying to make two peaks, with no underlying peak shape in mind. Then the second figure shows what happens if the digitized values from the first figure are raised to the 5-th power and plotted: Still ugly, but better resolved. Now taking into account a more recent answer by @MBaz (https://dsp.stackexchange.com/a/60750/41790), there is still one loose end. To see this, consider two Gaussians, $G_1(x)$ and $G_2(x)$, and adding them. Their sum function, i.e., $G_1(x)$ + $G_2(x)$, does not look like either function. Of course, we know the sum function's two constituent summand functions. But the sum function does not show them: it only shows their sum. Now square the sum function. Then the pointwise squaring works as expected. Alternatively, if we use the expansion, then we get three constituent functions: $G_1^2(x)$, $G_2^2(x)$ and $2G_1(x)G_2(x)$. So the squared sum function is just the sum of these three constituent functions and none of the three are 'visible' to us: we only see the sum of the three constituent functions. So this is why we can never see the 'extra' peak functions. Indeed, we cannot see any of the constituent functions. We can only see the their sum and should not have expected that sum to display its constituent functions.
{ "pile_set_name": "StackExchange" }
Q: How can I display a Thankyou page after user downloads file? I am using this little pusher php file to download an 'exe' file for the user to save when they fill-out a form. header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); with this method there is no link to the online $file location for someone to follow but for some reason I cannot display a thank you page after or even immediately before the code is executed. I've tried header( "Location: $thankyouurl" ); immediately after the above code, but nothing is ever displayed and I've tried echoing the html source of the thank you page just prior to running the above code, but that causes the exe file to be downloaded to the web page actually crashing the browser. Any suggestions??? A: Point the user directly to a static page that displays your thank you message. Then, use JavaScript to set the window.location to your download script. If your download page's headers are set up correctly, the browser will start downloading the file, while your user is reading your thank you message. Make sure to display a direct download link in case the user has JavaScript disabled. Example: index.php <a href="thankyou.php">Click here to download.</a> thankyou.php <html> <head> <script type="text/javascript"> function startDownload() { window.location = "/download.php"; } </script> </head> <body onload="startDownload();"> <h1>Thank you!</h1> <p>Your download will start in a moment. If it doesn't, use this <a href="download.php">direct link.</a></p> </body> download.php header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); Update In order to pass data from index.php on to the download script, you could use GET variables. The link to the thankyou.php page would become thankyou.php?download=12 where download is an ID for you to grab the correct file. You would then pass that variable on to your download script by echoing it out in your markup like so: index.php <a href="thankyou.php?download=12">Click here to download.</a> thankyou.php <html> <head> <script type="text/javascript"> function startDownload() { window.location = "/download.php?file=<?=$_GET['download']?>"; } </script> </head> <body onload="startDownload();"> <h1>Thank you!</h1> <p>Your download will start in a moment. If it doesn't, use this <a href="download.php?file=<?=$_GET['download']?>">direct link.</a></p> </body> You'd then grab the value in your download script and handle it any way you like.
{ "pile_set_name": "StackExchange" }
Q: Decreasing space between y-axis points in python I'm currently trying to make a plot where there are only two possible y values 1 and 2, and no matter what I try or how large or small I make the figure, the two points are super far apart. Is there a way to make the two y points closer to each other? I essentially would like to make the individual points on the sample graph below more visible. this is the code I'm currently using to make my figure: groups = df.groupby("response") for name, group in groups: plt.plot(group["trials"], group["tcolor"], marker="o", linestyle="", label=name) plt.legend() plt.show() example of desired result A: Not sure if I know what you mean, but try something like this: plot.ylim(-0.6, 0.6)
{ "pile_set_name": "StackExchange" }
Q: Why does the principal/interest applied to my balance fluctuate in spite of making payments on-time? In my first payment on 6/03/2011, the principal applied to my balance was $261.11 and the interest was $221.64. As I kept making the payment on-time, the principal applied to my balance kept increasing and the interest kept decreasing. But as you can see on 11/03/2011, the money applied to my principal went down and the interest taken went up. The same thing happened on 04/03/2012. I thought as I kept making payments on-time, the applied interest should decrease every time and the applied principal should increase. Am I wrong? This is how my loan payment history statement looks like: **04/03/2012 Payment Received $482.75 Interest $160.96 Principal $321.79** 03/02/2012 Payment Received $482.75 Interest $142.77 Principal $339.98 02/03/2012 Payment Received $482.75 Interest $154.97 Principal $327.78 01/04/2012 Payment Received $482.75 Interest $157.34 Principal $325.41 12/05/2011 Payment Received $482.75 Interest $169.92 Principal $312.83 **11/03/2011 Payment Received $482.75 Interest $166.60 Principal $316.15** 10/03/2011 Payment Received $482.75 Interest $141.54 Principal $341.21 09/07/2011 Payment Received $482.75 Interest $165.26 Principal $317.49 08/08/2011 Payment Received $482.75 Interest $172.73 Principal $310.02 07/08/2011 Payment Received $482.75 Interest $197.05 Principal $285.70 06/03/2011 Payment Received $482.75 Interest $221.64 Principal $261.11 A: The payments might be on time, but the aren't made the same numbers of days apart: $142.77 in interest from February 3rd to March 2nd is 28 days @ 5.0899 per day $154.97 in interest from January 4th to February 3rd is 30 days @5.166 per day The percentage of the daily payment for interest is decreasing, but the numbers of days wasn't constant.
{ "pile_set_name": "StackExchange" }
Q: SQL Query: insert if not already exists from 2 tables I am trying to insert rows if they don't exist (for specific values) in this table. My table where I insert is insertTable: date (date) created (datetime) category (varchar) companyId (int) price (decimal 6,3) I select my rows from an inner join between two tables doing : declare @currentDateTime datetime = getDate() declare @currentDate date = getDate() INSERT INTO insertTable (date, created, category, companyId, price) SELECT @currentDate, @currentDateTime, '30 Day', company.companyId, product.price FROM product INNER JOIN company ON product.companyid = company.companyid WHERE product.price >= 0.31 AND ... other conditions on company fields ... AND NOT EXISTS( SELECT * FROM insertTable WHERE insertTable.price = product.price AND insertTable.date = @currentDateTime AND insertTable.companyid = product.companyid AND LTRIM(RTRIM(insertTable.category)) = '30 Day' ) What am I doing wrong please? Thanks --edited after Gordon Linoff Comment. I insert the result of that select in my insertTable. My issue is that I get duplicates in insertTable. If insertTable had 2014-09-26 | 2014-09-26 02:25:00 | 30 Day | 32650 | 0.600 My select will return something like 2014-09-26 | 2014-09-26 02:36:00 | 30 Day | 32650 | 0.600 However I already have that companyID and price in the insert table A: You problem statement cannot be accurate rate is not defined you are missing created and you are comparing date to @currentDateTime SELECT @currentDate, @currentDateTime, '30 Day' , company.companyId, product.price FROM product JOIN company ON product.companyid = company.companyid and product.price >= 0.31 AND ... other conditions on company fields ... AND NOT EXISTS( SELECT * FROM insertTable WHERE insertTable.date = @currentDate --AND insertTable.created = @currentDateTime AND insertTable.price = product.price AND insertTable.companyid = product.companyid AND LTRIM(RTRIM(insertTable.category)) = '30 Day' )
{ "pile_set_name": "StackExchange" }
Q: How to use the events 'pause' and 'resume' in an Angular/Ionic project? In an Angular/Ionic project, where would I use the following attributes to appropriately handle my needs? document.addEventListener('pause', actiontobeperformed, false); document.addEventListener('resume', actiontobeperformed , false); My needs are: I am building an app that is protected, meaning that you can only view the content when: you enter the correct access code your session has not timed out But when you go to Home, then I want somehow to record that the session is over and that the user needs to authenticate when he comes back in the app. A: The cordova pause event might be your answer. And resume when they return.
{ "pile_set_name": "StackExchange" }
Q: Is this wall in my kitchen load bearing? Sorry for another one of these questions but here goes: My house is a single story bungalow, built in 1976. I can't get hold of the blueprints because the city in which I live does not keep blueprints before 1979. The house has an unfinished basement and has a main support beam running under the width of the main part of the house. I want to renovate the house by opening up the dinning, living, and kitchen. This would involve taking out all of one wall and part of another. The one that will be entirely remove is pretty obviously not load bearing because, among other reasons, it runs parallel to the trusses. However, there is a wall that runs perpendicular to the trusses and it's the one I'm not sure of and wanted to get some advice. Yes I'll be consulting a professional but I'm looking for some preliminary thoughts. In my diagram below is shown the dinning room, living room and kitchen layout in my house. The two interior walls I want to remove are shown, with the one labelled "Is it load bearing?" being the wall in question. The large area to the left of the interior walls is open from the back to the front of the house with no supporting beam. Trusses run in the direction shown and they are the same across the entire roof. I've verified that the "Is it Load Bearing?" wall has 24 inch-on-centre studs and removing the section I want to remove would mean removing 3 of 5 studs. The wall has a single top plate and does not sit directly over the main support beam in the basement. It sits about 1 ft off that beam. Any thoughts on whether the wall is load bearing? Is there anything I've missed? Ext. Wall +---------------------------------------------- | Dinning Room | | | | ^ | E | | | Kitchen x | | | t | Truss | . | Direction | | | | Is it Load Bearing? W | | +------------------------- a | v l | l | | | Living Room +---------------------------------------------- Ext.Wall A: I’m glad “you’re going to consult a professional.” I’m sure he’ll check: 1) that all the trusses are identical, including the connectors, 2) there are no additional loads on the trusses over the kitchen area, like air conditioner, etc., 3) the floor beam is just for floor loading, (the wall does not need to sit directly over the beam in order to transfer the roof load to the floor beam, 4) the wall that is being removed is not for lateral bracing (are you in a high seismic or wind zone), 5) the perimeter footings are not reduced in size by the kitchen area, Btw, it’s not just removing the wall...you’ll need to remove/reroute plumbing, electrical, hvac, etc. too.
{ "pile_set_name": "StackExchange" }
Q: how to delete a backbone model I have created the following code and i'm unable to destroy a model from the backend. I get a 'model is not defined error'. I don't know why it cannot find a model? what parameters am i missing? am i wrong in adding this in this list view? should i add it in the models view? and if that is the case i added the save new model in the list view so can't see why i can't add it her. window.LibraryView = Backbone.View.extend({ tagName: 'section', className: 'mynotes', events: { "keypress #new-title": "createOnEnter", //"keypress #new-content": "createOnEnter" "click .mybutton": "clearCompleted" }, initialize: function() { _.bindAll(this, 'render'); this.template = _.template($('#library-template').html()); this.collection.bind('reset', this.render); this.collection.bind('add', this.render); this.collection.bind('remove', this.render); }, render: function() { var $mynotes, collection = this.collection; $(this.el).html(this.template({})); $mynotes = this.$(".mynotes"); collection.each(function(mynote) { var view = new LibraryMynoteview({ model: mynote, collection: collection }); $mynotes.append(view.render().el); }); return this; }, createOnEnter: function(e) { var input = this.$("#new-title"); var input2 = this.$("#new-content"); //var msg = this.model.isNew() ? 'Successfully created!' : "Saved!"; if (!input || e.keyCode != 13) return; // this.model.save({title: this.$("#new-title").val(), content: this.$("#new-content").val() }, { var newNote = new Mynote({title: this.$("#new-title").val(), content: this.$("#new-content").val()}); this.collection.create(newNote); }, clearCompleted: function() { this.model.destroy(); this.collection.remove(); } }); A: You have to bind your clearCompleted method to this: _.bindAll(this, 'render', 'clearCompleted');
{ "pile_set_name": "StackExchange" }
Q: Should we migrate old Robotics questions to the new Robotics Beta site when it opens? With the latest combined Robotics proposal now very close to full commitment, I was wondering whether we should consider migrating old questions which are about robotics, but not about electronics to the new stack exchange site, when it comes out of private beta. It seems clear that new questions that are about robotics, but not about electronics should be migrated, when deemed appropriate by the community and our moderators, but should we consider migrating questions which predate the creation of the Robotics site? A: This might be moot now. Questions older then 60 days may not be migrated. This means even if we wanted to we could not migrate most of our content. Sorry. I was going to post an answer saying I was behind it but I would only migrate truly great content and only after the site had built up basic content.
{ "pile_set_name": "StackExchange" }
Q: Backbone.js: Fetch a collection of models and render them I am learning JavaScript MVC application development using Backbone.js, and having issues rendering model collection in the view. Here's what I want to do: After the page finishes loading, retrieves data from the server as model collection Render them in the view That's all I want to do and here is what I have so far: $(function(){ "use strict"; var PostModel = Backbone.Model.extend({}); var PostCollection = Backbone.Collection.extend({ model: PostModel, url: 'post_action.php' }); var PostView = Backbone.View.extend({ el: "#posts-editor", initialize: function(){ this.template = _.template($("#ptpl").html()); this.collection.fetch({data:{fetch:true, type:"post", page:1}}); this.collection.bind('reset', this.render, this); }, render: function(){ var renderedContent = this.collection.toJSON(); console.log(renderedContent); $(this.el).html(renderedContent); return this; } }); var postList = new PostCollection(); postList.reset(); var postView = new PostView({ collection: postList }); }); Problem As far as I know, Chrome is logging the response from the server and it's in JSON format like I want it. But it does not render in my view. There are no apparent errors in the console. The server has a handler that accepts GET parameters and echos some JSON: http://localhost/blog/post_action.php?fetch=true&type=post&page=1 [ { "username":"admin", "id":"2", "title":"Second", "commentable":"0", "body":"This is the second post." }, { "username":"admin", "id":"1", "title":"Welcome!", "commentable":"1", "body":"Hello there! welcome to my blog." } ] A: There are 2 potential problems with your code. The event listener callback should be registered before calling the collection.fetch(). Otherwise, you might miss the first reset event as it might be triggered before the listener is registered. The reset event is not enough to ensure that the view will re-render every time the collection gets updated. Also, note that it is a good practice to use the object.listenTo() form to bind events as it will ensure proper unregistration when the view is closed. Otherwise, you may end up with what is known as Backbone zombies. Here is a solution. this.listenTo( this.collection, 'reset add change remove', this.render, this ); this.collection.fetch({ data: { fetch:true, type:"post", page:1 } }); Note how you can register multiple events from the same object by separating them with whitespace.
{ "pile_set_name": "StackExchange" }
Q: $\operatorname{rank}AB\leq \operatorname{rank}A, \operatorname{rank}B$ Prove that if $A,B$ are any such matrices such that $AB$ exists, then $\operatorname{rank}AB \leq \operatorname{rank}A,\operatorname{rank}B$. I came across this exercise while doing problems in my textbook, but am not sure where to start for the proof of this. I think columnspace might be involved in the proof, although I am not sure. A: I think it is best to prove two things that are stronger statements: $x\in \ker B \Rightarrow x\in \ker AB$, $y\in \text{im}\;AB \Rightarrow y\in \text{im}\;A$. Together with the rank-nullity theorem, I believe this provides a solution not in the link @Amzoti provided above. Edit- nevermind, it's in there, but not all in one place.
{ "pile_set_name": "StackExchange" }
Q: Can someone explain the logic behind this? Why in the 'for' loop is it <12? How can the i var be over 2 in the array? I see this similar question asked in the java section. But i am just using 1 for loop. Why in the for() loop is it i<12?? I am not understanding the logic of that. There are only 3 variables in the episodes array. Can someone lead me in the right direction to understand this? I was just doing some practice on openclassroom.com. class Episode { constructor(title, duration, hasBeenWatched) { this.title = title; this.duration = duration; this.hasBeenWatched = hasBeenWatched; } } let firstEpisode = new Episode('Dark Beginnings', 45, true); let secondEpisode = new Episode('The Mystery Continues', 45, false); let thirdEpisode = new Episode('An Unexpected Climax', 60, false); // Create your array here // ==================================== let episodes = [firstEpisode, secondEpisode, thirdEpisode]; // ==================================== const body = document.querySelector('body'); for(let i = 0; i < 12; i++) { //this <12 i don't understand let newDiv = document.createElement('div'); newDiv.classList.add('series-frame'); let newTitle = document.createElement('h2'); newTitle.innerText = 'The Story of Tau'; let newParagraph = document.createElement('p'); newParagraph.innerText = `${episodes[i].title} ${episodes[i].duration} minutes ${episodes[i].hasBeenWatched ? 'Already been watched' : 'Not yet watched'}`; newDiv.append(newTitle); newDiv.append(newParagraph); body.append(newDiv); } A: There is no sense of using 12 in forLoop. However you can use episodes.length to iterate over episodes array class Episode { constructor(title, duration, hasBeenWatched) { this.title = title; this.duration = duration; this.hasBeenWatched = hasBeenWatched; } } let firstEpisode = new Episode('Dark Beginnings', 45, true); let secondEpisode = new Episode('The Mystery Continues', 45, false); let thirdEpisode = new Episode('An Unexpected Climax', 60, false); // Create your array here // ==================================== let episodes = [firstEpisode, secondEpisode, thirdEpisode]; // ==================================== const body = document.querySelector('body'); for(let i = 0; i < episodes.length; i++) { //this <12 i don't understand let newDiv = document.createElement('div'); newDiv.classList.add('series-frame'); let newTitle = document.createElement('h2'); newTitle.innerText = 'The Story of Tau'; let newParagraph = document.createElement('p'); newParagraph.innerText = `${episodes[i].title} ${episodes[i].duration} minutes ${episodes[i].hasBeenWatched ? 'Already been watched' : 'Not yet watched'}`; newDiv.append(newTitle); newDiv.append(newParagraph); body.append(newDiv); }
{ "pile_set_name": "StackExchange" }
Q: jQuery smooth image change I wonder how to make image change in my jQuery script smoother. I also have an animate() chain, can I attach the "src" change into it or not? Sadly I can't use images as CSS backgrounds... Here's a little sample... function growBigger(element) { $(element) .find(".inside") .animate({ width: curWidth, height: curHeight, marginTop:"0px" }) .end() .find(".label") .animate({ fontSize:curTitleSize }) .end() $(element + " .inside .thumbnail").attr("src","images/big_" + curPanel + ".jpg") } A: Solved by preloading the images. Take a look at http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
{ "pile_set_name": "StackExchange" }
Q: Can't Generate Large Prime Numbers I'm trying to generate large prime numbers in Java. I use BigIntegers for this. Here is my code to generate and store 10 prime numbers inside an array. public static void primeGenerator() { BigInteger[] primeList = new BigInteger[10]; BigInteger startLine = new BigInteger("10"); int startPower = 6; BigInteger endLine = new BigInteger("10"); int endPower = 9; int j = 0; for (BigInteger i = fastExp(startLine,startPower); i.compareTo(fastExp(endLine,endPower)) <= 0; i = i.add(BigInteger.ONE)) { if (checkPrimeFermat(i) == true && j < 10) { primeList[j] = i; j++; } } System.out.println(primeList[0]); System.out.println(primeList[1]); System.out.println(primeList[2]); System.out.println(primeList[3]); System.out.println(primeList[4]); System.out.println(primeList[5]); System.out.println(primeList[6]); System.out.println(primeList[7]); System.out.println(primeList[8]); System.out.println(primeList[9]); } I wrote my own fastExp function to generate numbers faster. Here are my other functions. public static BigInteger getRandomFermatBase(BigInteger n) { Random rand = new Random(); while (true) { BigInteger a = new BigInteger (n.bitLength(), rand); if (BigInteger.ONE.compareTo(a) <= 0 && a.compareTo(n) < 0) { return a; } } } public static boolean checkPrimeFermat(BigInteger n) { if (n.equals(BigInteger.ONE)) return false; for (int i = 0; i < 10; i++) { BigInteger a = getRandomFermatBase(n); a = a.modPow(n.subtract(BigInteger.ONE), n); if (!a.equals(BigInteger.ONE)) return false; } return true; } public static void main(String[] args) throws IOException { primeGenerator(); } public static BigInteger fastExp (BigInteger x, int n){ BigInteger result=x; int pow2=powof2leN(n); int residue= n-pow2; for(int i=1; i<pow2 ; i=i*2){ result=result.multiply(result); } for(int i=0 ; i<residue; i++){ result=result.multiply(x); } return result; } private static int powof2leN(int n) { for(int i=1; i<=n; i=i*2){ if(i*2>2) return 1; } return 0; } } So the problem is when I try it with small numbers (for example startPower=3, endPower=5) it generates and prints prime numbers. But when I try it with big numbers (for example startPower=5, endPower=7) it doesn't generate anything. How can I improve my code to work with large numbers? Thank you A: First of all, I would like to point out that you did not write this code. You stole it from here and claimed that you wrote it, which is incredibly unethical. The code is correct. It's just slow. As you increase the power, the code takes increasingly longer. There are two reasons why this occurs: The Fermat test takes increasingly longer to apply. BigInteger operations take increasingly longer to execute. The Fermat test grows like O(k × log2n × log log n × log log log n). BigInteger's addition and subtraction grow like O(n). Obviously, BigInteger is what is slowing you down. Below is a profile of your code with the power set from 5 to 7. If you want your code to produce larger and larger primes, you should focus on reducing the number of operations you do on BigIntegers. Here is one such improvement: Take n.subtract(BigInteger.ONE) outside of your for loop. The result does not need to be calculated many times. Further suggestions will have to come from the Mathematics folks over on Mathematics Stack Exchange.
{ "pile_set_name": "StackExchange" }
Q: Select rows where ID is repeated, but value in another column is different I have a table like this: What I would like to be able to do is return the IDs and how many different types of fruit the ID is associated with other than 1 like so: Can someone help me out? I don't think it should be that difficult, but I haven't had much luck. Thanks! A: I think you want the having clause and count(distinct): select id, count(distinct fruit) as numfruit from t group by id having count(distinct fruit) > 1;
{ "pile_set_name": "StackExchange" }
Q: How do i CHECK if a year is between 2000 and the current year? I need to create a table for automobiles. Each automobile has a year of manufacture. The year of manufacture must be between 2000 and the current year. year_manufacture INTEGER CONSTRAINT nn_automobiles_year_manufacture NOT NULL CONSTRAINT ck_automobiles_year_manufacture CHECK ((year_manufacture>= 2000)AND(year_manufacture<= "current year")), A: See if such a workaround helps. Everything you've been already told stands. As you can't directly check the year against SYSDATE, create another column - THIS_YEAR - which won't be used anywhere in your code. It is automatically populated on each insert and gets current year. Constraint (which can't be inline) then compares YEAR_MANUFACTURE with THIS_YEAR. SQL> create table cars 2 (id number constraint pk_cars primary key, 3 name varchar2(20) not null, 4 this_year number(4) default extract (year from sysdate), 5 year_manufacture number(4), 6 -- 7 constraint ch_year_manufacture check (year_manufacture between 2000 and this_year) 8 ); Table created. SQL> Testing: SQL> -- OK - after 2000, before 2019 (which is the current year) SQL> insert into cars (id, name, year_manufacture) values (1, 'BMW', 2005); 1 row created. SQL> -- Wrong - before 2000 SQL> insert into cars (id, name, year_manufacture) values (2, 'Mercedes', 1998); insert into cars (id, name, year_manufacture) values (2, 'Mercedes', 1998) * ERROR at line 1: ORA-02290: check constraint (SCOTT.CH_YEAR_MANUFACTURE) violated SQL> -- Wrong - after 2019 (which is the current year) SQL> insert into cars (id, name, year_manufacture) values (3, 'Cooper', 2020); insert into cars (id, name, year_manufacture) values (3, 'Cooper', 2020) * ERROR at line 1: ORA-02290: check constraint (SCOTT.CH_YEAR_MANUFACTURE) violated SQL> -- OK - current year SQL> insert into cars (id, name, year_manufacture) values (4, 'Opel', 2019); 1 row created. SQL> SQL> select * from cars; ID NAME THIS_YEAR YEAR_MANUFACTURE ---------- -------------------- ---------- ---------------- 1 BMW 2019 2005 4 Opel 2019 2019 SQL>
{ "pile_set_name": "StackExchange" }
Q: Using map to return an empty array instead of [0] zero I have some working code that will take a string of words and return an array of the length of each word. For example: let str = "hello world" returns [5, 5] My issue is if str = "" (empty) it will return [0] instead of [] (empty array) which is what I'd like it to do. Does anyone have any ideas how I can alter my code to return this? Thank you! const arr = str.split(' '); return arr.map(words => words.length); A: You can return an empty array if the string is equal to '' (empty string): function count(str) { return (str === '') ? [] : str.split(' ').map(({length}) => length); } console.log(count('hello world')); console.log(count('')); A: Add a filter at the end. const str = ""; const arr = str.split(' '); console.log(arr.map(words => words.length).filter(count => count != 0));
{ "pile_set_name": "StackExchange" }
Q: constant variable declaration in Haskell To declare constant variables I can do following in Ruby class COLOR RED = 10 BLUE = 20 GREEM = 30 end COLOR::RED returns 10, COLOR::BLUE returns 20, and so on. How do I accomplish that in Haskell? I want to have a namespace name in front of my variable name. Maybe the example above is not a good example. For the case below, you can see including a namespace name will make a variable much easier to understand. class BASEBALL_TEAM GIANTS = 15 METS = 30 REDS = 45 ... end BASEBALL_TEAM::GIANTS is much clear than GIANTS. based on the comments below, it seems the only way I can accomplish it is by doing something like below: module Color (Color) where data Color = Red | Blue | Green deriving (Eq, Show, Ord, Bounded, Enum) fromEnum' x = (fromEnum x) + 10 to get integer value of 10 for Color.Red, I have to write fromEnum Color.Red, the syntax is not very clean. A: Untagged constants are bad. If you go with bunch of Int constants then you lose type-checking (think about possible values that Int -> whatever function takes as opposed to SomeConstType -> whatever) and possibly introduce bugs. You want a strong type instead: data Colour = Red | Blue | Green deriving (Show, Eq, Enum) Also, representing those values as integers is not really necessary in most cases. If you actually do need it, Enum typeclass provides toEnum and fromEnum. As for namespaces: modules are namespaces in Haskell. Put your type in a module and then you can import it qualified and you'll have your prefix: -- Colours.hs module Colours (Colour) where data Colour = ... -- SomeOtherModule.hs module SomeOtherModule where import qualified Colours foo = Colours.Red That said, creating modules just for this one type with constants (or importing them qualified) is not really necessary, because you can easily trace things by their types. A: Things are constant in Haskell by default, so red = 10 blue = 20 green = 30 would be equivalent. A more interesting question would be why you want to do this? There are likely better ways to accomplish what you want in Haskell. The answer by @CatPlusPlus shows a good way of doing this. This seems like a very basic Haskell question, so I'll politely point you to Learn you a Haskell, which, in my opinion, is the best resource to get started with Haskell. Another promising resource for learning Haskell is FP complete's School of Haskell, which is currently in beta, but I haven't tried it myself. This is a more interactive setting, where you can directly try things out in the browser.
{ "pile_set_name": "StackExchange" }
Q: Scala, P08 - pack I'm doing the packing problem from P08 from the 99 Problems, I think I'm doing this right but there's something wrong with the syntax of Scala that I think I don't know.. def pack(list: List[Char]): List[List[Char]] = { @tailrec def checkNext(a: List[List[Char]], prev: Char, l: List[Char] ): List[List[Char]] = { if (!l.nonEmpty) a else { val res = if (prev==l.head) List(a.head:::List(l.head)) else a:::List(List(l.head)) checkNext(res, l.head, l.tail) } } checkNext(List(List(list.head)), list.head, list.tail) } EDIT: sorry everyone, yes it compiles perfectly, but instead of doing what it is supposed to do, it merges everything and I cannot understand why. It should group nearby equal letters into lists of char, example: pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) => List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d), List('e, 'e, 'e, 'e)) A: You are adding characters to the wrong list : you want to append to a.last (the list you are currently working on), not a.head (which contains the list of the first equal characters you found). def pack(list: List[Char]): List[List[Char]] = { def checkNext(a: List[List[Char]], prev: Char, l: List[Char] ): List[List[Char]] = { if (!l.nonEmpty) a else { val res = if (prev==l.head) a.init:+(a.last:+l.head) // a.last contains the list you are currently adding to, // a.init's list are all completed else a:+List(l.head) // start a new list of character checkNext(res, l.head, l.tail) } } checkNext(List(List(list.head)), list.head, list.tail) } Note that this code has horrible performance, as appending is O(n) (so you should pretty much always try to replace (at least when inside a loop) it with prepend (which is O(1))). A better way to do this is to first reverse the input list and then prepend elements to the result list : def pack(list: List[Char]): List[List[Char]] = { def checkNext(a: List[List[Char]], prev: Char, l: List[Char]): List[List[Char]] = { if (!l.nonEmpty) a else { val res = if (prev == l.head) ((l.head::a.head)::a.tail) else List(l.head)::a checkNext(res, l.head, l.tail) } } checkNext(List(List[Char](list.last)), list.last, list.init.reverse) } or the more idiomatic : def pack(list: List[Char]) = { def checkNext(a: List[List[Char]], prev: Char, l: List[Char]): List[List[Char]] = l match { case Nil => a case h::tail if h == prev => checkNext((h::a.head)::a.tail,h,tail) case h::tail => checkNext(List(h)::a,h,tail) } checkNext(List(List[Char](list.last)), list.last, list.init.reverse) }
{ "pile_set_name": "StackExchange" }
Q: Nested mini-app with own router I have a web-app that has basically another mini-app (that lives inside a sidebar, drawer, etc) inside of it that needs its own navigation independent of the main app and does not affect the URL or browser History; but they need to share a redux store because changes in either need to be sychronised. <BrowserHistory> <ConnectedSwitchWithRouter> <Header /> {/* <Route/>s *} <Footer> {/* Mini-app here */} </Footer> </ConnectedSwitchWithRouter> </BrowserHistory> First, is this possible? I'm thinking the mini-app in might be able to use MemoryRouter, but I'm wondering how updating the mini-apps route would work. Can I use <Link>? I can't seem to find any documentation on this. A: Turns out yes, that works exactly as I expected. For navigation, I used onClick and props.history.push().
{ "pile_set_name": "StackExchange" }
Q: text[] in postgresql? I saw a field text[] (text array) in Postgresql. As far as I understood,it can store multiple text data in a single column. I tried to read more about it the manual: http://www.postgresql.org/docs/current/static/datatype-character.html but unfortunately nothing much was there about text[] column type. So can anyone help me to understand How to add a new value to text[] column? What will be the resultset when we query to retrieve the values of text[] column? EDIT I have a table containing 2 columns group_name and members. Each time a new person join the group,the new person's id should be inserted in the column members for that group_name. This is my requirement.A Group can contain 'n' number of members EDIT 2 Pablo is asking me to use two tables instead. May I know how this could be solved by using two different tables? Right now I am using comma(,) to store multiple values separated by comma. Is this method wrong? A: To insert new values just do: insert into foo values (ARRAY['a', 'b']); Assuming you have this table: create table foo (a text[]); Every time you do a select a from foo you will have a column of type array: db1=> select a from foo; a ------- {a,b} (1 row) If you want a specific element from the array, you need to use subscripts (arrays in PostgreSQL are 1-based): db=> select a[1] from foo; a --- a (1 row) Be careful when choosing an array datatype for your PostgreSQL tables. Make sure you don't need a child table instead.
{ "pile_set_name": "StackExchange" }
Q: node labelling not working d3 v5 I am trying to add labels inside my node but that doesn't seem to be working. //draw circles for the nodes var node = g.append("g") .attr("class", "nodes") .selectAll("circle") .data(nodes_data) .enter() .append("circle") .attr("r", radius) .attr("fill", circleColour); node.append("text") .attr("dx", 12) .attr("dy", ".35em") .text(function (d) { return d.name }); When I do inspect elements of the node, I can see the text inside the node: <circle r="15" fill="blue" style="touch-action: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);" cx="421.4930863434973" cy="221.26393165638473"><text dx="12" dy=".35em">some name</text></circle> But it doesn't display in chart. Can anyone please help me here? Here is the full plunkr: A: Per definition circle can have only animation elements and descriptive elements as content. So you cannot put text inside circle. Solution is to add multiple g elements for each node and then inside it have circle and text elements. var node = g.selectAll('.nodes') .data(nodes_data) .enter().append('g') .attr('class', 'nodes') node.append('circle') .attr("r", radius) .attr("fill", circleColour) node.append("text") .attr("dx", 12) .attr("dy", ".35em") .text(function (d) { return d.name }); and then in tick node.attr('transform', d => `translate(${d.x},${d.y})`); Here is working forked plunkr
{ "pile_set_name": "StackExchange" }
Q: Redirect $stdin to string in Ruby I'm writing a unit test for my class which reads inputs from stdin. In the unit tests, I'm hoping I can redirect the stdin stream to a string. How can I achieve this? A: To answer your literal question: unlike the constant STDIN, $stdin is just a global variable, you can replace it with another IO object: require 'stringio' $stdin = StringIO.new("foo\nbar") 2.times { puts gets } # => foo # => bar But it is probably a better idea to use a proper mocking framework instead, for example like this.
{ "pile_set_name": "StackExchange" }
Q: Origin of lighting the chanukiah Why did people start to light oil lamps on chanukah? How did the holiday come to be represented by lights? If in fact it was that the menorah was lit for eight days with oil, and that was considered the essence of the holiday, then why is there even a discussion about what is chanuka? A: (Building on my comment, at Isaac's suggestion:) The Or Zarua isn't saying that the oil with which the miracle occurred wasn't used for lighting the menorah. Indeed, he quotes the narrative in Menachos about how the Chashmonaim created a temporary menorah out of iron spits and used it for the lighting. (Bear in mind that iron is not to be allowed to touch the Altar - Ex. 20:21 and Deut. 27:5; Rambam, Hil. Beis Habechirah 1:15-16.) He simply says that the miracle had to last for eight days, because for seven of those days they were busy rebuilding and rededicating the altar, and therefore had no time to prepare new other oil; and he goes on to say that the holiday is called "Chanukah" in honor of this rededication. This use of oil for lighting was, of course, the continuation of the mitzvah recorded in the Torah (Ex. 27:20-21, Lev. 24:1-4) to light the menorah daily in the Mishkan, and later in the Beis Hamikdash.
{ "pile_set_name": "StackExchange" }
Q: Test if characters are in a string I'm trying to determine if a string is a subset of another string. For example: chars <- "test" value <- "es" I want to return TRUE if "value" appears as part of the string "chars". In the following scenario, I would want to return false: chars <- "test" value <- "et" A: Use the grepl function grepl(value, chars, fixed = TRUE) # TRUE Use ?grepl to find out more. A: Answer Sigh, it took me 45 minutes to find the answer to this simple question. The answer is: grepl(needle, haystack, fixed=TRUE) # Correct > grepl("1+2", "1+2", fixed=TRUE) [1] TRUE > grepl("1+2", "123+456", fixed=TRUE) [1] FALSE # Incorrect > grepl("1+2", "1+2") [1] FALSE > grepl("1+2", "123+456") [1] TRUE Interpretation grep is named after the linux executable, which is itself an acronym of "Global Regular Expression Print", it would read lines of input and then print them if they matched the arguments you gave. "Global" meant the match could occur anywhere on the input line, I'll explain "Regular Expression" below, but the idea is it's a smarter way to match the string (R calls this "character", eg class("abc")), and "Print" because it's a command line program, emitting output means it prints to its output string. Now, the grep program is basically a filter, from lines of input, to lines of output. And it seems that R's grep function similarly will take an array of inputs. For reasons that are utterly unknown to me (I only started playing with R about an hour ago), it returns a vector of the indexes that match, rather than a list of matches. But, back to your original question, what we really want is to know whether we found the needle in the haystack, a true/false value. They apparently decided to name this function grepl, as in "grep" but with a "Logical" return value (they call true and false logical values, eg class(TRUE)). So, now we know where the name came from and what it's supposed to do. Lets get back to Regular Expressions. The arguments, even though they are strings, they are used to build regular expressions (henceforth: regex). A regex is a way to match a string (if this definition irritates you, let it go). For example, the regex a matches the character "a", the regex a* matches the character "a" 0 or more times, and the regex a+ would match the character "a" 1 or more times. Hence in the example above, the needle we are searching for 1+2, when treated as a regex, means "one or more 1 followed by a 2"... but ours is followed by a plus! So, if you used the grepl without setting fixed, your needles would accidentally be haystacks, and that would accidentally work quite often, we can see it even works for the OP's example. But that's a latent bug! We need to tell it the input is a string, not a regex, which is apparently what fixed is for. Why fixed? No clue, bookmark this answer b/c you're probably going to have to look it up 5 more times before you get it memorized. A few final thoughts The better your code is, the less history you have to know to make sense of it. Every argument can have at least two interesting values (otherwise it wouldn't need to be an argument), the docs list 9 arguments here, which means there's at least 2^9=512 ways to invoke it, that's a lot of work to write, test, and remember... decouple such functions (split them up, remove dependencies on each other, string things are different than regex things are different than vector things). Some of the options are also mutually exclusive, don't give users incorrect ways to use the code, ie the problematic invocation should be structurally nonsensical (such as passing an option that doesn't exist), not logically nonsensical (where you have to emit a warning to explain it). Put metaphorically: replacing the front door in the side of the 10th floor with a wall is better than hanging a sign that warns against its use, but either is better than neither. In an interface, the function defines what the arguments should look like, not the caller (because the caller depends on the function, inferring everything that everyone might ever want to call it with makes the function depend on the callers, too, and this type of cyclical dependency will quickly clog a system up and never provide the benefits you expect). Be very wary of equivocating types, it's a design flaw that things like TRUE and 0 and "abc" are all vectors. A: You want grepl: > chars <- "test" > value <- "es" > grepl(value, chars) [1] TRUE > chars <- "test" > value <- "et" > grepl(value, chars) [1] FALSE
{ "pile_set_name": "StackExchange" }
Q: Is it faster to only query specific columns? I've heard that it is faster to select colums manually ("col1, col2, col3, etc") instead of querying them all with "*". But what if I don't even want to query all columns of a table? Would it be faster to query, for Example, only "col1, col2" insteaf of "col1, col2, col3, col4"? From my understanding SQL has to search through all of the columns anyway, and just the return-result changes. I'd like to know if I can achieve a gain in performance by only choosing the right columns. (I'm doing this anyway, but a backend API of one of my applications returns more often than not all columns, so I'm thinking about letting the user manually select the columns he want) A: In general, reducing the number of columns in the select is a minor optimization. It means that less data is being returned from the database server to the application calling the server. Less data is usually faster. Under most circumstances, this a minor improvement. There are some cases where the improvement can be more important: If a covering index is available for the query, so the index satisfies the query without having to access data pages. If some fields are very long, so records occupy multiple pages. If the volume of data being retrieved is a small fraction (think < 10%) of the overall data in each record. Listing the columns individually is a good idea, because it protects code from changes in underlying schema. For instance, if the name of a column is changed, then a query that lists columns explicitly will break with an easy-to-understand error. This is better than a query that runs and produces erroneous results.
{ "pile_set_name": "StackExchange" }
Q: How can I create a list of panels that contains fields connect by LiveBinding to a Dataset in FireMonkey? Delphi XE5 update 2 I am looking for a list of "panels" that will have the same layout (same controls) and each panel is created for each record of the DataSet existent. I need to use LiveBindings preferably. But if that is not possible I would like to know how to do the list of panels thing. You can see on this image below an example in a list of contacts (marked in red) I remember that in Delphi 6 VCL we had a component that were capable of such thing, we only needed to add the required DBEdit's and other DB Control on the first panel and it created a panel for each record of the table accordingly. A: There's a sample of doing something very similar to this in the ListView example in the \Samples\FireMonkey Mobile folder. Despite it's location, it's designed for Win32, iOS, and Android targets, so it's actually relevant here. (In XE6, it's in a slightly different location, in the Samples\Object Pascal\Mobile Samples\User Interface\ListView folder. The latest version of the sample is also available at SourceForge in the RAD Studio Demo repository.) There are samples of creating various types of custom ListItems in the demos in that folder, including some using Live Binding. Make sure to see the Readme.txt in that folder before opening any of the projects; it implements some design-time packages that allow you to configure the items in the IDE that require installation before the projects will load/compile. –
{ "pile_set_name": "StackExchange" }
Q: Making a "tree array" from an array in php I work with PHP. I have an array, made like this : (the level attribute is the level of the branch in the tree I want to make) Array ( [0] => stdClass Object ( [value] => Array ( [name] => Dog [level] => 1 ) ) [1] => stdClass Object ( [value] => Array ( [name] => Yorkshire [level] => 2 ) ) [2] => stdClass Object ( [value] => Array ( [name] => Rottweiler [level] => 2 ) ) [3] => stdClass Object ( [value] => Array ( [name] => Cat [level] => 1 ) ) ) My goal is to make some kind of tree array from it, something like this : Array ( [0] => stdClass Object ( [value] => Array ( [name] => Dog [level] => 1 ) ) Array ( [1] => stdClass Object ( [value] => Array ( [name] => Yorkshire [level] => 2 ) ) [2] => stdClass Object ( [value] => Array ( [name] => Rottweiler [level] => 2 ) ) ) [3] => stdClass Object ( [value] => Array ( [name] => Cat [level] => 1 ) ) ) But I really can't manage to do it. I even have issues to see the algorithm! Any help would be greatly appreciated. A: I managed to do it this way : $new = array(); foreach ($arr as $a){ $new[$a['parentid']][] = $a; } $tree = createTree($new, $new[0]); // changed print_r($tree); function createTree(&$list, $parent){ $tree = array(); foreach ($parent as $k=>$l){ if(isset($list[$l['id']])){ $l['children'] = createTree($list, $list[$l['id']]); } $tree[] = $l; } return $tree; } from arthur : create array tree from array list
{ "pile_set_name": "StackExchange" }
Q: Error installing addons in GRASS 7.0.2: File is not a zip file? When I attempt to install an addon in GRASS Setting->Install Extension from Addons and select the addon i want from the list (r.stream.order) i get the following error: "ERROR: File is not a zip file: http://wingrass.fsv.cvut.cz/grass70/addons/grass-7.0.2/r.stream.order.zip" I get a similar error no matter what addon I attempt to install. Is there a way to download the zip files and install locally? If so where should I download these? When I follow the addon links and locate the the location of this addon online, it does not contain any zip files. (https://svn.osgeo.org/grass/grass-addons/grass7/raster/r.stream.order/) What are the correct steps in successfully installing an addon? A: Version 7.0.2 is an older one. The current release is 7.0.4: https://grass.osgeo.org/news/56/15/GRASS-GIS-7-0-4-released/ If you are speaking about MS Windows, the older addons are still online but you would need to copy the files manually: https://wingrass.fsv.cvut.cz/grass70/x86/addons/ Installation trough g.extension is no longer supported for this version. Install the latest release or as @gene says, use Linux or Mac where the addons will be compiled exactly for your version.
{ "pile_set_name": "StackExchange" }
Q: when should I write code with `{{}}` and without `{{}}` in html of angular js project May be This is a simple question but it is challenging for me. In angularJS when i write {{}} in html code so i write code like this like if i talk about dynamic id, we write like code this <div ng-repeat = 'item in itmes track by $index'> <div id = "div-{{$index}}">{{item.name}}</div> </div> If i use any model without {{}} i write this example <input id = 'name' ng-model = "item.name"/> whenever i am coding in angular js, i write code without {{}} then if it is not work then i try code with {{}} and vise versa. and randomly 1 will correct Question is when i write code with {{}} and without {{}} in html code ? A: After the OP explained what exactly was the problem. So, the question here is very simple: when do we use {{}} and when we don't in the context of ng-model. When you do a <input type=... ng-model="someModel>, what you're essentially telling Angular is: "Here is an input element; attach $scope's someModel variable to the value of this input element. Now, you can use this in your JavaScript controller like so: $scope.someModel, but what about HTML? We have a templating language in Angular, and when you give it some variable (say someModel), it'll search its $scope for it, and then put in the value there. If it is unable to, it'll throw a nasty error. In essence, {{}} GETS the value, without that, you generally set the variable to gold the value of something. Very simply put, AngularJS thinks that the content within the brace is an expression, which must be resolved. Once it is, Angular puts the value of the resolved expression there. In the most basic of the terms, you just tell it: "Here is some expression; put the evaluated value instead." In ES6, we call it template strings. So, you'll use it for expressions which mutate after every iteration. Say, a loop or something. Places where you know what the answer is, or you have static content, you won't use it. Say you have the following bit of code: ... ... $scope.figureOne = 10; in your controller.js and the following in its view file: <div>My age is {{ figureOne }}</div> Angular gets the value from the $scope, and puts it there; so, the rendered form will be: My age is 10. However, if you had the following <div>My age is figureOne</div> This time, Angular knows that there is nothing to evaluate or resolve, so, it'll just render it as it is: My age is figureOne. I hope I made it clear! :)
{ "pile_set_name": "StackExchange" }
Q: How to get a count of rows qualified for clean-up in Change Tracking? Is there a way to get a rowcount for clean-up in Change Tracking? When I run the following command, I get the number of rows affected. However, I need this information, ahead of time. sp_flush_CT_internal_table_on_demand [ @TableToClean= ] 'TableName' Can I get this info from the system tables? A: There are many good blogs on a bunch of alerts you should have set up by default. Here is one, and here is another. This will prevent you from searching the error log for certain messages pertaining to this severity. However, it will alert you for any application or code that raises this severity and 16 is very common so you may not want to add that level to an alert. I'd add 19-25 though as well as other specified error messages contained in those blogs (823, 824, 825, 829, 832, 855, 856). To only be notified when that job fails, you can just add a notification on the job to alert you when it fails. First you will need to set up an operator so you can get emails, and then you'll just want to enable the notification on the job. If you do want to scan the error log for specific text though, I created a script that'll do just that. You can find it on GitHub here, and while it was designed to send daily emails with error log results, it can be ran adhoc.
{ "pile_set_name": "StackExchange" }
Q: Hrefs vs JavaScript onclick (with regard to Unobtrusive JavaScript) What is best practice with regard to using links/<a> tags with explicit hrefs to other pages in your site (i.e. href="/blah/blah/blah.html) vs having hrefs/divs/etc. that don't have an explicit href and have their onclick set within the document ready handler with JavaScript in say a main.js file. I'm not an expert when it comes to web development, but I'm enjoying learning jQuery and such and find myself subscribing to the notion of Unobtrusive JavaScript. While both options above don't break the "don't have JavaScript within the HTML" part of that mentality, I suppose I'm hung up on the "Separation of structure and presentation from behavior". While it's admittedly more natural for me to put an <a> tag in there and explicitly set the href, I find myself thinking that this is really behavior and thus should be set within the JS. Is that going to far, or am I just not used to it? The other side of me sees the benefit of putting it in the JS, b/c now I have the ability to completely control the behavior of that link without having to change anything within the HTML. I guess you'd say I'm on the proverbial fence. Please help get me down. =) (One note: The site uses JavaScript heavily, so the notion of providing functionality with JS turned off isn't really a concern as most of the site will not function without it.) A: That really is going too far for a multitude of reasons. It is mostly tricky code, which should be avoided. It provides no tangible benefit to your website. Doesn't have an eloquent fallback for no-js. It has negative effect on SEO. Specifically, bots wont run your script, and thus wont see the links and will ultimately not index your site properly. Probably most importantly, this effect can severely impact UX for screen readers or users with JS disabled (for instance, many mobile phone browsers disable JS) In the end, unless you have explicit need to break the mold (e.g. legacy support) you should try your best to follow unobtrusive design, and this is very obtrusive in the sense that you are using JavaScript to create a static structure, something that is far better to be done with HTML. A: Normal users won't really know the difference. However, search engines and SEO practices would require you to use the href="" to link to your other pages if you want the spiders to follow them. Same with if the visitor was using some screen reader or had some special accessibility needs. Many of those read the source code and not the DOM. In general if you are linking to pages and actions use the href. If you need to attach additional functionality or not really go to another page or action then use javascript onclick style, or use jQuery to attach events. A: Links are not behavior — they represent links between one document and another. Web browsers offer the behavior of navigating to the linked page when you click on links, but this is the browser's behavior, and each browser has its own conventions for how best to do this — for example, primary click might open the page in the current tab, middle-click might open in a new tab, and M4 might open the link in a new page. Replacing this raw information with behavior breaks the browser's ability to offer this kind of choice. And there are other clients that would be affected as well. Spiders and other bots will read your page for the information in your anchor tags to determine what the page is linked to. If you instead use "behavior," you're stripping this meaningful information from the page.
{ "pile_set_name": "StackExchange" }
Q: How to change prometheus alert manager port address I have downloaded prometheus alert manager from prometheus.io and try to run it. Alert manager is not running because some of our internal applications are running on the port 9093. So i need to change the alert manager running port from 9093 to some other port say 3002. How to change this? A: Run alertmanager binary with a --web.listen-address option. For example: alertmanager --web.listen-address=http://localhost:9876 alertmanager --web.listen-address=http://:9876 This flag was added some time ago and can be found in output of alertmanager -h command.
{ "pile_set_name": "StackExchange" }
Q: Can I change the output format of the "last" command to display the year? I'm trying to find a way to report on the most recent login for all users on my Solaris 10 server. I'm starting with the output of the last command. Using that command, I get output like this: bd9439 pts/1 vpn-xxx-xx-xxx-x Fri Oct 25 10:46 still logged in vf7854 pts/1 vpn-xxx-xx-xxx-x Fri Oct 25 10:23 - 10:38 (00:15) According to the man page, the date and time formats are controlled by locale. I've very rarely used locale settings. Is there something I can use that will change the display to include the "year" portion of the date? I'm hoping to get an output line similar to this: bd9439 pts/1 vpn-xxx-xx-xxx-x Fri Oct 25 2013 10:46 still logged in vf7854 pts/1 vpn-xxx-xx-xxx-x Fri Oct 25 2013 10:23 - 10:38 (00:15) It's not clear to me if the man page was referring to the output of the last command itself or how the data is actually stored in /var/adm/wtmpx. If there is another way to get this "last login" attribute, I'd be happy to learn it. A: In which I half-provide context, half rant You're running into an example of the main reason I don't like managing Solaris systems: Nothing is ever just easy. I don't know if the locale's really going to do anything except change the order of certain portions of the timestamp around. I'm interested if anyone knows of a way to coax Solaris's last into giving the year, but I'm not going to hold my breath. Sun's software development mantra seems to have been "It Technically Works." Sun seems to have pretty much developed something right up to the point absolutely required of them, and then pretty much stopped there. So you end up with generally accepted solutions being like these and you just keep a listed collection of workarounds for common problems. The only way I've ever found of doing this is to use /usr/lib/acct/fwtmp to dump the entire contents of /var/adm/wtmpx to a pipe to some other program that I use for manipulating the text output (grep, tac, sed, etc). Bonus: Since seeking the end of the file and just moving back by the fixed wtmpx record length would be asking too much, fwtmp can only print out the contents of wtmpx as they appear in the file. So you have to use some other means (probably tac) of reversing the lines, unless you're actually interested in the oldest information (which is the least likely use case, but I digress). Depending how long your system has been in operation wtmpx might be kind of large, so you may want to go get a cup of coffee, maybe go check to see if your tires are underinflated, and maybe go read a book or two while you're at it. The Actual Answer to your question: This is a command that emulates last in way that is usable to most people interested in looking at login records: # cat /var/adm/wtmpx | /usr/lib/acct/fwtmp | tac | head You'll notice I have to pipe wtmpx in since they don't give you a means of just giving the file to fwtmp. That's because feeding it in via stdin Technically Works™ in the majority of use cases and they wouldn't have had to write a few extra lines of code. So they'd rather just make Admins do that. This is example output of the above on on of the systems I look after: [root@atum root]# cat /var/adm/wtmpx | /usr/lib/acct/fwtmp | tac | head jadavis6 ts/1 pts/1 19410 7 0000 0000 1382723864 157168 0 19 ditirlns01.xxx.edu Fri Oct 25 13:57:44 2013 jadavis6 sshd 19404 7 0000 0000 1382723864 133973 0 19 ditirlns01.xxx.edu Fri Oct 25 13:57:44 2013 oracle sshd 6640 8 0000 0000 1382713401 157107 0 0 Fri Oct 25 11:03:21 2013 oracle ts/1 pts/1 6647 8 0000 0000 1382713401 150489 0 0 Fri Oct 25 11:03:21 2013 oracle ts/1 pts/1 6647 7 0000 0000 1382712445 24488 0 23 a0003040148735.xxx.edu Fri Oct 25 10:47:25 2013 oracle sshd 6640 7 0000 0000 1382712442 304729 0 23 a0003040148735.xxx.edu Fri Oct 25 10:47:22 2013 jadavis6 sshd 23537 8 0000 0000 1382560970 410725 0 0 Wed Oct 23 16:42:50 2013 jadavis6 ts/1 pts/1 23544 8 0000 0000 1382560970 404795 0 0 Wed Oct 23 16:42:50 2013 jadavis6 ts/1 pts/1 23544 7 0000 0000 1382552999 619524 0 19 ditirlns01.xxx.edu Wed Oct 23 14:29:59 2013 jadavis6 sshd 23537 7 0000 0000 1382552999 602215 0 19 ditirlns01.xxx.edu Wed Oct 23 14:29:59 2013 [root@atum root]# EDIT: I know I'm whining about something small up there, but after a while I just get tired of every little thing (such as simply asking "what's the year?") turning into an hour long googlefest or something that's more or less just tribal knowledge (such as the existence of fwtmp). A: GNU/Linux's last offers the -F switch. I'd be surprised if Solaris does, though. Internally, the wtmp file should have epoch timestamps and thus if you would care to write something in C or Perl you can create your own last command. You will need to look at the appropriate C-header file for the structure. The wtmp is a "binary" file and isn't amenable to evaluation with standard parsing tools. Consider periodically archiving and truncating your wtmp file so that you know what year to which it applies.
{ "pile_set_name": "StackExchange" }
Q: Truncate with where clause Can I use truncate command with a where clause? I need to remove specific rows from several tables. How can I delete specific data from the entire database? SELECT DimEmployee.[FirstName], DimEmployee.[LastName], [SalesOrderNumber], [ShipDateKey] FROM DimEmployee JOIN [FactResellerSales] ON DimEmployee.[EmployeeKey] = [FactResellerSales].[ProductKey] WHERE DimEmployee.[FirstName] like 'kevin%' <--have to truncate this specific name from entire DB Is there any other method to remove a specific data from entire DB? In my database there are 172 tables. I wanted to delete a specific name and its corresponding columns from the entire database. The name is spread across entire database, hence I want to remove it in a single shot instead of going to each table and deleting it individually. A: No, Truncate can't be used with a WHERE clause. Truncate simply deallocates all the pages belonging to a table (or a partition) and its indexes. From BOL: -- Syntax for SQL Server and Azure SQL Database TRUNCATE TABLE [ { database_name .[ schema_name ] . | schema_name . } ] table_name [ WITH ( PARTITIONS ( { <partition_number_expression> | <range> } [ , ...n ] ) ) ] [ ; ] If you're looking for a more efficient way to delete data, I'd start here. A: There are three delete methods in sql server: Truncate , Delete , Drop DROP, TRUNCATE are DDL commands (DROP is used to remove objects like tables, columns, constraints,...but not rows) DELETE is a DML commands. "TRUNCATE Removes all rows from a table without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources..." Read more You have to create command using a dynamic sql and execute it: (something like this query) DECLARE @strquery as NVARCHAR(MAX) SET @strquery = '' SELECT 'Delete T2 from [' + Table_name + '] As T2 Inner join DimEmployee as T1 On T1.[EmployeeKey] = T2.[ProductKey] Where T1.[FirstName] like ''kevin%'';' From information_schema.tables WHERE table_name <> 'DimEmployee' EXEC(@strquery) Helpful links Drop vs Truncate vs Delete (oracle) infos are similar to sql server Truncate vs Delete (sql server) Delete using inner join with sql server
{ "pile_set_name": "StackExchange" }
Q: How to synchronize the horizontal scroll bar of jQuery.SerialScroll with the slider contents? I am using jquery SerialScroll on my web page to slide around 20 images and it's working perfectly fine.Now i want to do this: As their are 20 images to slide so a scroll bar comes under the sliding images(or i can say at the end point of the sliding div) and this scroller automatically updates as images slides,so now i want that if a user click on that scroll bar and slide the slider manually and leave the scroller on 10th images then it should start it next scroll from the 10th images and then continue to scroll. So please tell me or suggest me how can i do this? I think it can be done by detecting a if a user clicked on scroll bar and scroll manually then i need to detect how many images passed then start the scroll again by triggering an event. But please give me some idea in terms of code ? -Thanks A: Let's write our own tiny serial-scroll! And ... a nice Image slider: Stop on mouseEnter Restart on mouseLeave During manual slide it controls the image mostly visible (more than 50% on screen!) Start slider again from the mostly visible image Gallery DEMO
{ "pile_set_name": "StackExchange" }
Q: What is the name of the idea that humans are granted rights? Some say that human beings are granted rights, and this becomes the basis for a claims in parts of the Western legal system. Other parts of the Western legal system consider these privileges that are specific grants from an authority - but have an equivalent legal remedy. My question is: What is the name of the idea that humans are granted rights? (and that these are not considered privileges) A: Natural law - a system of right or justice held to be common to all humans and derived from nature rather than from the rules of society, or positive law. At certain point it was considered the most right law because if we got this by nature than this is in God too. Others think that we lived freely by natural laws before we became chained by society laws and positive law. Here you can read more on the topic: link 1 link 2 link 3 link 4 link 5 Also there are alot of resources on the internet just google : natural law/natural rights
{ "pile_set_name": "StackExchange" }
Q: Vue JS - Display data if two strings from two different json arrays match In my Vue JS app I would like to display a div only if two strings match form two different json arrays. I'm using Axios to get the two different json endpoints combining them into two arrays and displaying the data in a view. The strings that should match are the following [ { "info": [ { "uuid": "888" } ] } ] [ { "postId": "888" } ] I'm posting the uuid in a view using a loop <div v-for="posts in $route.params.post.postdata" :key="post.uuid"> <p>{{ post.uuid }}</p> </div> and the post id by <div v-for="special in specials" :key="special.postId"> <p>{{ special.postId }}</p> My details view export default { data () { return { loading: false } }, computed: { specials () { return this.$store.state.specials } }, created () { this.loading = true this.$store.dispatch('fetchPosts') .then(specials => { this.loading = false }) } } Would I need a method and a v-if? A: There are some naming mismatches in your example and we don't know what the route params correlate with. info is not explicitly used anywhere, and it's unclear what layout you are trying for. But here's my guess, assuming that the outer loop represents info <div v-for="post in $route.params.post.postdata" :key="post.uuid"> {{ post.uuid }} <template v-for="special in specials"> <p v-if="post.uuid == special.postId">{{ special }}</p> </template> </div>
{ "pile_set_name": "StackExchange" }
Q: scala function not called from lambda function I am new to scala and just understanding how can I transform via Map call. The foo function is not getting called. What is that I am missing ? import org.apache.spark.rdd.RDD import org.apache.spark.SparkConf import org.apache.spark.SparkContext object Expt { def main(args: Array[String]): Unit = { var conf = new SparkConf().setAppName("Test").setMaster("local[*]") val sc = new SparkContext(conf) val a1 = sc.parallelize(List((1,"one"),(2,"two"),(3,"three")) val a3 = a1.map(x => Expt.foo(x)) } def foo(x: (Int,String)) : (Int,String) = { println(x) x } } A: You don't execute any action so map is never evaluated. Also println in map usually won't have visible effect.
{ "pile_set_name": "StackExchange" }
Q: Convert a React.element to a JSX string I am trying to build a component which, Takes children and Renders the children in the DOM and also, Shows the children DOM in a pre for documentation sake One solution is to pass the JSX as a separate prop as well. This makes it repetitive since I am already able to access it through this.props.children. Ideally, I just need to somehow convert the children prop as a string so that I can render it in a pre to show that "this code produces this result". This is what I have so far class DocumentationSection extends React.Component{ render(){ return <div className="section"> <h1 className="section__title">{heading || ""}</h1> <div className="section__body"> {this.props.children}</div> <pre className="section__src"> //Change this to produce a JSX string from the elements {this.props.children} </pre> </div>; } } How can I get the a jsx string in the format '<Div className='myDiv'>...</Div> when I render DocumentationSection as <DocumentationSection heading='Heading 1'> <Div className='myDiv'>...</Div> </DocumentationSection> Thanks. Edit: I tried toString, it dint work, gave [object Object] A: If you want the HTML representation of a React element you can use #renderToString or #renderToStaticMarkup. React.renderToString(<div>p</div>); React.renderToStaticMarkup(<div>p</div>); will produce <div data-reactid=".1" data-react-checksum="-1666119235">p</div> and <div>p</div> respectively. You will however not be able to render the parent as a string from within itself. If you need the parent too then from where you render the parent pass a renderToString version of it as props to itself. A: You can use react-element-to-jsx-string: import React from 'react'; import reactElementToJSXString from 'react-element-to-jsx-string'; console.log(reactElementToJSXString(<div a="1" b="2">Hello, world!</div>)); // <div // a="1" // b="2" // > // Hello, world! // </div> A: React.renderToString is depreciated as of React v0.14.0, it's recommended to use ReactDOMServer.renderToString instead. e.g import ReactDOMServer from 'react-dom/server' ... ReactDOMServer.renderToString(YourJSXElement())
{ "pile_set_name": "StackExchange" }
Q: I like knowing / to know things in advance There is a very small difference in meaning between the two forms. The -ing form emphasises the action or experience. The to-infinitive gives more emphasis to the results of the action or event. We often use the -ing form to suggest enjoyment (or lack of it), and the to-infinitive form to express habits or preferences. Cambridge Dictionary I couldn't understand what they mean by "emphasises the action" and "emphasis to the results". as example, which of the following sentence is correct? I don't like surprises. I like knowing things in advance. I don't like surprises. I like to know things in advance. A: As the link you quoted says, it is a very small difference. It's not really a difference in meaning, but in implication. Try this example: I like eating ice cream. Emphasises the action or experience This implies that the act of eating is most enjoyable. The action of eating it is the best part of the experience. I like to eat ice cream. More emphasis to the results This indicates that the ice cream itself is the best part. As in, the result of having ice cream in you is what you enjoy! Don't worry about the difference too much when you are speaking. In casual conversation, they are pretty much interchangeable.
{ "pile_set_name": "StackExchange" }
Q: mongodb - Replica set creation error: Quorum check failed because not enough voting nodes responded I am configuring a mongodb replica set. From my current primary node, when rs.add('host1:27017'), it yields this error Quorum check failed because not enough voting nodes responded; required 2 but only the following 1 voting nodes responded; the following nodes did not respond affirmatively; failed with Server min and max wire version are incompatible (7,7) with client min wire version (6,6) On my host1 and host2 machines, I already added replication option with the same replSetName, bind_ip, and exposed firewall. As a proof, through command line mongo --host host1 I can still connect to host1's mongo instance. The telnet command also yields the same successful connection. I don't know how to fix this. A: The answer is that all 3 machines must have the same version 4.0
{ "pile_set_name": "StackExchange" }
Q: AWS SES Timeout I am using Rails 4.2, the AWS-SES gem and the Mailform gem. I am trying to set up AWS SES in development and have added this to config/development.rb: # Configure mail using AWS SES config.after_initialize do ActionMailer::Base.delivery_method = :amazon_ses ActionMailer::Base.custom_amazon_ses_mailer = AWS::SES::Base.new( :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], :access_key_id => ENV['AWS_SECRET_KEY_ID'], :server => 'email.eu-west-2.amazonaws.com' ) end When I attempt to send emails from the console, I am getting a timeout after 30 seconds. I started to write all this up asking for help, but then it occurred to me that MailForm may not be derived from ActionMailer. Sure enough, MailForm::Base has superclass Object, so configuring ActionMailer is pointless. I changed these two lines to configure MailForm::Base, but I still get a timeout. Is it possible that these two gems are not compatible? Otherwise, any suggestions to either resolve or troubleshoot would be appreciated. A: As I mentioned in my question, the MailForm and AWS-SES gems are not compatible out of the box. It is possible that they can be made to work together but I took a different route. Some keys to setting up AWS-SES (code included below for reference): AWS set up - with AWS you start off in sandbox mode. You need to register all of your destination email addresses in the SES console for anything to work. Click on the Email Addresses link to list your verified addresses and add more. Also, you will need to set up AWS IAM credentials to use with the gem. When you do this, make sure the user has the SES Full Access managed policy attached (on the IAM console). :server setting - AWS operates in multiple regions but your SES account will be set up in one of them. To determine your region, go to the AWS console and click on SES. You will see your region in the URL - for me it is region=us-west-2. I recommend setting up an initializer as described in Dan Croak's excellent article. I did it just as Dan recommended, except that I set the delivery method to :amazon-ses and added a server configuration line. Configuration - Dan's article (mentioned above) explains how to set delivery_method in your environment configuration file. Again, I used :amazon-ses. Once you have AWS configured and your gem installed, you can test your setup in the rails console. Much easier to troubleshoot there than in your code base. Somewhat unrelated, but I used the Dotenv gem to manage my environment settings. In a nutshell, once you install the gem, you can stick all of your environment settings in ~/.env and have access to them in ENV throughout your code. /config/initializers/amazon-ses.rb ActionMailer::Base.add_delivery_method :amazon_ses, AWS::SES::Base, :access_key_id => ENV['AWS_SECRET_KEY_ID'], :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], :server => 'email.us-west-2.amazonaws.com' /config/environments/development.rb (excerpts): # Configure mailer for development test config.action_mailer.raise_delivery_errors = true # Configure mail using AWS SES config.action_mailer.delivery_method = :amazon_ses # Configure URL options host = 'www.example.com' config.action_mailer.default_url_options = { host: host } Of course, to make this work in production, you'll need to make these changes to /config/environments/production.rb. You'll also need to make your AWS secret settings on your production server. If you are using Heroku: $ heroku config:add AWS_SECRET_KEY_ID=12345XYZ $ heroku config:add AWS_SECRET_ACCESS_KEY=67890ABC
{ "pile_set_name": "StackExchange" }
Q: Use Shift+F12 in an application I am using an application which has a shortcut that uses Shift + F12. But when I do that on my mac, it goes to the dashboard. Which is very irritating. How can I quickly bypass that feature and send the shortcut to the app? A: Go to System Preferences → Mission Control and change the Show Dashboard shortcut to something else.
{ "pile_set_name": "StackExchange" }
Q: Firebase: Uncaught Error: Query.equalTo: startAt() or equalTo() previously called I found nothing when I tried to search this error on Google: "Uncaught Error: Query.equalTo: startAt() or equalTo() previously called!". (one result that says nothing) I'm trying to select X children with name of Toni that are found before lastId. for example: Ref: -236feg262477 name: "Toni" -9759jj900000 name: "RVR" -969999999999 name: "Toni" -777777777777 name: "TTT" -553333333333 name: "Toni" Ref.orderByChild("name") .equalTo("Toni") .startAt(null, "-969999999999") .limitToFirst(1) .on('child_added', function (snapshot) { // do something... }); But I get the error in the title of this topic. Any help appreciated! A: This happens when you call either startAt(...) endAt(...) or equalTo(...) in the same query. You can't do multiple, just one. Below are two options to fix your example Ref.orderByChild("name") .equalTo("Toni") .limitToFirst(1) .on('child_added', function (snapshot) {...})` or Ref.orderByChild("name") .startAt(null, "-969999999999") .limitToFirst(1) .on('child_added', function (snapshot) {...})`
{ "pile_set_name": "StackExchange" }
Q: What kind of times does `times` output? From the Bash reference manual, times (emphasis mine): Print out the user and system times used by the shell and its children. From help times: Prints the accumulated user and system times for the shell and all of its child processes. What is "times used by the shell and its children"? For example, in a bash shell that has been running for several months: $ times 0m0.152s 0m0.080s 0m15.804s 0m13.296s How is it possilble that all kinds of times used by the shell and its children is less than 1 min? A: From help times: Prints the accumulated user and system times for the shell and all of its child processes. You were emphasising for the shell and all of its child processes when you should have been paying more attention to user and system times. User Time and System Time is not Real (or clock) time, they are the CPU times used in user code and system function calls respectively. BTW, the time built-in (and the external utility of the same name) can display all three times - Real Time, User Time, and System Time. From help time: Execute PIPELINE and print a summary of the real time, user CPU time and system CPU time spent executing PIPELINE when it terminates. Also BTW. the bash built-in time output format is configurable. I like to to use the following so that it only uses one line of my terminal rather than wasting 3 lines: export TIMEFORMAT=$'\nreal %3lR\tuser %3lU\tsys %3lS' The GNU version of the external time utility (/usr/bin/time) allows you to configure the output format with the -f or --format option. Other versions may or may not have similar options...don't know, don't care enough to look it up.
{ "pile_set_name": "StackExchange" }
Q: Looking for a horror manga I read some years ago I read it probably one or two years ago, but I'm pretty sure it was older than that. Its art style was extremely detailed, maybe even too much so. It was quite violent as well (e.g. at some point a character throws a sink or something like that through the body of another one). The story was about a group of students (maybe high school, not too sure about that) who "build" a Frankenstein-ish monster which should serve them in doing... something? I can't really remember. The monster at the end rebels against the group and slaughters them all. They kidnap and maybe rape one of their teachers. The leader of the group had some kind of "black star", and at some point he meets a fortune teller who tells him that the black star is a mark of great evil and that people like Hitler had one, but also that the boy would be even more successful than them. I am pretty sure it had an anime adaptation, but it was less gory and wasn't well accepted. EDIT: I'm absolutely not sure about this, but the title may have been the name of the creature. A: This is Lychee Light Club. On the cover you can see the black star, the symbol you mentioned , on the leader's glove. He was indeed told by a fortune teller that he would be more evil than Hitler - and he takes pride in it. The Frankenstein monster you're thinking of is Litchi. He's powered by lychee fruits. He was created so that he could capture beautiful girls for the club. He discovers love from one of his captive females and betrays the club whilst defending her. The anime is significantly less dark than the manga and the characters are in a chibi art style
{ "pile_set_name": "StackExchange" }
Q: How can I force the opening of my jQuery Dialog even if I've a link? I'm currently working on a jQuery Dialog and I've a problem. Here's my JavaScript code: $(function() { $('.overlay-trigger').click(function() { $('#expose-mask').fadeIn(function() { $('.overlay-box').css({'display':'block'}); }); }); $('.overlay-box-closer, #expose-mask').click(function() { $('.overlay-box, #expose-mask').css({'display':'none'}); }); }); my HTML code: <div id="footer"> <div class="wrapper"> <ul> <li> <a id="help" class="overlay-trigger" href="help.php">Help</a> </li> </ul> <span id="footer-copyright"> <a href="./..">Coded by Dylan.</a> </span> </div> </div> <div class="overlay-box"> <div class="overlay-box-container"> <span class="overlay-box-closer" title="Close the overlay"></span> <h1 class="big-title">Help</h1> <p>Your privacy is important to us. To better protect your privacy we provide this notice explaining our online information practices and the choices you can make about the way your information is collected and used. To make this notice easy to find, we make it available in our footer and at every point where personally identifiable information may be requested.Log files are maintained and analysed of all requests for files on this website's web servers. Log files do not capture personal information but do capture the user's IP address, which is automatically recognised by our web servers.</p> </div> </div> <div id="expose-mask" style="display: none;"></div> and my CSS code: .overlay-box { background-color: #FFFFFF; display: none; position: fixed; top: 40%; right: 0; left: 0; z-index: 3; width: 50%; margin: 0 auto; box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 7px; -webkit-box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 7px; -moz-box-shadow: rgba(0, 0, 0, 0.3) 0px 1px 7px; } .overlay-box-container { margin: 20px; } #expose-mask { background-color: rgba(0, 0, 0, 0.6); position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 2; } As you can see, in my link <a id="help" class="overlay-trigger" href="help.php">Help</a> I've my href and my class overlay-triggerthat performs the opening of the overlay. If I put # in my href, the overlay opens well: http://prntscr.com/686n07 I'd like to put a link to my "Help" text, but when I click the link, the overlay does not open and I'm directly redirected to the link. I'd like that even if there's a link, the overlay is opened anyway. Like this example: http://community.invisionpower.com/register/ (click the "Privacy Policy" text). Thanks. A: Prevent the default behavior using event.preventDefault(): $('.overlay-trigger').click(function(event){ event.preventDefault(); $('#expose-mask').fadeIn(function(){ $('.overlay-box').css({'display':'block'}); }); });
{ "pile_set_name": "StackExchange" }
Q: BrowserStack with Nightwatch take screenshot and get that screenshot URL for custom reporting I am using BrowserStack along with Nightwatch as testing framework. In Nightwatch test I took screenshot using "saveScreenshot" Selenium command. Screenshot is saved by BrowserStack on CDN. I want that screenshot URL for my custom reporting. I got one solution, which is get current(test) sessions logs and parse that logs to get screenshot(s) URL(s). Which is tedious task. In single test for multiple "saveScreenshot" command calls its also difficult to map which URL corresponds to which page(May be "hcode" value in response will solve it but not sure). Can you please suggest how to achieve my goal ? A: Yes, if you wish to fetch the screenshot URLs, the only way you can do it would be by parsing the session logs that are fetched using the REST API. You'll also need the session ID of the test to fetch the session logs, for which you can refer this question. Additional points that can help you: You can check the Python script here, for more details on parsing the logs to get the screenshot URLs The browser.saveScreenshot('<path>/Screenshot.png'); in Nightwatch, also saves the screenshot to your local machine which you can use for reporting. You can name the screenshots accordingly so that it will help you understand at what point of the test was the screenshot captured.
{ "pile_set_name": "StackExchange" }
Q: php multiple images updating I am creating PHP multiple images updating page my script is updating only one image second image updating if i selected all image file only updating first and second image I want to create one by one images updating I have tried to do that's but it's not working Here is my code if($_SERVER['REQUEST_METHOD'] == "POST"){ //$id=$_POST['id']; $title=$_POST['title']; $desc1=$_POST['desc1']; $content=$_POST['content']; $category=$_POST['category']; $random = substr(number_format(time() * rand(),0,'',''),0,10); $img= $random .$_FILES['image']['name'][0]; $image_tmp= $_FILES['image']['tmp_name'][0]; $img1= $random .$_FILES['image']['name'][1]; $image_tmp1= $_FILES['image']['tmp_name'][1]; if(move_uploaded_file($image_tmp,"images/$img")){ move_uploaded_file($image_tmp1,"images/$img1"); $stmt = $con->prepare("UPDATE products SET title=?, desc1=?, content=?, category=?,img=?,img1=? WHERE id=?"); $stmt->bind_param("sssssss", $title, $desc1, $content, $category, $img,$img1, $id); }else{ $stmt = $con->prepare("UPDATE products SET title=?, desc1=?, content=?, category=? WHERE id=?"); $stmt->bind_param("sssss", $title, $desc1, $content, $category, $id); } if($stmt->execute()){ header('location:edit-source.php'); }else{ echo "Failed to update product<br/>"; } } ?> A: I think you have an incorrect logic in place. The logic should be if($_SERVER['REQUEST_METHOD'] == "POST"){ $id=$_POST['id']; $title=$_POST['title']; $desc1=$_POST['desc1']; $content=$_POST['content']; $category=$_POST['category']; $random = substr(number_format(time() * rand(),0,'',''),0,10); $img= $random .$_FILES['image']['name'][0]; $image_tmp= $_FILES['image']['tmp_name'][0]; $img1= $random .$_FILES['image']['name'][1]; $image_tmp1= $_FILES['image']['tmp_name'][1]; if(move_uploaded_file($image_tmp,"images/$img")){ move_uploaded_file($image_tmp1,"images/$img1"); $stmt = $con->prepare("UPDATE products SET title=?, desc1=?, content=?, category=?,img=?,img1=? WHERE id=?"); $stmt->bind_param("sssssss", $title, $desc1, $content, $category, $img,$img1, $id); } else if (move_uploaded_file($image_tmp1,"images/$img1")) { move_uploaded_file($image_tmp1,"images/$img"); $stmt = $con->prepare("UPDATE products SET title=?, desc1=?, content=?, category=? WHERE id=?"); $stmt->bind_param("sssss", $title, $desc1, $content, $category, $id); } if($stmt->execute()){ header('location:edit-source.php'); }else{ echo "Failed to update product<br/>"; } } ?> Alternatively, I would recommend wrapping it in a function to make it reusable.
{ "pile_set_name": "StackExchange" }
Q: Micro-Controller Operating System with GUI I'm looking for embedded OS for w micro-controller, it's not clear until now for me what'll be the controller type, but my first priority is to found an OS with GUI can be written in C# or any .NET family or JAVA. I found some good operating system like: emWIN, easyGUI, PEG but all of them could be customized in C++, Any help please about same OSs but not in C++. and due to I'm new in embedded systems developing and until now not clear with the main structure, is it possible to let developers create applications and install it on my embedded system or the main structure only allow to customize the software and burn it to micro-controller, or in other words.. in advanced mood. Can I create SDKs for my embedded system or the only way to create a software on an embedded system is to customize my OS with my applications and burn it.. Thanks and sorry if am not clear with that field but am trying to collect a lot about it. A: Basically, this question is not capable of being answered. You don't need to consider what OS you're going to use at first. First, you need to consider what kind of micro-controller you're going to be using. Various ARM CPUs will be perfectly capable of running a "OS" in .Net However, AVR and PIC and such will not be able to use even the most micro of .Net frameworks. Second, you need to consider why you're needing to use .Net. The .Net micro framework will have a lot more overhead than a direct native program. If using .Net is only a priority because you don't want to learn C++, you probably just need to man up and learn C or C++. And what kind of OS are you looking for? An RTOS, or a more general purpose OS, such as Linux? You're going to have a hard time finding an OS of much complexity implemented in C#, because of the reason I said above. A: If you like C# you can use Netduino It has a Free IDE supported by Microsoft you can download here. Netduino is an open source electronics platform using the .NET Micro Framework. Featuring a 32-bit microcontroller and a rich development environment. Suitable for engineers and hobbyists alike Atmel 32-bit microcontroller Speed: 48MHz, ARM7 Code Storage: 128 KB RAM: 60 KB It is cheap but some accessories can be expensive (But you can make your own cheaper) A: How about a $35 computer? The Raspberry Pi is the latest viral trend for cheap but extremely powerful "Micro Controller" The supported OS is a special version of Debian for ARM6 but it can run almost anything the normal Debian does and also has Input/Output pins. Most of software is also Free The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming. CPU, 700 MHz ARM (ARM11) GPU, VideoCore IV, OpenGL ES 2.0, 1080p30 h.264/MPEG-4 AVC RAM 256mb (depends on model too) Storage, Unlimited (Whatever you connect to it) (Priamry SD-Card, USB and Network) Ask the dedicated Raspberry Pi Stack Exchange Community for more questions...
{ "pile_set_name": "StackExchange" }
Q: Excel VBA - Number format seems unchangeable I have an excel table which is straight from a database. Its first column contain dates but are not formatted as dates. They are written as : 03/01/2014 for example. So I'm trying to comparing values from some cells and the problem is people type dates as : 3/01/2014. When comparing the values no value is returned. I'm using the range.find() command. So I tried to change the format of the date column in the table but it didn't change at all. However if I try to edit a cell and just press enter it becomes a normal date. I wonder if there is a way I can convert all those rigid dates in the table to normal excel dates so that the comparison routine can work. Thanks you. A: Select the cells whose dates you wish to convert and run this small macro: Sub DateSetter() Dim r As Range, d As Date, st As String For Each r In Selection st = r.Text If InStr(st, "/") <> 0 Then ary = Split(st, "/") d = DateSerial(CInt(ary(2)), CInt(ary(1)), CInt(ary(0))) r.Clear r.Value = d r.NumberFormat = "m/d/yyyy" End If Next r End Sub It should perform the conversion, but ignore zeros, blanks, and other junk.
{ "pile_set_name": "StackExchange" }
Q: Displaying a byte content given by an address I have to display the content of n bytes starting in a specific memory address, i.e: an output for 25 bytes since 0x00004000 (segment text in virtual space) would be #include <stdio.h> #inclu (25 letters) My idea was to assign to a char *c the address given, like: *c=address; and then printf("%s",c);. For me, conceptually makes sense and I know that in some cases it would cause a segmentation fault if the address is not valid. However I have implemented it and it always causes a segmentation fault. I use pmap <pid> to know what areas can be displayed (low areas) of that process. When I say "areas that can be displayed" I mean text areas (code). So, what I am doing wrong? is stupid the assignment *c=address; ? A: char *c = address; for (int i = 0; i < n; i++) { putchar(c[i]); } Errors in your code having something like char *c; *c = address; Is invalid, because c is a dangling pointer (you have never initialized it). You want to set the address which c points to to address: c = address printf("%s",c); You don't know if c is a proper string, it may contain garbage or may not be n bytes length. That's why I used putchar
{ "pile_set_name": "StackExchange" }
Q: How to eliminate empty csv records from Java arraylist? I have requirement where I need to fetch few values and then write all those to csv file. To achieve this, I am adding the values to Java Arraylist and writing to a csv file. But when I do this Its writing the records to CSV but with empty rows in between records. Not sure why this problem is coming. 1,abc,fname,lname,email,log 1,abc1,fname1,lname1,email1,log1 1,abc2,fname2,lname2,email2,log2 1,abc3,fname3,lname3,email3,log3 1,abc4,fname4,lname4,email4,log4 here is my code. Please let me know what's wrong with this code: public StringBuilder fetchUsers() { ArrayList<String> users = null; StringBuilder sb1 = new StringBuilder(); try { client = getMyClient(); if (client != null) { UserList usersList = getUsers(); if (usersList.totalCount != 0 && usersList.totalCount >= 1) { System.out.println("usersList.totalCount ----->" + usersList.totalCount); for (KalturaUser user : usersList.objects) { users = new ArrayList<String>(); if (user != null) { String action = null; String userFullName = null; String modifiedName = null; String firstName = user.firstName; if (user.id != null) { String cnum = getUserUniqueId(user.id); String userRole = getUserRole(user.id); if (cnum != null || userRole != null) { action = validateCnum(cnum, userRole); if (!action.equals("3")) { users.add(action); users.add(cnum); if (firstName != null && firstName.contains("@")) { user.email = firstName; userFullName = getUserNames(user.id); firstName = userFullName; } users.add(firstName); users.add(user.lastName); users.add(user.email); users.add(userRole); } } } } allUsers.add(users); } } } } catch (MyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } writeToCSV(); return sb1; } private void writeToCSV() { FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System .getProperty("line.separator")); try { fileWriter = new FileWriter("C:/users.csv"); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(USER_COLUMNS); for (List<String> rowData : allUsers) { csvFilePrinter.printRecord(rowData); } } catch (Exception e) { logger.error(e.getStackTrace()); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException e) { logger.error("Error while flushing/closing fileWriter/csvPrinter!"); } } } A: This: allUsers.add(users); should be inside the if (user != null) and all the sub-ifs Something like this: if (user != null) { ... if (user.id != null) { ... if (cnum != null || userRole != null) { .... if (!action.equals("3")) { users = new ArrayList<String>(); .... allUsers.add(users); } } } } In general, you should create the array and add it to the allUsers only if you have something to add
{ "pile_set_name": "StackExchange" }
Q: Find all possible to ways to reach a point $N$ meters away using steps that are of lengths 1 meter or 2 meters. Find all possible to ways to reach a point $N$ meters away in only 2 possible steps that are of 1 meter and 2 meter respectively. Now let me illustrate using an example: Let the point be 4 meters away. So all possible ways to reach the point: (1,1,1,1) (2,2) (1,2,1) (2,1,1) (1,1,2) My approach: I sought to the computational power of my laptop, I brute forced to reach the solution. Yet this isn't really a solution, I am looking for some more logically derived solution. Any help is appreciated. A: Let $a_n$ be the number of ways of reaching a point $n$ meters away by taking steps of $1~\text{m}$ or $2~\text{m}$. There is only one way to move $1~\text{m}$ (take a $1~\text{m}$ step), and two ways to move $2~\text{m}$ (take two $1~\text{m}$ steps or one $2~\text{m}$ step). Hence, we have the initial conditions \begin{align*} a_1 & = 1\\ a_2 & = 2 \end{align*} An admissible sequence of steps that results in moving $n$ meters must begin with a $1~\text{m}$ step or a $2~\text{m}$ step. If it begins with a $1~\text{m}$ step, then it must be followed by an admissible sequence of steps that results in moving $(n - 1)~\text{m}$, of which there are $a_{n - 1}$. If it begins with a $2~\text{m}$ step, then it must be followed by an admissible sequence of steps that results in moving $(n - 2)~\text{m}$, of which there are $a_{n - 2}$. Hence, we have the recurrence relation $$a_n = a_{n - 1} + a_{n - 2}$$ The first few terms of the sequence are $1, 1, 2, 3, 5, 8, 13, 21, 34, 55$, so this is the Fibonacci sequence.
{ "pile_set_name": "StackExchange" }
Q: How do I fix my systemctl status tomcat? How can I get systemctl status tomcat to return 'success' instead of 'failed'? This is my etc/systemd/system/tomcat.service file: [Unit] Description=Apache Tomcat Web Application Container After=syslog.target network.target [Service] Type=forking Environment=JRE_HOME=JAVA_HOME='/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.161-0.b14.el7_4.x86_64/' Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid Environment=CATALINA_HOME=/opt/tomcat Environment=CATALINA_BASE=/opt/tomcat #Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC' Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom' ExecStart=/opt/tomcat/bin/startup.sh ExecStop=/bin/kill -15 $MAINPID User=tomcat Group=tomcat [Install] WantedBy=multi-user.target now when i check the status of my tomcat it says # systemctl status tomcat ● tomcat.service - Apache Tomcat Web Application Container Loaded: loaded (/etc/systemd/system/tomcat.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Sat 2019-08-10 14:03:10 EDT; 55min ago Main PID: 22165 (code=exited, status=127) Aug 10 14:03:10 localhost.localdomain kill[22167]: -q, --queue <sig> use sigqueue(2) rather than kill(2) Aug 10 14:03:10 localhost.localdomain kill[22167]: -p, --pid print pids without signaling them Aug 10 14:03:10 localhost.localdomain kill[22167]: -l, --list [=<signal>] list signal names, or convert one to a name Aug 10 14:03:10 localhost.localdomain kill[22167]: -L, --table list signal names and numbers Aug 10 14:03:10 localhost.localdomain kill[22167]: -h, --help display this help and exit Aug 10 14:03:10 localhost.localdomain kill[22167]: -V, --version output version information and exit Aug 10 14:03:10 localhost.localdomain kill[22167]: For more details see kill(1). Aug 10 14:03:10 localhost.localdomain systemd[1]: tomcat.service: control process exited, code=exited status=1 Aug 10 14:03:10 localhost.localdomain systemd[1]: Unit tomcat.service entered failed state. Aug 10 14:03:10 localhost.localdomain systemd[1]: tomcat.service failed. Caused by: java.net.ConnectException: Connection refused (Connection refused) I got this error trying to run sudo certbot --apache Error while running apachectl graceful. Job for httpd.service invalid. Unable to restart apache using ['apachectl', 'graceful'] Error while running apachectl restart. Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details. Encountered exception during recovery: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/certbot/error_handler.py", line 124, in _call_registered self.funcs[-1]() File "/usr/lib/python2.7/site-packages/certbot/auth_handler.py", line 220, in _cleanup_challenges self.auth.cleanup(achalls) File "/usr/lib/python2.7/site-packages/certbot_apache/configurator.py", line 2332, in cleanup self.restart() File "/usr/lib/python2.7/site-packages/certbot_apache/configurator.py", line 2202, in restart self._reload() File "/usr/lib/python2.7/site-packages/certbot_apache/configurator.py", line 2229, in _reload raise errors.MisconfigurationError(error) MisconfigurationError: Error while running apachectl restart. Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details. This is my journalctl -xe: https://pastebin.com/JvJ8Uej0 This is my journalctl -b -u tomcat: https://pastebin.com/zPqEBGXH Tried killing proccess but dont work none: # kill 23656 bash: kill: (23656) - No such process What may be the cause this? How do I fix these error? The website is working fine but I'm getting these errors. A: My issue was with the line in the unit file: Environment=JRE_HOME=JAVA_HOME='/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.161-0.b14.el7_4.x86_64/' it should be without quotes: Environment=JRE_HOME=JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.161-0.b14.el7_4.x86_64/ I was able to find this by trying systemctl restat tomcat and then looking at log catalia.out showed an error in /opt/tomcat/bin/catalina.sh which /opt/tomcat/bin/startup.sh calls which looked like an error with JAVA_HOME. Thank you djdomi for helping me get there in the comments.
{ "pile_set_name": "StackExchange" }
Q: Are the "greatest hits" in the Stack Overflow newsletter appropriate? I have been surprised by the questions featured as the "greatest hits" in the Stack Overflow newsletter. 2012 January 3 Most useful free third-party Java libraries (deleted) 2011 November 29 What is the worst gotcha in C# or .NET? (deleted) November 15 Must haves for developers office (closed and deleted) Interview question: f(f(n)) == -n (closed) November 1 What are programming lost arts? (deleted) Biggest Delphi nitpicks? September 20 What are some bad programming habits to look out for and avoid? (closed and deleted) September 13 What is Boost missing? Stack overflow code golf (closed) August 30 Worst security hole you've ever seen? (closed) August 23 What made programming easier in the last couple of years? (deleted) August 16 What was "The Next Big Thing" when you were just starting out in programming? (deleted) What IDE to use for Python? (closed) Do we really want the newsletter to feature questions like these? I understand that they exist for historical reasons, but given that moderators would probably close any new questions like these without hesitation I don't think that we should be actively promoting them, either. Would it be possible for someone to give the newsletter a quick, manual check before it goes out, or is Stack Exchange not really set up for that? How difficult would it be to catch off-topic posts like these before the newsletter is actually sent? Interestingly enough, I don't notice an overwhelming number of these "inappropriate" questions on Stack Overflow's Greatest Hits page, which is probably used to populate the newsletter. Any idea why? A: I think those questions should just be put in protected status, and then have the algorithm that chooses "greatest hits" ignore protected posts (along with closed ones). A: This is exactly the problem with keeping these questions around. Broken windows encourage more damage (more questions of the same ilk) even when not publicized in the newsletter. Though the newsletter exacerbates the problem or brings it further to light, it's not a problem with the newsletter; having these questions around is the problem. I would like to see these questions killed with fire, historical or not. A: Given that the policies for on-topic questions may alter as new (and intriguing) sites are added, I would suggest that these 'Greatest Hits' selections have a filter to feature only high view questions which were asked less than say six months ago. I would also suggest avoiding questions which have been closed & re-opened more than once. As for the previously featured questions: Worst security hole you've seen? asked on Sept. 24th, 2009 (closed / reopened once) Hidden features of Perl? asked on Oct. 2nd, 2008 What was "The Next Big Thing" when you were just starting out in programming? asked on Sept. 17th, 2008 (closed(6) / reopened five times) What IDE to use for Python? asked on Sept. 17th, 2008 Hidden Features of Visual Studio 2005-2010? asked on Sept. 19th, 2008 What made programming easier in the last couple of years? asked on March 10th, 2009 I believe the current modus operandi of Stack Exchange Moderators is to not migrate a question which pre-dates the existence of a site where it would now be considered on-topic, except on a highly selective basis. Within the past year, we now have added sites where some of the above questions would be on-topic (the links below are to their Area 51 proposals with launch dates): Unix & Linux Programmers Theoretical Computer Science Web Applications IT Security and many more. In contrast, there have been about 200 questions, asked within the past six months and have more than 5,000 views many of which I think would make excellent candidates for the 'Greatest Hits' category. Here's one example with 47,277 views & 259 upvotes where Sir Skeet-a-lot has already earned 599 up-votes on a question which was asked on July 27th, 2011 at 8:15pm.
{ "pile_set_name": "StackExchange" }
Q: Fibonacci Sequence: Prove $f_1+f_3+\dots+f_{2n-1}=f_{2n}$ by Induction. I believe the majority of my proof is correct I'm just not certain about the base case if any one can explain how to do that base case or fix any error I made I would greatly appreciate it. Recall the fibonacci sequence is defined by $f_1=f_2=1$ and for $n\in \mathbb{N}$, $f_n+f_{n+1}=f_{n+2}$ Prove that for every natural number $n$ that:$$f_1+f_3+\dots+f_{2n-1}=f_{2n}$$ By Induction Let $a_n=f_1+f_3+\dots+f_{2n-1}$ Base case:Let $a_1=1$ Thus LHS$=1$ and RHS$=1$. Therefore the base case holds. Induction Hypothesis: Assume $f_1+f_3+\dots+f_{2n-1}=f_{2n}$ NTS:$f_1+f_3+\dots+f_{2n-1}+f_{2n+1}=f_{2n+2}$ Inductive Step: By Induction Hypothesis the above simplifies to $f_{2n}+f_{2n+1}=f_{2n+2}$. As was to be shown. A: Problems in Your Post You wrote, By Induction, Let $a_n=f_1+f_3+⋯+f_{2n−1}$ It is not clear from what you wrote what actually you are trying to prove. For example, you haven't defined what your $a_n$ is. You also haven't properly written what your actual statement is on which you are trying to apply induction. More precisely, to apply induction we need to have some statement $P(n)$ but in your case you haven't explicitly stated what your $P(n)$ is. Unless you state this, you can't apply the principle of mathematical induction. Next you wrote, Base case: Let $a_1=1$. Thus LHS=$1$ and RHS=$1$. Therefore the base case holds. There are at least two problems in this statement. Remember that in the Base Case you are to prove that when in your statement $n=1$ (or, in general a suitable initial value) then $P(1)$ is true. But here how are you proving that when $a_1=1$ LHS=RHS? Furthermore, how do you even know that $a_1=1$? What Your Proof Could Be Define, $$P(n):=f_1+f_3+\ldots+f_{2n-1}=f_{2n}$$ Base Case: When $n=1$, in LHS we only have $f_1=1$ and in RHS we have $f_2=1$. So in this case LHS=RHS. Induction Hypothesis: When $n=k$, $P(n)$ is true, i.e., $P(k)$ is true. In other words, $$f_1+f_3+\ldots+f_{2k-1}=f_{2k}$$ (What would happen if we would use the symbol $n$ instead of $k$?) The remaining part of your proof seems fine to me although it could be made more explicit.
{ "pile_set_name": "StackExchange" }
Q: Cannot read property ' ' of null I'm trying to access some data from an API but when I do I get Cannot read property '5' of null import React from "react"; function Card(props) { console.log(props.data[5].mission_name); //why is it that this doesn't work in my machine? console.log(props.data); //this works with my machine return ( <div> <h1>test</h1> </div> ); } export default Card; I initially set the data that I'm passing as null and then I update it once the data from the API loads so I'm thinking that might be part of the problem but I don't know how to get around it. I made a code sandbox for more context. And for reference I'm using the spacex api. https://codesandbox.io/embed/gallant-mcnulty-lyied?fontsize=14&hidenavigation=1&theme=dark Thanks in advance. A: As you said, you are initially setting the data value to null. When the Card initially renders, it'll try to index 5 on null and give you that error. Try something like if (props.data) { // the first render (where data is null) will skip this block console.log(props.data[5].mission_name); }
{ "pile_set_name": "StackExchange" }
Q: From objects to tables using activerecord I'm getting some objects from an external library and I need to store those objects in a database. Is there a way to create the tables and relationships starting from the objects, or I have to dig into them and create migrations and models by hand? Thanks! Roberto A: Even if you could dynamically create tables on the fly like that (not saying that you can). I wouldn't want to do that. There is so much potential for error there. I would create the migrations by hand and have the tables and fields pre-created and fill them in with rows as needed.
{ "pile_set_name": "StackExchange" }
Q: JavaScript - show/ hide function I am new to JavaScript and I do not know how to approach this homework assignment - "modify the page to hide all the images until the “start” button is clicked. Once clicked the start button should become the stop button and display the word “stop” and when clicked hide the images. Once hidden that same button should become the start button and display the word “start” and act again like the start button. Notice there is a single button that changes the text and what is does depending on whether the show is currently stopped or started." I know i am supposed to use the show/hide effects, but I don't really know how to apply them to the code? <!doctype html> <html> <head> <title>Slide Show</title> <!-- will remove the 404 error for favicon.ico from console --> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> <link rel="icon" href="favicon.ico" type="image/x-icon"> <!-- using jQuery --> <link href="simpleImageV2.css" rel="stylesheet" type="text/css"> <script src="jquery-3.3.1.min.js"></script> <script src="simpleImagesV2.js"></script> </head> <body bgcolor="black" onload="preLoadImages()"> <div id="setSize"> <img name="campus_pic" src="images/fall_1_480x640.png" width="480" height="640"> </div> <br /> <br /> <button id="startShow">Start the Show</button> <button id="stopShow">Stop the Show</button> </body> </html> JavaScript - /*global $ */ var i = 0, myTimer, campus; function preLoadImages() { "use strict"; if (document.images) { campus = new Array(); // global variable campus[0] = new Image(); campus[0][0] = "images/fall_1_480x640.png"; campus[0][1] = "480"; campus[0][2] = "640"; campus[1] = new Image(); campus[1][0] = "images/winter_1_640x480.png"; campus[1][1] = "640"; campus[1][2] = "480"; campus[2] = new Image(); campus[2][0] = "images/spring_1_640x480.png"; campus[2][1] = "640"; campus[2][2] = "480"; campus[3] = new Image(); campus[3][0] = "images/summer_1_480x640.png"; campus[3][1] = "480"; campus[3][2] = "640"; } else { window.alert("This browser does not support images"); } } A: You can use jQuery for that like below : /*global $ */ var i = 0, myTimer, campus; function preLoadImages() { "use strict"; if (document.images) { campus = new Array(); // global variable campus[0] = new Image(); campus[0][0] = "images/fall_1_480x640.png"; campus[0][1] = "480"; campus[0][2] = "640"; campus[1] = new Image(); campus[1][0] = "images/winter_1_640x480.png"; campus[1][1] = "640"; campus[1][2] = "480"; campus[2] = new Image(); campus[2][0] = "images/spring_1_640x480.png"; campus[2][1] = "640"; campus[2][2] = "480"; campus[3] = new Image(); campus[3][0] = "images/summer_1_480x640.png"; campus[3][1] = "480"; campus[3][2] = "640"; } else { window.alert("This browser does not support images"); } } function init() { $('#stopShow').hide(); } $(document).ready(function () { $("#startShow").click(function () { var images = ['<div>']; campus.forEach(function (img) { images.push('<img src="' + img[0] +'" height="' + img[1] + '" width="' + img[2] + '" />'); }); images.push('</div>'); $("#images").html(images.join('')); $('#startShow').hide(); $('#stopShow').show(); }); $("#stopShow").click(function () { $("#images").html(''); $('#stopShow').hide(); $('#startShow').show(); }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!doctype html> <html> <head> <title>Slide Show</title> <!-- will remove the 404 error for favicon.ico from console --> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> <link rel="icon" href="favicon.ico" type="image/x-icon"> <!-- using jQuery --> <link href="simpleImageV2.css" rel="stylesheet" type="text/css"> <script src="jquery-3.3.1.min.js"></script> <script src="simpleImagesV2.js"></script> </head> <body bgcolor="black" onload="preLoadImages(); init();"> <div id="setSize"> <img name="campus_pic" src="images/fall_1_480x640.png" width="480" height="640"> </div> <br /> <br /> <div id="images"></div> <button id="startShow">Start the Show</button> <button id="stopShow">Stop the Show</button> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Why doesn't a PHP string "<>" show up in echo? I have a question with regards to what happens to a PHP string enclosed within two <> symbols? For example, I have a string, "This is an <apple>". When I tried to echo the string, the result is "This is an". So my question is: what happens to the string enclosed within the symbols? To provide some context, I'm using this as a placeholder for a regex search and replace in my code. I'm also using PHP 5.3 at the moment. Thanks! A: That has got nothing to do with php, but with html. Your browser thinks you are using an html tag. To avoid that, you need to encode the characters: echo htmlspecialchars('This is an <apple>');
{ "pile_set_name": "StackExchange" }
Q: How to format int64 to upper case hex in Vala? The following example does not compile public static int main (string[] args) { var now = new GLib.DateTime.now_utc(); int64 val = now.to_unix(); print ("%" + int64.FORMAT + "\n", val); print ("%X\n", val); // ERROR return 0; } There is a int64 format string for decimal representation but none for hex (See Valadoc). The %X does also not work. How do I get upper case hex formatting for a int64? A: The error is a type error: Argument 2: Cannot convert from int64 to uint print uses the printf format string and accepts the long long type, which is specified as at least 64 bits. You can use %llX to print out an int64 as upper case hexadecimal. Working example: void main () { var now = new GLib.DateTime.now_utc(); int64 val = now.to_unix(); print ("%" + int64.FORMAT + "\n", val); print ("%llX\n", val); }
{ "pile_set_name": "StackExchange" }
Q: How to add an action to the button in Controller of magento? $fieldset->addField('test_connection', 'submit', array( 'label' => Mage::helper('rpos_connect')->__('Test Connection'), 'required' => true, 'value' => 'Test', 'after_element_html' => '', 'tabindex' => 1 )); This is my PHP code to prepare a form with a button in my module block folder.Now I want this to call a function named testAction() in my Controller class. A: You can use onclick as follows. 'onclick' => "setLocation('{$this->getUrl('*/controller/action')}')"
{ "pile_set_name": "StackExchange" }
Q: How can i return the address of a line in a Random Access file? i'm trying to create a Random Access file in java. I write something in a new line. How can i return the address of that line in Java? Also, I'm a bit confused with RAFs. For example i have a file that consists of the following entries in alphabetical manner George 10 10 8 Mary 9 10 10 Nick 8 8 8 Nickolas 10 10 9 I would like to return the grades of Nickolas. How can i declare that in a RAF? Is there any method that can "read("Nickolas")" and return to me the line? Thanks, in advance A: Random access files usually contain binary data rather than ascii (e.g. plain text) data. The example you are showing is ascii. Since the data is ascii, this means it's not as easy to seek to various places in the file. In fact, generally the approach to get the grades for Nickolas would be to read the file line by line and parse each line into columns. Then, compare the first column for Nickolas. For example, BufferedReader in = new BufferedReader(new FileReader("grades.txt")); String line = in.readLine(); while(null != line) { String [] columns = line.split(" "); if( columns[0].equals("Nickolas") ) System.out.println("I found the line! " + line); line = in.readLine(); } EDIT: There are a number of ways to speed this up. Here are three: Storing all data in a HashMap If you don't have too many records, or if each record doesn't take much space, you could read them all into RAM. You can also use a HashMap to map the name of the student to their record. For example: HashMap<String, Student> grades = new HashMap<String, Student>(); BufferedReader in = new BufferedReader(new FileReader("grades.txt")); String line = in.readLine(); while(null != line) { String [] columns = line.split(" "); grades.put( column[0], new Student( /* create student class instance from columns */ ); line = in.readLine(); } Now, lookups will be extremely fast. Using a Binary Search If you have too many records to fit in RAM, you can write all of the student data to a random access (binary) file. Here, you have a couple of options: you can either make each record vary in length, or you can make each record have a fixed length. Fixed length records are easier for some kinds of searching, like binary searches. For example, if you know each record is 100 bytes, then you know how to get to the n'th record in the binary file storing the records. Basically, read 99*n bytes. Then the next 100 bytes are the 100th record. Thus, if the records are sorted by student name, you can very easily use a binary search to find a specific student. This approach will still be fast, albeit not as fast as the RAM-based data structure. Using a HashMap as an index Yet another option is to combine the two approaches I mentioned above. Write the data to a binary file, and store the byte offsets of the records in a hash map. The hash map can use the student name as the key as before, but then stores a long integer offset to the record in the random access file. Thus, to look up a specific student, you find the byte offset using the hash map, and then "seek" to the record in the file and then read it. This last approach works even if the records vary in length.
{ "pile_set_name": "StackExchange" }
Q: Can someone expain how I use this C data structure that comes from grub? I don't understand hi mem and lo mem Grub is a multiboot compliant boot loader. When it boots an operating system it creates a structure defining the available memory and leaves a pointer to that structure in memory. I got that information here: http://wiki.osdev.org/Detecting_Memory_(x86)#Memory_Map_Via_GRUB This is the structure that I think I'm interested in: typedef struct memory_map { unsigned long size; unsigned long base_addr_low; unsigned long base_addr_high; unsigned long length_low; unsigned long length_high; unsigned long type; } memory_map_t; So I've got a collection of memory map structures. As the above page mentions, you can see the memory map by typing "displaymem" at the grub prompt. This is my output But I don't fully understand the structure.... Why are the lengths set to 0 (0x0)? Do I have to combine low memory and high memory? It says the values are in 64 bit so did it push together "low mem and high mem" together like this: __int64 full_address = (low_mem_addr + high_mem_addr); or am I getting 1 list containing both low and high addresses exclusively in them? and since I'm using a 32bit machine do I basically refer to each unique address with both values? I was expecting one single list of addresses, like displaymem shows but with actual length fields populated but I'm not seeing that. Is there something I don't understand? A: Ok, basically it's just two variables...that are 64 bit numbers, so what is above and what is below are IDENTICAL! typedef struct memory_map { unsigned long size; //unsigned long base_addr_low; //unsigned long base_addr_high; unsigned long long base_addr; // unsigned long length_low; // unsigned long length_high; unsigned long long length; //holds both halves. unsigned long type; } memory_map_t; You can get the two halves out like this: unsigned long base_addr_low = base_addr unsigned long base_addr_high = base_addr >> 32 The question was just that simple. :-s
{ "pile_set_name": "StackExchange" }
Q: How can I determine the transfer rate ? Can I determine from an ASP.NET application the transfer rate, i.e. how many KB per second are transferd? A: You can set some performance counters on ASP.NET. See here for some examples. Some specific ones that may help you figure out what you want are: Request Bytes Out Total The total size, in bytes, of responses sent to a client. This does not include standard HTTP response headers. Requests/Sec The number of requests executed per second. This represents the current throughput of the application. Under constant load, this number should remain within a certain range, barring other server work (such as garbage collection, cache cleanup thread, external server tools, and so on). Requests Total The total number of requests since the service was started.
{ "pile_set_name": "StackExchange" }
Q: How to select specific combobox item with multiple keystrokes? First few characters of item Windows explorer in XP will allow you to make a file selection based on typing a few characters. I would like to know if there is any simplistic .net feature I can use to mimic this behaviour in a combobox? I think I've seen this happen in comboboxes before, and would like to know if there is a property I can use? I know I could develop code around the "Key" events, but can't justify spending the time on it. For example: In a folder which contains "Apple.doc, banana.doc, cherry.doc, cranberry.doc" then typing "b" will select "banana.doc", typing "c" will select "cherry.doc" but typing "cr" will select "cranberry.doc" Thanks in advance G A: Have a look at ComboBox.AutoCompleteMode.
{ "pile_set_name": "StackExchange" }
Q: How to debug cocos2d-x 3 native code on android device I could not find any cookbook/tutorial how build in debug build a cocos2d-x 3.1 project for Android and how to debug it directly on device. Please help by pointing out steps. What I do and what problems I have: cd proj.android cocos compile -p android -m debug --ndk-mode NDK_DEBUG=1 (to build with debug info) cocos run -p android -m debug to deploy on device run app on the device cd jni ndk-gdb And I get this error: Nareks-MacBook-Pro:jni Narek$ ndk-gdb jni/Android.mk:67: *** Android NDK: Aborting. . Stop. ERROR: The device does not support the application's targetted CPU ABIs! Device supports: armeabi-v7a armeabi Package supports: Android NDK: Into Application.mk I have added: APP_ABI := armeabi armeabi-v7a APP_PLATFORM := android-10 but it did not help. What I do wrong? EDIT: Adding result of ndk-build DUMP_APP_ABI command called in projects jni directory: Nareks-MacBook-Pro:jni Narek$ ndk-build DUMP_APP_ABI Android NDK: /Users/Narek/NoorGames/Games/test2/proj.android/jni/Android.mk: Cannot find module with tag '.' in import path Android NDK: Are you sure your NDK_MODULE_PATH variable is properly defined ? Android NDK: The following directories were searched: Android NDK: /Users/Narek/NoorGames/Games/test2/proj.android/jni/Android.mk:67: *** Android NDK: Aborting. . Stop. A: Here is the step-by-stet tutorial to debug cocos2d-x 3.x on Android device. Please correct or optimize my steps if you do it in better way. cd proj.android cocos compile -p android -m debug --ndk-mode NDK_DEBUG=1 (to build with debug info) cocos run -p android -m debug to deploy on device (sometimes it rebuilds, and I don't know why). This command uninstalls former installation, installs the new one and runs the app on the device. make sure in proj.android/libs/armeabi directory you have the following files gdb.setup, gdbserver, libcocos2dcpp.so also make sure that in /proj.android/jni/obj/local/armeabi directory you have app_process, gdb.setup, libc.so, linker ndk-gdb (important! this should be called in projects directory, not in jni directory) If it worked then congratulations! But in this step you may see such error message: Nareks-MacBook-Pro:proj.android Narek$ ndk-gdb jni/Android.mk:67: *** Android NDK: Aborting. . Stop. ERROR: The device does not support the application's targetted CPU ABIs! Device supports: armeabi-v7a armeabi Package supports: Android NDK: Don't worry :). Lets see what is wrong: here is the result of ndk-build DUMP_APP_ABI command called in project's jni directory: Nareks-MacBook-Pro:jni Narek$ ndk-build DUMP_APP_ABI Android NDK: /Users/Narek/NoorGames/Games/test2/proj.android/jni/Android.mk: Cannot find module with tag '.' in import path Android NDK: Are you sure your NDK_MODULE_PATH variable is properly defined ? Android NDK: The following directories were searched: Android NDK: /Users/Narek/NoorGames/Games/test2/proj.android/jni/Android.mk:67: *** Android NDK: Aborting. . Stop. As you can see NDK_MODULE_PATH is missing. For obtaining the value do the following. Go to step where you compiled code. In first linse of execution of command cocos compile -p android -m debug --ndk-mode NDK_DEBUG=1 you can see something like this: Runing command: compile Building mode: debug building native NDK build mode: NDK_DEBUG=1 The Selected NDK toolchain version was 4.8 ! running: '/Users/Narek/NoorGames/android-ndk-r9d/ndk-build -C /Users/Narek/NoorGames/Games/test2/proj.android -j1 NDK_MODULE_PATH=/Users/Narek/NoorGames/Games/test2/proj.android/../cocos2d:/Users/Narek/NoorGames/Games/test2/proj.android/../cocos2d/cocos:/Users/Narek/NoorGames/Games/test2/proj.android/../cocos2d/external' copy from the log above you see the necessary value of NDK_MODULE_PATH. Execute the following command export NDK_MODULE_PATH=/Users/Narek/NoorGames/Games/test2/proj.android/../cocos2d:/Users/Narek/NoorGames/Games/test2/proj.android/../cocos2d/cocos:/Users/Narek/NoorGames/Games/test2/proj.android/../cocos2d/external (be attentive to copy your path not mine) That's it. Now run game on device, cd proj.android, call ndk-gdb and you should be able to debug with gdb. I personally looked for this kind of tutorial already more than 20 days. I hope you enjoy your debugging already. :) And thank you @VikasPatidar for your help with ndk-build DUMP_APP_ABI step! EDIT1: As commented Vikas you can add NDK_MODULE_PATH in Android.mk file like this: NDK_MODULE_PATH := $(LOCAL_PATH)/../../../../cocos NDK_MODULE_PATH += $(LOCAL_PATH)/../../../../external EDIT2: If your app crashed here is a very powerful and easy way to investigate the problem by preventing direct debugging: adb logcat | $NDK_ROOT/ndk-stack -sym $PROJECT_PATH/obj/local/armeabi It prints the crash dump.
{ "pile_set_name": "StackExchange" }
Q: Maximizing the efficiency of a simple algorithm in MATLAB So here is what I'm trying to do in MATLAB: I have an array of n, 2D images. I need to go through pixel by pixel, and find which picture has the brightest pixel at each point, then store the index of that image in another array at that point. As in, if I have three pictures (n=1,2,3) and picture 2 has the brightest pixel at [1,1], then the value of max_pixels[1,1] would be 2, the index of the picture with that brightest pixel. I know how to do this with for loops, %not my actual code: max_pixels = zeroes(x_max, y_max) for i:x_max for j:y_max [~ , max_pixels(i, j)] = max(pic_arr(i, j)) end end But my question is, can it be done faster with some of the special functionality in MATLAB? I have heard that MATLAB isn't too friendly when it comes to nested loops, and the functionality of : should be used wherever possible. Is there any way to get this more efficient? -PK A: You can use max(...) with a dimension specified to get the maximum along the 3rd dimension. [max_picture, indexOfMax] = max(pic_arr,[],3)
{ "pile_set_name": "StackExchange" }