w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Do I need to explicitly include a common header file(in an include path folder) used in shared library?
If your main_prog.c depends on shr_struct.h, the compiler will need to know where this last file is located. Now if the library is installed in the system "standard" library path, you may not have to explicitly add this path to the compiler command as it may be smart enough to search in the standard system path by itself.

Categories : C

Testing python package bin scripts best practice
I don't believe there is any "best practices" about where to put tests. See how many different opinions are there: Where do the Python unit tests go? I'd personally have one and only tests directory on the top-level, near your bin and mypackage directories - as, for example, django has. For running your bin script and getting results you can use: subprocess (as you've mentioned), but using check_output: import subprocess output = subprocess.check_output("cat /etc/services", shell=True) scripttest module was designed to test command-line scripts - looks like the tool for a job also see this article cli and it's cli.test module (haven't ever used personally) Hope that helps.

Categories : Python

How to create a common array and be used between several perl scripts?
Normally one perl instance can not access the variables of another instance. The question then becomes "what can one do that is almost like sharing variables"? One approach is to store data somewhere it can persist, such as in a database or a CSV file on disk. This means reading the data at the beginning of the program, and writing it or updating it, and naturally leads to questions about race conditions, locking, etc... and greatly expands the scope that any possible answer would need to cover. Another approach is to write your programs to use CSV or YAML or some other format easily read and written by libraries from CPAN, and use STDIN and STDOUT for input and output. This allows decoupling of storage, and also chaining several tools together with a pipe from the shell prompt. For

Categories : Perl

Python: sharing common code among a family of scripts
My preference would be a separate "bin" or "scripts" directory, with subprojects as libraries / packages: projectroot | |- scripts | |- lib | | | `- matcher.py | `- merger.py | `- subproject1 | `- subproject2 | `- subproject3 The idea being your scripts can each reference any subprojects necessary as usual packages. And your subprojects can also reference each other with imports. You can then also have a main or shared script that sets up the subproject packages for you, if that helps.

Categories : Python

Is it a common practice to copy code from the .net libraries?
This is not common practice, but in fact (very) bad practice. Depending on the license of the code (work) that was decompiled it may or may not be legal in terms of copyright laws. When applied to a class, the sealed modifier prevents other classes from inheriting from it. The author of a class marked as sealed did not want anyone to inherit from it. You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.

Categories : C#

best practice common imports between base/child class
As far as I know, the best practice is considered to keep all imports explicit. Just the way they are right now. But, you probably need to import base from child in order to inherit from Base. When you import base, x, y, z and Base will be available as base.x, base.y, base.z and base.Base.

Categories : Python

How do I layout code in a website with a common header import and jquery scripts?
Sure, I do the same thing with php. I split my header into two, so I include three items: <jsp:include page="headerTop.jsp" /> <!-- custom CSS links go here --> <!-- javascript references go here --> <!-- custom javascript goes here --> <jsp:include page="headerBottom.jsp" /> <!-- Page contents go here. --> <jsp:include page="footer.jsp" /> The headerTop.jsp file would contain the <head> tag, and the headerBottom.jsp file would contain the closing </head> tag.

Categories : Javascript

Common practice to compress image before sending to mobile device?
Since latency is often the largest problem with mobile connections, reducing the number of connections you have to open is a great way to optimize the loading times. Sending a zip file with all the images sounds like a very good idea, and is probably worth the time implementing.

Categories : PHP

C/C++ #include formating best practice
This is a subjective answer; if both work then both are correct, however I prefer to have no knowledge of the source tree within the source code, only in the project settings/Makefile, so for me the first option is best: #include "mycode.h"

Categories : C++

Is it good practice to include a setter in my object even if I know I will never need it
By not creating a setter and only allowing the field to be set through the constructor, you have created an immutable field. Once you create an instance of your class, that value will never change. Note: The statement above will not hold if the value return by your getter is itself mutable. Say, if returning an instance of ArrayList, someone can use that reference to add and remove items in that list. Look at java.util.Collections.unmodifiableList to fix that. Even a java.util.Date can be changed if you return it in a getter. To fix that, you can use JodaTime (or other similar third-party date classes), or wait for Java 8. In my humble (and other's not always so humble) opinion(s) imutability is a great thing that makes software less buggy and easier to maintain.

Categories : Java

What is the best practice for multiple "Include"-s in Entity Framework?
Some of the performance considerations are ADO.Net connector specific. I would keep in mind a database view or stored procedure as a backup if you're not getting the performance needed. First, note that DbContext (and ObjectContext) objects are not thread-safe. If you are concerned about clairity over performance, then the first option is the simplest. On the other hand, if you're worried about performance--and are willing to dispose of the context object after getting the data--then you can query the data with multiple simultaneous tasks (threads) each using their own context object. If you need a context to track changes to the data, you have the straight forward way of a single query to add all the items to the context, or you can use the Attach method to 'rebuild' the original stat

Categories : C#

Should I put the entire head tag and footer scripts inside the an include file?
You could do something like this, with the example for a home page: <?php // put metadata inside this array $pageData = array( 'title' => 'my page title', 'metaDataDescription' => 'my meta data for this page', 'customAssets' => array( array( 'type' => 'js', 'src' => '//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js' ) ) ); // include your header file now require_once 'header.php'; ?> <div> This is where the unique content or HTML for this page should go. You could also include unique JavaScript here as well </div> <?php require_once 'footer.php'; ?> And then the header.php file could lo

Categories : HTML

How can I use make to maintain a common C++ header include directory?
Alternatively, is there a better way to make my header files available to other components in the same project? There are two obvious and simple ways: keep all the headers in the include dir in the first place set up CPPFLAGS for each component to tell it where to find its dependencies. I'd recommend the former approach for small, tightly-coupled projects. The second approach is better for really componentized systems, as it forces you to think about the internal dependencies in your project.

Categories : C++

Is it considered poor DI practice to include your app container within the constructor of a service?
In my opinion, passing in the container is not good design. You are essentially passing in a generic object construction factory, and so bypass the value inherent in being explicit about your dependencies. In practice you could just as well declare a static property for container on your Service class. If I need to construct objects dynamically, I usually pass in a factory instead of an explicit instance. Like, passing in an ILogFactory instead of just an instance of ILog. This makes it apparent from the code what things are constructed dynamically, at the cost of a few factories and constructor parameters. Another option, if you do not have a need to create multiple instances of the dependencies, but you know you will only need some of them, is to ensure that object construction is ligh

Categories : C#

Is it good programming practice to use shell scripts in systems programming
You're running the shell script from within code in another language? In that case using a shell script is almost certainly unnecessary. Virtually all languages allow you to run an arbitrary command and capture the output. For example, C and friends have popen() and Perl, Ruby and such have backticks (`lpstat -a` returns the output of that command as a string). This kind of approach makes it unnecessary to have an extra shell script or a temporary file.

Categories : Bash

php include function to include parent folder in LAMP server
Drop the leading / and change your includes to include("../footer.php"); the leading / means from the root of the file system. You are digging below the root and there just ain't nothing there. Another thing to beware of when dealing with problems between windows and linux is that on windows ../footer.php is the same as ../Footer.php which is not the case on linux (case sensitive vs case insensitive file systems). UPDATE The final solution was to for the relative path for the include into a absolute one by prefixing it with __DIR__ as in ... include(__DIR__."/../footer.php");

Categories : PHP

Why is it considered a better practice to use anonymous function instead of a function reference as parameter?
Using a naming function involves : more code a pollution of the global space a less readable code because it isn't obvious that the function isn't used elsewhere So, provided you don't reuse the function, it's better to use an anonymous one instead of creating a named function. But that if your code is exactly the one you show, then the anonymous function makes no sense at all. What would be the equivalent anonymous equivalent of the second code is addEventHandler(document.getElementById('btnAdd'), "click", function() { // addNewItem implementation }, false); And if you already have a named function, for example because you reuse it, then don't use an anonymous function just to wrap it.

Categories : Javascript

Why using @function (disabling error reporting per function) in PHP is bad practice?
Yeah it is a bad practice. For example an user wants to register on your site and you will send him an activation link or something important in the mail. You are using @mail, but the mail can not be send, because of an internal error(mail server down) or something like that. Will the user ever know, that the email wasn't sent? No, because you suppressed the error with the @ or didn't handle the error and notified the user.

Categories : PHP

Access function from within scripts and from commandline
try the following (note that the different indentation, the if __name__ part is not part of class test anymore): class test: def quicktest(params): pprint(params) if __name__ == '__main__': if sys.argv[1] == "quicktest": testObj = test() testObj.quicktest(sys.argv) else: print "Wrong call." from other scripts: from test import test testObj = test() testObj.quicktest(...)

Categories : Python

Is it bad practice to use a function in an if statement?
No real difference. The second is better if you need the value again of course. It's also marginally easier to debug when you have a value stored in a variable. Personally I tend to use the first because I'm an old school C programmer at heart!

Categories : Vb.Net

make HTML generated by content scripts of extensions inaccessible to page scripts
There aren't any special Chrome Extension techniques for this. As you'll read here, JavaScript injected via a content script is automatically sandboxed, or separated from the JavaScript on a web page, but this is not the case for HTML -- the DOM elements are shared between the page scripts and the injected content scripts.

Categories : Javascript

Contexts and methods for communication between the browser action, background scripts, and content scripts of chrome extensions?
It's been some time since I have had to deal with chrome's extensions. I remember it was quite a struggle before I got how things worked. In order for your extension to communicate with the browser it's easy you use your javascript/background file, and to communicate with the webpage you need to use chrome.tabs.executeScript but that's really tricky and can be a real pain in the butt. I suggest you take google's tour on extensions and give their api a really good overlook, everything's in there! I wish you good luck and I hope this answer has helped you! :P

Categories : Javascript

Nested function calls - What's the best practice?
I usually go for the first option, because that way I can insert a breakpoint between the invocations of GetResults and SendResults. It's usually not that big of a deal, if the code is in the middle of a method, but if it's in the form of: return Process(GetData()); the return values of both the GetData and the Process calls are not readily visible. Unless we are talking of a framework function that has no side effects and has obvious results (e.g. int.Parse) I prefer the format: var data = GetData(); var result = Process(data); return result;

Categories : C#

Chrome call function in content scripts from background.js
To call a function in the content script from the background page, you first need to know the tab id. contextMenus.onClicked event has a tab parameter containing that id. Then use message passing to do it. For example, in your background page: chrome.contextMenus.onClicked.addListener(function(info, tab) { if (tab) chrome.tabs.sendMessage(tab.id, {args: ...}, function(response) { // ... }); }); In your content script: chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { sendResponse(myFunc(request.args)); });

Categories : Javascript

It is good practice to pass the dbcontext to a function?
If you use IOC container, the recommended approach is to inject the IContext in your contoller constructor per Http Request, then you can use it in any function. I would not recommend passing the context into your function.

Categories : Entity Framework

Returning Meaningful Errors From C++ Function - Best Practice
Technically if the error is something that shouldn't happen in normal operation, this is what C++ expects you to use exceptions for, and they are as standard as anything else in C++. However, if the error may be a part of normal program flow, or if due to performance exceptions are not an option, consider returning a std::pair, or std::optional (C++14 or boost) if just the fail/succeed information is needed.

Categories : C++

Is there a way to get Common/templated functionality with different function names?
I don't know your types and such, but will this work? template<typename Req, typename Data> bool getGeneric(Data::CallbackType Callback){ if (Callback != nullptr) return false; Req* request = new T(this, GetNewRequestID()); //what is *this? Data* data = new Data(request,Callback); return StoreAndPerformRequest(data); } //getGeneric<FriendsListRequest, FriendsListRequestData> == GetFriendsList //getGeneric<AccountInfoRequest, AccountInfoRequestData> == GetAccountInfo By the way, the template inputs should be able to be automatically deduced; I don't think you would have to explicitly declare them, but I've been wrong about that before on some occasions.

Categories : C++

What algorithm is used for "sort" function in Common Lisp?
Yes, the algorithm is implementation defined (imagine prescribing a specific algorithm in the standard, and then someone comes a long and invents a better general purpose one). You can look up the standard yourself (just google "clhs sort"). The implementation provided sort and stable-sort should generally cover almost any sorting need you have. I can imagine the following reasons to write your own: You need hooks into specific stages of the sorting procedure You need only partial sorting You need a specific algorithm for your problem domain You want to compare different algorithms In any case, I should recommend to take a deep look into the existing sorting implementations in order not to miss possible optimizations (which is generally relevant in the context of sorting).

Categories : Sorting

Common FormatDate function for different date formats
I think you can first create a javascript Date object from date string then format it in what ever way you want. ex: var date = new Date("7/18/2013 4:28:52 PM"); then you can use different date class methods and format the string manually.

Categories : Javascript

Networkx: Use common function for edge weight calculation
Neither graph.size nor graph.add_edge uses a function to evaluate the weight, they just store values with a given key. To make it easier to work with, just define a function to add an edge with the appropriate weight: def add_euc2d_edge(graph, u, v): graph.add_edge(u, v, weight=euc_2d(graph, u, v))

Categories : Python

function to find common rows between more than two data frames in R
Rewritten: common <- function(a, b, c, d) { Name <- a$Name inB <- Name %in% b$Name inC <- Name %in% c$Name inD <- Name %in% d$Name which(!(inB | inC | inD)) }

Categories : R

Status of perl scripts run from bash scripts
Perl scripts behave the same when run from the shell. Having test.pl: #!/usr/bin/env perl exit(0); # or just exit running: ./test.pl && echo "OK" || echo $? OK Having #!/usr/bin/env perl exit(123); running: ./test.pl && echo "OK" || echo $? 123 Having #!/usr/bin/env perl die; running: ./test.pl && echo "OK" || echo $? Died at ./test.pl line 2. 255 So: Exiting from perl script with 0 (or nothing) will be true in shell. Exiting from perl script with a (byte) value other than 0 will be false in shell and $? will give you the exit value. Exiting from perl script with die will be false in shell and $? will be 255 (in my case - I checked it).

Categories : Linux

Changing the global variable from inside a function, or best practice to achieve the same
Leave the first var and remove the one inside the function var projectCounter = 1; $('a').click(function() { function setValue() { projectCounter = projectCounter + 1; alert(window.projectCounter); } }); Your setValue() function never runs in the code you posted. It will only be defined after a click (so it's not available before) and only after that click can you call/run it. Is that what you want? If you want the projectCounter variable to add on click, remove the whole function setValue() leaving only its content. when you run setValue() projectCounter will be 2, in this example. You can also use just projectCounter++; to achieve same as projectCounter = projectCounter + 1;

Categories : Javascript

Is it bad practice to store the hash function used as part of the hashed password?
I think this is good practice. It means that if you upgrade your hashing function (to something more secure) new users will use the one new one immediately. Now, you can't rehash users on the old hashing functions immediately, since you need their password to do that, and you can't retrieve it from its hashed state. Instead, when such a user logs in, you use their password to store a new hashed column, and reset the hashing function against their user account. Thus, with such a configuration, users will slowly move onto the more secure system as they log in.

Categories : PHP

Passing object to a function to use common functionality among distinct C# classes
What about: if(someBool) Use(dv.SelectMany(x => x.Rows).SelectMany(x => x.Cells[2].Text)); else Use(gv.SelectMany(x => x.Rows).SelectMany(x => x.Cells[2].Text)); And changing the Use() method to accept an IEnumerable<string> instead of a single string. Still looks like violating DRY, but you've removed the foo() method.

Categories : C#

How to create a common function in codeigniter for checking if session exist?
You can create a function in library that you created it or another library ex: application/libraries/Common.php public function logged_in() { return (bool) $this->session->userdata('userId'); } Using like this: if ($this->common->logged_in()) { // User logged } else { // User not logged }

Categories : PHP

Why is it considered bad practice to call trigger: true in the navigate function of backbone.js?
In my opinion it's considered bad practice because you should imagine a Backbone application not like a Ruby On Rails application but rather like a Desktop application. When I say RoR, I'm just saying a framework supporting routing in sense that a route brings you to a specific call to the controller to run a specific action (imagine a CRUD operation). Backbone.history is intended just as a bookmark for the user so he can, for example, save a specific url, and run it again later. In this case he will find the same situation he left before. When you say: In my opinion it is not really bad to call the navigate function with the trigger:true option. The route function could upon calling always check if the considered data is already loaded and show this loaded data instead of doi

Categories : Backbone Js

Best practice for refactoring a python function to return a tuple, instead of a single variable?
Rename the function to GetEventsAndHeader(), and add a new function GetEvents(): def GetEvents(*args, **kw): return GetEventsAndHeader(*args, **kw)[0] or just bite the bullet and update all code that calls GetEvents() and adjust that code to either use the returnvalue indexed to [0] or make use of the headers as well.

Categories : Python

Write a function taking arbitrary objects and methods with common return types
The simplest way is make a new subclass of Status that fills it the Failed property for you, you can just have the constructor take a object in as the type and call GetType() in there. public class FailedStatus : Status { public FailedStatus(object source) { this.Failed = source.GetType().ToString(); } } Result resultA = A.something(); if(resultA.Failed) return new FailedStatus(A); Result resultB = B.somethingElse(3); if(resultB.Failed) return new FailedStatus(B); Result result3 = C.someOtherThing("apple"); if(resultC.Failed) return new FailedStatus(C); If Result derives from Status too the least verbose way is modify something(), somethingElse(int), and someOtherThing(string) to set the string itself (but I doubt this is true sense it appears Result.Failed is a

Categories : C#

VBA function to include CDATA
Yes as Ripster says find the library reference. From the VBA window Tools>References For a list of relevant references see... http://msdn.microsoft.com/en-us/library/windows/desktop/ms763701%28v=vs.85%29.aspx However, if you have a hard time tracking down the reference, replace all Dim Statements and Set objDom = New DOMDocument to... Dim objDom as Object Set objDom = CreateObject("Microsoft.XMLDOM") ' EDIT: If this does not work, try... 'Set objDom = CreateObject("MSXML22.DOMDocument.6.0") Dim objKMLRootelement As Object Dim objKMLelement As Object Dim cdata As Object

Categories : Vba



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.