Rails: Why "sudo" command is not recognized?
Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions.
Windows does not have (need?) this.
Run the command with the sudo removed from the start.
How to get the full url in Express?
The protocol is available as req.protocol
. docs here
- Before express 3.0, the protocol you can assume to be
http
unless you see that req.get('X-Forwarded-Protocol')
is set and has the value https
, in which case you know that's your protocol
The host comes from req.get('host')
as Gopal has indicated
Hopefully you don't need a non-standard port in your URLs, but if you did need to know it you'd have it in your application state because it's whatever you passed to app.listen
at server startup time. However, in the case of local development on a non-standard port, Chrome seems to include the port in the host header so req.get('host')
returns localhost:3000
, for example. So at least for the cases of a production site on a standard port and browsing directly to your express app (without reverse proxy), the host
header seems to do the right thing regarding the port in the URL.
The path comes from req.originalUrl
(thanks @pgrassant). Note this DOES include the query string. docs here on req.url and req.originalUrl. Depending on what you intend to do with the URL, originalUrl
may or may not be the correct value as compared to req.url
.
Combine those all together to reconstruct the absolute URL.
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
When do I use path params vs. query params in a RESTful API?
In a REST API, you shouldn't be overly concerned by predictable URI's. The very suggestion of URI predictability alludes to a misunderstanding of RESTful architecture. It assumes that a client should be constructing URIs themselves, which they really shouldn't have to.
However, I assume that you are not creating a true REST API, but a 'REST inspired' API (such as the Google Drive one). In these cases the rule of thumb is 'path params = resource identification' and 'query params = resource sorting'. So, the question becomes, can you uniquely identify your resource WITHOUT status / region? If yes, then perhaps its a query param. If no, then its a path param.
HTH.
Difference between $(this) and event.target?
Within an event handler function or object method, one way to access the properties of "the containing element" is to use the special this keyword. The this keyword represents the owner of the function or method currently being processed. So:
For a global function, this represents the window.
For an object method, this represents the object instance.
And in an event handler, this represents the element that received the event.
For example:
<!DOCTYPE html>
<html>
<head>
<script>
function mouseDown() {
alert(this);
}
</script>
</head>
<body>
<p onmouseup="mouseDown();alert(this);">Hi</p>
</body>
</html>
The content of alert windows after rendering this html respectively are:
object Window
object HTMLParagraphElement
An Event object is associated with all events. It has properties that provide information "about the event", such as the location of a mouse click in the web page.
For example:
<!DOCTYPE html>
<html>
<head>
<script>
function mouseDown(event) {
var theEvent = event ? event : window.event;
var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
alert(event);
alert(locString);
}
</script>
</head>
<body>
<p onmouseup="mouseDown(event);">Hi</p>
</body>
</html>
The content of alert windows after rendering this html respectively are:
object MouseEvent
X = 982 Y = 329
How to remove specific elements in a numpy array
list comprehension could be an interesting approach as well.
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = np.array([2, 3, 6]) #index is changed to an array.
out = [val for i, val in enumerate(a) if all(i != index)]
>>> [1, 2, 5, 6, 8, 9]
Field 'id' doesn't have a default value?
Solution: Remove STRICT_TRANS_TABLES
from sql_mode
To check your default setting,
mysql> set @@sql_mode =
'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
Query OK, 0 rows affected (0.00 sec)
mysql> select @@sql_mode;
+----------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------+
| STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------------------------+
1 row in set (0.00 sec)
Run a sample query
mysql> INSERT INTO nb (id) VALUES(3);
ERROR 1364 (HY000): Field 'field' doesn't have a default value
Remove your STRICT_TRANS_TABLES
by resetting it to null.
mysql> set @@sql_mode = '';
Query OK, 0 rows affected (0.00 sec)
Now, run the same test query.
mysql> INSERT INTO nb (id) VALUES(3);
Query OK, 1 row affected, 1 warning (0.00 sec)
Source: https://netbeans.org/bugzilla/show_bug.cgi?id=190731
Using "Object.create" instead of "new"
I think the main point in question - is to understand difference between new
and Object.create
approaches. Accordingly to this answer and to this video new
keyword does next things:
Creates new object.
Links new object to constructor function (prototype
).
Makes this
variable point to the new object.
Executes constructor function using the new object and implicit perform return this
;
Assigns constructor function name to new object's property constructor
.
Object.create
performs only 1st
and 2nd
steps!!!
In code example provided in question it isn't big deal, but in next example it is:
var onlineUsers = [];
function SiteMember(name) {
this.name = name;
onlineUsers.push(name);
}
SiteMember.prototype.getName = function() {
return this.name;
}
function Guest(name) {
SiteMember.call(this, name);
}
Guest.prototype = new SiteMember();
var g = new Guest('James');
console.log(onlineUsers);
As side effect result will be:
[ undefined, 'James' ]
because of Guest.prototype = new SiteMember();
But we don't need to execute parent constructor method, we need only make method getName
to be available in Guest.
Hence we have to use Object.create
.
If replace Guest.prototype = new SiteMember();
to Guest.prototype = Object.create(SiteMember.prototype);
result be:
[ 'James' ]
Moving from JDK 1.7 to JDK 1.8 on Ubuntu
Most of the answers for this question can not helped me in 2020.
This notification from download site of Oracle may be the reason:
Important Oracle JDK License Update
The Oracle JDK License has changed for releases starting April 16, 2019.
I try to google a little bit and those tutorials below helped me a lot.
Remove completely the previous version of JVM installed on your
PC.
sudo update-alternatives --remove-all java
sudo update-alternatives --remove-all javac
sudo update-alternatives --remove-all javaws
# /usr/lib/jvm/jdk1.7.0 is the path you installed the previous version of JVM on your PC
sudo rm -rf /usr/lib/jvm/jdk1.7.0
Check to see whether java is uninstalled or not
java -version
Install Java 8
JDK.
- Download Java 8 from Oracle's website. The version being used is
1.8.0_251
. Pay attention to this value, you may need it to edit commands in this answer when Java 8 is upgraded to another version.
- Extract the compressed file to the place where you want to install.
cd /usr/lib/jvm
sudo tar xzf ~/Downloads/jdk-8u251-linux-x64.tar.gz
sudo gedit /etc/environment
- Edit the PATH's value by appending the string below to the current value
:/usr/lib/jvm/jdk1.8.0_251/bin:/usr/lib/jvm/jdk1.8.0_251/jre/bin
- Append those strings to the environment file
J2SDKDIR="/usr/lib/jvm/jdk1.8.0_251"
J2REDIR="/usr/lib/jvm/jdk1.8.0_251/jre"
JAVA_HOME="/usr/lib/jvm/jdk1.8.0_251"
- Complete the installation by running commands below
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_251/bin/java" 0
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_251/bin/javac" 0
sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_251/bin/java
sudo update-alternatives --set javac /usr/lib/jvm/jdk1.8.0_251/bin/javac
update-alternatives --list java
update-alternatives --list javac
Getting permission denied (public key) on gitlab
I found the solution in gitlab help.
To create a new SSH key pair:
1. Open a terminal on Linux or macOS, or Git Bash / WSL on Windows.
2. Generate a new ED25519 SSH key pair: ssh-keygen -t ed25519 -C "[email protected]"
2.1 Or, if you want to use RSA: ssh-keygen -o -t rsa -b 4096 -C "[email protected]"
3. Next, you will be prompted to input a file path to save your SSH key pair to... use the suggested path by pressing Enter
4. Once the path is decided, you will be prompted to input a password to secure your new SSH key pair. It's a best practice to use a password, but it's not required and you can skip creating it by pressing Enter twice.
5. Copy your public SSH key to the clipboard by using one of the commands below depending on your Operating System:
macOS: pbcopy < ~/.ssh/id_ed25519.pub
WSL / GNU/Linux (requires the xclip package): xclip -sel clip < ~/.ssh/id_ed25519.pub
Git Bash on Windows: cat ~/.ssh/id_ed25519.pub | clip
6. Navigating to SSH Keys and pasting your public key in the Key field
7. Click the Add key button
I hope it can help some of you!
Removing duplicates in the lists
I had a dict in my list, so I could not use the above approach. I got the error:
TypeError: unhashable type:
So if you care about order and/or some items are unhashable. Then you might find this useful:
def make_unique(original_list):
unique_list = []
[unique_list.append(obj) for obj in original_list if obj not in unique_list]
return unique_list
Some may consider list comprehension with a side effect to not be a good solution. Here's an alternative:
def make_unique(original_list):
unique_list = []
map(lambda x: unique_list.append(x) if (x not in unique_list) else False, original_list)
return unique_list
Changing the resolution of a VNC session in linux
As this question comes up first on Google I thought I'd share a solution using TigerVNC which is the default these days.
xrandr
allows selecting the display modes (a.k.a resolutions) however
due to modelines being hard
coded
any additional modeline such as "2560x1600" or "1600x900" would need to
be added into the
code. I
think the developers who wrote the code are much smarter and the hard
coded list is just a sample of values. It leads to the conclusion that
there must be a way to add custom modelines and man xrandr
confirms
it.
With that background if the goal is to share a VNC session between two
computers with the above resolutions and assuming that the VNC server is
the computer with the resolution of "1600x900":
Start a VNC session with a geometry matching the physical display:
$ vncserver -geometry 1600x900 :1
On the "2560x1600" computer start the VNC viewer (I prefer
Remmina) and connect to the remote VNC
session:
host:5901
Once inside the VNC session start up a terminal window.
Confirm that the new geometry is available in the VNC session:
$ xrandr
Screen 0: minimum 32 x 32, current 1600 x 900, maximum 32768 x 32768
VNC-0 connected 1600x900+0+0 0mm x 0mm
1600x900 60.00 +
1920x1200 60.00
1920x1080 60.00
1600x1200 60.00
1680x1050 60.00
1400x1050 60.00
1360x768 60.00
1280x1024 60.00
1280x960 60.00
1280x800 60.00
1280x720 60.00
1024x768 60.00
800x600 60.00
640x480 60.00
and you'll notice the screen being quite small.
List the modeline (see xrandr article in ArchLinux wiki) for
the "2560x1600" resolution:
$ cvt 2560 1600
# 2560x1600 59.99 Hz (CVT 4.10MA) hsync: 99.46 kHz; pclk: 348.50 MHz
Modeline "2560x1600_60.00" 348.50 2560 2760 3032 3504 1600 1603 1609 1658 -hsync +vsync
or if the monitor is old get the GTF timings:
$ gtf 2560 1600 60
# 2560x1600 @ 60.00 Hz (GTF) hsync: 99.36 kHz; pclk: 348.16 MHz
Modeline "2560x1600_60.00" 348.16 2560 2752 3032 3504 1600 1601 1604 1656 -HSync +Vsync
Add the new modeline to the current VNC session:
$ xrandr --newmode "2560x1600_60.00" 348.16 2560 2752 3032 3504 1600 1601 1604 1656 -HSync +Vsync
In the above xrandr
output look for the display name on the second
line:
VNC-0 connected 1600x900+0+0 0mm x 0mm
Bind the new modeline to the current VNC virtual monitor:
$ xrandr --addmode VNC-0 "2560x1600_60.00"
Use it:
$ xrandr -s "2560x1600_60.00"
How to assign multiple classes to an HTML container?
From the standard
7.5.2 Element identifiers: the id and class attributes
Attribute definitions
id = name [CS]
This attribute assigns a name to an element. This name
must be unique in a document.
class = cdata-list [CS]
This attribute
assigns a class name or set of class names to an element. Any number
of elements may be assigned the same class name or names. Multiple
class names must be separated by white space characters.
Yes, just put a space between them.
<article class="column wrapper">
Of course, there are many things you can do with CSS inheritance. Here is an article for further reading.
What is the difference between persist() and merge() in JPA and Hibernate?
Persist should be called only on new entities, while merge
is meant to reattach detached entities.
If you're using the assigned generator, using merge
instead of persist
can cause a redundant SQL statement.
Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.
Best practice for localization and globalization of strings and labels
When you’re faced with a problem to solve (and frankly, who isn’t
these days?), the basic strategy usually taken by we computer people
is called “divide and conquer.” It goes like this:
- Conceptualize the specific problem as a set of smaller sub-problems.
- Solve each smaller problem.
- Combine the results into a solution of the specific problem.
But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:
- Conceptualize the specific problem as a special case of a more general problem.
- Somehow solve the general problem.
- Adapt the solution of the general problem to the specific problem.
- Eric Lippert
I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.
I've outlined some of the major aspects of the problem
ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)
Issue: Resource files for each page should be separated so we only get the data we need
Solution: We can use some tools that already exist like
https://github.com/rgrove/lazyload
Issue: We need a key/value pair structure to save our data
Solution: I suggest a javascript object instead of string/string air.
We can benefit from the intellisense from an IDE
Issue: General members should be stored in a public file and all pages should access them
Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'
Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope
Solution: I considered a file for each
Application Structure
root/
Global_Resources/
default.js
default.fr.js
UserManagementSystem/
Local_Resources/
default.js
default.fr.js
createUser.js
Login.htm
CreateUser.htm
The corresponding code for the files:
Global_Resources/default.js
var res = {
Create : "Create",
Update : "Save Changes",
Delete : "Delete"
};
Global_Resources/default.fr.js
var res = {
Create : "créer",
Update : "Enregistrer les modifications",
Delete : "effacer"
};
The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.
UserManagementSystem/Local_Resources/default.js
res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";
UserManagementSystem/Local_Resources/default.fr.js
res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";
UserManagementSystem/Local_Resources/createUser.js
// Override res.Create on Global_Resources/default.js
res.Create = "Create User";
UserManagementSystem/Local_Resources/createUser.fr.js
// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";
manager.js file (this file should be load last)
res.lang = "fr";
var globalResourcePath = "Global_Resources";
var resourceFiles = [];
var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;
if(!IsFileExist(currentFile))
currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");
resourceFiles.push(currentFile);
// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";
if(!IsExist(currentFile))
currentFile = folder + "\\Local_Resource\\default.js";
if(!IsExist(currentFile)) throw new Exception("File Not Found");
resourceFiles.push(currentFile);
}
for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }
// Get current page name
var pageNameWithoutExtension = "SomePage";
currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;
if(!IsExist(currentFile))
currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");
Hope it helps :)
How to pass parameters to ThreadStart method in Thread?
You can encapsulate the thread function(download) and the needed parameter(s)(filename) in a class and use the ThreadStart delegate to execute the thread function.
public class Download
{
string _filename;
Download(string filename)
{
_filename = filename;
}
public void download(string filename)
{
//download code
}
}
Download = new Download(filename);
Thread thread = new Thread(new ThreadStart(Download.download);
Understanding dict.copy() - shallow or deep?
Adding to kennytm's answer. When you do a shallow copy parent.copy() a new dictionary is created with same keys,but the values are not copied they are referenced.If you add a new value to parent_copy it won't effect parent because parent_copy is a new dictionary not reference.
parent = {1: [1,2,3]}
parent_copy = parent.copy()
parent_reference = parent
print id(parent),id(parent_copy),id(parent_reference)
#140690938288400 140690938290536 140690938288400
print id(parent[1]),id(parent_copy[1]),id(parent_reference[1])
#140690938137128 140690938137128 140690938137128
parent_copy[1].append(4)
parent_copy[2] = ['new']
print parent, parent_copy, parent_reference
#{1: [1, 2, 3, 4]} {1: [1, 2, 3, 4], 2: ['new']} {1: [1, 2, 3, 4]}
The hash(id) value of parent[1], parent_copy[1] are identical which implies [1,2,3] of parent[1] and parent_copy[1] stored at id 140690938288400.
But hash of parent and parent_copy are different which implies
They are different dictionaries and parent_copy is a new dictionary having values reference to values of parent
Youtube iframe wmode issue
recently I saw that sometimes the flash player doesn't recognize &wmode=opaque
, istead you should pass &WMode=opaque
too (notice the uppercase).
What is the use of BindingResult interface in spring MVC?
Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.
Then, you can check this object looking for validation errors:
validator.validate(modelObject, bindingResult);
if (bindingResult.hasErrors()) {
// do something
}
plot is not defined
If you want to use a function form a package or module in python you have to import and reference them.
For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
Methods vs Constructors in Java
The Major difference is Given Below -
1: Constructor must have same name as the class name while this is not the case of methods
class Calendar{
int year = 0;
int month= 0;
//constructor
public Calendar(int year, int month){
this.year = year;
this.month = month;
System.out.println("Demo Constructor");
}
//Method
public void Display(){
System.out.println("Demo method");
}
}
2: Constructor initializes objects of a class whereas method does not. Methods performs operations on objects that already exist. In other words, to call a method we need an object of the class.
public class Program {
public static void main(String[] args) {
//constructor will be called on object creation
Calendar ins = new Calendar(25, 5);
//Methods will be called on object created
ins.Display();
}
}
3: Constructor does not have return type but a method must have a return type
class Calendar{
//constructor – no return type
public Calendar(int year, int month){
}
//Method have void return type
public void Display(){
System.out.println("Demo method");
}
}
Reimport a module in python while interactive
If you want to import a specific function or class from a module, you can do this:
import importlib
import sys
importlib.reload(sys.modules['my_module'])
from my_module import my_function
Google Maps setCenter()
For me above solutions didn't work then I tried
map.setCenter(new google.maps.LatLng(lat, lng));
and it worked as expected.
Overlapping elements in CSS
You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.
You have to set translate property in such way that both the <div>
overlap each other then You can use JavaScript to show and hide both the <div>
according to your requirements
Reading From A Text File - Batch
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
What is the difference between Hibernate and Spring Data JPA
There are 3 different things we are using here :
- JPA : Java persistence api which provide specification for persisting, reading, managing data from your java object to relations in database.
- Hibernate: There are various provider which implement jpa. Hibernate is one of them. So we have other provider as well. But if using jpa with spring it allows you to switch to different providers in future.
- Spring Data JPA : This is another layer on top of jpa which spring provide to make your life easy.
So lets understand how spring data jpa and spring + hibernate works-
Spring Data JPA:
Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.
Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.
How to check if a column exists in a datatable
Base on accepted answer, I made an extension method to check column exist in table as
I shared for whom concern.
public static class DatatableHelper
{
public static bool ContainColumn(this DataTable table, string columnName)
{
DataColumnCollection columns = table.Columns;
if (columns.Contains(columnName))
{
return true;
}
return false;
}
}
And use as dtTagData.ContainColumn("SystemName")
Why is Java Vector (and Stack) class considered obsolete or deprecated?
java.util.Stack
inherits the synchronization overhead of java.util.Vector
, which is usually not justified.
It inherits a lot more than that, though. The fact that java.util.Stack extends java.util.Vector
is a mistake in object-oriented design. Purists will note that it also offers a lot of methods beyond the operations traditionally associated with a stack (namely: push, pop, peek, size). It's also possible to do search
, elementAt
, setElementAt
, remove
, and many other random-access operations. It's basically up to the user to refrain from using the non-stack operations of Stack
.
For these performance and OOP design reasons, the JavaDoc for java.util.Stack
recommends ArrayDeque
as the natural replacement. (A deque is more than a stack, but at least it's restricted to manipulating the two ends, rather than offering random access to everything.)
Select Last Row in the Table
Another fancy way to do it in Laravel 6.x (Unsure but must work for 5.x aswell) :
DB::table('your_table')->get()->last();
You can access fields too :
DB::table('your_table')->get()->last()->id;
HttpContext.Current.Session is null when routing requests
Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:
<configuration>
...
<system.webServer>
...
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
...
</modules>
</system.webServer>
</configuration>
Simply adding it won't work since "Session" should have already been defined in the machine.config
.
Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...
Python - Convert a bytes array into JSON format
Python 3.5 + Use io module
import json
import io
my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'
fix_bytes_value = my_bytes_value.replace(b"'", b'"')
my_json = json.load(io.BytesIO(fix_bytes_value))
Non-static variable cannot be referenced from a static context
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
How can I get nth element from a list?
I'm not saying that there's anything wrong with your question or the answer given, but maybe you'd like to know about the wonderful tool that is Hoogle to save yourself time in the future: With Hoogle, you can search for standard library functions that match a given signature. So, not knowing anything about !!
, in your case you might search for "something that takes an Int
and a list of whatevers and returns a single such whatever", namely
Int -> [a] -> a
Lo and behold, with !!
as the first result (although the type signature actually has the two arguments in reverse compared to what we searched for). Neat, huh?
Also, if your code relies on indexing (instead of consuming from the front of the list), lists may in fact not be the proper data structure. For O(1) index-based access there are more efficient alternatives, such as arrays or vectors.
adb shell command to make Android package uninstall dialog appear
Use this command in cmd:
adb shell pm uninstall -k com.packagename
For example:
adb shell pm uninstall -k com.fedmich.pagexray
The -k
flag tells the package manager to keep the cache and data directories around, even though the app is removed. If you want a clean uninstall, don't specify -k
.
runOnUiThread in fragment
I used this for getting Date and Time in a fragment.
private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_head_screen, container, false);
dateTextView = root.findViewById(R.id.dateView);
hourTv = root.findViewById(R.id.hourView);
Thread thread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
//Calendario para obtener fecha & hora
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");
String currentDate = date_sdf.format(currentTime);
String currentHour = hour_sdf.format(currentTime);
dateTextView.setText(currentDate);
hourTv.setText(currentHour);
}
});
}
} catch (InterruptedException e) {
Log.v("InterruptedException", e.getMessage());
}
}
};
}
Resolve promises one after another (i.e. in sequence)?
Here is how I prefer to run tasks in series.
function runSerial() {
var that = this;
// task1 is a function that returns a promise (and immediately starts executing)
// task2 is a function that returns a promise (and immediately starts executing)
return Promise.resolve()
.then(function() {
return that.task1();
})
.then(function() {
return that.task2();
})
.then(function() {
console.log(" ---- done ----");
});
}
What about cases with more tasks? Like, 10?
function runSerial(tasks) {
var result = Promise.resolve();
tasks.forEach(task => {
result = result.then(() => task());
});
return result;
}
Getting time difference between two times in PHP
You can use strtotime() for time calculation. Here is an example:
$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';
$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);
echo '<hr>';
$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
echo '<hr>';
$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
Check the already-asked question - how to get time difference in minutes:
Subtract the past-most one from the future-most one and divide by 60.
Times are done in unix format so they're just a big number showing the
number of seconds from January 1 1970 00:00:00 GMT
Ruby: Can I write multi-line string with no concatenation?
The Ruby-way (TM) since Ruby 2.3: Use the squiggly HEREDOC <<~
to define a multi-line string with newlines and proper indentation:
conn.exec <<~EOS
select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc
where etc etc etc etc etc etc etc etc etc etc etc etc etc
EOS
# -> "select...\nfrom...\nwhere..."
If proper indentation is not a concern, then single and double quotes can span multiple lines in Ruby:
conn.exec "select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc"
# -> "select...\n from...\n where..."
If single or double quotes are cumbersome because that would need lots of escaping, then the percent string literal notation %
is the most flexible solution:
conn.exec %(select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc
where (ProductLine = 'R' OR ProductLine = "S") AND Country = "...")
# -> "select...\n from...\n where..."
If the aim is to avoid the newlines (which both the squiggly HEREDOC, quotes and the percent string literal will cause), then a line continuation can be used by putting a backslash \
as the last non-whitespace character in a line. This will continue the line and will cause Ruby to concatenate the Strings back to back (watch out for those spaces inside the quoted string):
conn.exec 'select attr1, attr2, attr3, attr4, attr5, attr6, attr7 ' \
'from table1, table2, table3, etc, etc, etc, etc, etc, ' \
'where etc etc etc etc etc etc etc etc etc etc etc etc etc'
# -> "select...from...where..."
If you use Rails, then String.squish
will strip the string of leading and trailing space and collapse all consecutive whitespaces (newlines, tabs, and all) into a single space:
conn.exec "select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc".squish
# -> "select...attr7 from...etc, where..."
More details:
Ruby HEREDOC Syntax
The Here Document Notation for Strings is a way to designate long blocks of text inline in code. It is started by <<
followed by a user-defined String (the End of String terminator). All following lines are concatenated until the End of String terminator is found at the very beginning of a line:
puts <<HEREDOC
Text Text Text Text
Bla Bla
HEREDOC
# -> "Text Text Text Text\nBlaBla"
The End of String terminator can be chosen freely, but it is common to use something like "EOS" (End of String) or something that matches the domain of the String such as "SQL".
HEREDOC supports interpolation by default or when the EOS terminator is double quoted:
price = 10
print <<"EOS" # comments can be put here
1.) The price is #{price}.
EOS
# -> "1.) The price is 10."
Interpolation can be disabled if the EOS terminator is single quoted:
print <<'EOS' # Disabled interpolation
3.) The price is #{price}.
EOS
# -> "3.) The price is #{price}."
One important restriction of the <<HEREDOC
is that the End of String terminator needs to be at the beginning of the line:
puts <<EOS
def foo
print "foo"
end
EOS
EOS
#-> "....def foo\n......print "foo"\n....end\n..EOS"
To get around this, the <<-
syntax was created. It allows the EOS terminator to be indented to make the code look nicer. The lines between the <<-
and EOS terminator are still used in their full extend including all indentation:
def printExample
puts <<-EOS # Use <<- to indent End of String terminator
def foo
print "foo"
end
EOS
end
# -> "....def foo\n......print "foo"\n....end"
Since Ruby 2.3, we now have the squiggly HEREDOC <<~
removes leading whitespace:
puts <<~EOS # Use the squiggly HEREDOC <<~ to remove leading whitespace (since Ruby 2.3!)
def foo
print "foo"
end
EOS
# -> "def foo\n..print "foo"\nend"
Empty lines and lines which only contains tabs and space are ignored by <<~
puts <<~EOS.inspect
Hello
World!
EOS
#-> "Hello\n..World!"
If both tabs and spaces are used, tabs are considered as equal to 8 spaces.
If the least-indented line is in the middle of a tab, this tab is not removed.
puts <<~EOS.inspect
<tab>One Tab
<space><space>Two Spaces
EOS
# -> "\tOne Tab\nTwoSpaces"
HEREDOC can do some crazy stuff such as executing commands using backticks:
puts <<`EOC`
echo #{price}
echo #{price * 2}
EOC
HEREDOC String definitions can be "stacked", which means that the first EOS terminator (EOSFOO below) will end the first string and start the second (EOSBAR below):
print <<EOSFOO, <<EOSBAR # you can stack them
I said foo.
EOSFOO
I said bar.
EOSBAR
I don't think anybody would ever use it as such, but the <<EOS
is really just a string literal and can be put whereever a string can normally be put:
def func(a,b,c)
puts a
puts b
puts c
end
func(<<THIS, 23, <<THAT)
Here's a line
or two.
THIS
and here's another.
THAT
If you don't have Ruby 2.3, but Rails >=
3.0 then you can use String.strip_heredoc
which does the same as <<~
# File activesupport/lib/active_support/core_ext/string/strip.rb, line 22
class String
def strip_heredoc
gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "".freeze)
end
end
puts <<-USAGE.strip_heredoc # If no Ruby 2.3, but Rails >= 3.0
This command does such and such.
Supported options are:
-h This message
...
USAGE
Troubleshooting
If you see errors when Ruby parses your file, then it is most likely that you either have extra leading or trailing spaces with a HEREDOC or extra trailing spaces with a squiggly HEREDOC. For example:
What you see:
database_yml = <<~EOS
production:
database: #{fetch(:user)}
adapter: postgresql
pool: 5
timeout: 5000
EOS
What Ruby tells you:
SyntaxError: .../sample.rb:xx: can't find string "EOS" anywhere before EOF
...sample.rb:xx: syntax error, unexpected end-of-input, expecting `end'
What is at fault:
Spot the extra spaces after the terminating EOS.
Percent String Literals
See RubyDoc for how to use the percentage sign followed by a string in a parentheses pair such as a %(...)
, %[...]
, %{...}
, etc. or a pair of any non-alphanumeric character such as %+...+
Last Words
Last, to get the answer to the original question "Is there a way to imply concatenation?"
answered: Ruby always implies concatenation if two strings (single and double quoted) are found back to back:
puts "select..." 'from table...' "where..."
# -> "select...from table...where..."
The caveat is that this does not work across line-breaks, because Ruby is interpreting an end of statement and the consequitive line of just strings alone on a line doesn't do anything.
Easiest way to convert a List to a Set in Java
Java- addAll
set.addAll(aList);
Java- new Object
new HashSet(list)
Java-8
list.stream().collect(Collectors.toSet());
Using Guva
Sets.newHashSet(list)
Apache Commons
CollectionUtils.addAll(targetSet, sourceList);
Java 10
var set = Set.copyOf(list);
jQuery lose focus event
blur event: when the element loses focus.
focusout event: when the element, or any element inside of it, loses focus.
As there is nothing inside the filter element, both blur and focusout will work in this case.
$(function() {
$('#filter').blur(function() {
$('#options').hide();
});
})
jsfiddle with blur: http://jsfiddle.net/yznhb8pc/
$(function() {
$('#filter').focusout(function() {
$('#options').hide();
});
})
jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/
Check if string is upper, lower, or mixed case in Python
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
idiomatic-python
pySerial write() won't take my string
I had the same "TypeError: an integer is required" error message when attempting to write.
Thanks, the .encode() solved it for me.
I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.
I'm omitting the com port settings here:
>>>import serial
>>>ser = serial.Serial(5)
>>>ser.close()
>>>ser.open()
>>>ser.write("1".encode())
1
>>>
Parse usable Street Address, City, State, Zip from a string
There are data services that given a zip code will give you list of street names in that zip code.
Use a regex to extract Zip or City State - find the correct one or if a error get both.
pull the list of streets from a data source Correct the city and state, and then street address. Once you get a valid Address line 1, city, state, and zip you can then make assumptions on address line 2..3
Java: How to convert String[] to List or Set
Collections.addAll provides the shortest (one-line) receipt
Having
String[] array = {"foo", "bar", "baz"};
Set<String> set = new HashSet<>();
You can do as below
Collections.addAll(set, array);
Oracle: SQL query that returns rows with only numeric values
If you use Oracle 10 or higher you can use regexp functions as codaddict suggested. In earlier versions translate
function will help you:
select * from tablename where translate(x, '.1234567890', '.') is null;
More info about Oracle translate function can be found here or in official documentation "SQL Reference"
UPD: If you have signs or spaces in your numbers you can add "+-
" characters to the second parameter of translate
function.
Dictionary text file
What about /usr/share/dict/words
on any Unix system? How many words are we talking about? Like OED-Unabridged?
compare differences between two tables in mysql
Based on Haim's answer I created a PHP code to test and display all the differences between two databases.
This will also display if a table is present in source or test databases.
You have to change with your details the <> variables content.
<?php
$User = "<DatabaseUser>";
$Pass = "<DatabasePassword>";
$SourceDB = "<SourceDatabase>";
$TestDB = "<DatabaseToTest>";
$link = new mysqli( "p:". "localhost", $User, $Pass, "" );
if ( mysqli_connect_error() ) {
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
mysqli_set_charset( $link, "utf8" );
mb_language( "uni" );
mb_internal_encoding( "UTF-8" );
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';
$SourceDB_Content = query( $link, $sQuery );
if ( !is_array( $SourceDB_Content) ) {
echo "Table $SourceDB cannot be accessed";
exit(0);
}
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';
$TestDB_Content = query( $link, $sQuery );
if ( !is_array( $TestDB_Content) ) {
echo "Table $TestDB cannot be accessed";
exit(0);
}
$SourceDB_Tables = array();
foreach( $SourceDB_Content as $item ) {
$SourceDB_Tables[] = $item["TABLE_NAME"];
}
$TestDB_Tables = array();
foreach( $TestDB_Content as $item ) {
$TestDB_Tables[] = $item["TABLE_NAME"];
}
//var_dump( $SourceDB_Tables, $TestDB_Tables );
$LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
$NoOfDiscrepancies = 0;
echo "
<table border='1' width='100%'>
<tr>
<td>Table</td>
<td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
<td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
<td>Test result</td>
<tr>
";
foreach( $LookupTables as $table ) {
$FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
$FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
echo "
<tr>
<td>$table</td>
<td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td>
<td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>
<td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>
</tr>
";
}
echo "
</table>
<br><br>
No of discrepancies found: $NoOfDiscrepancies
";
function query( $link, $q ) {
$result = mysqli_query( $link, $q );
$errors = mysqli_error($link);
if ( $errors > "" ) {
echo $errors;
exit(0);
}
if( $result == false ) return false;
else if ( $result === true ) return true;
else {
$rset = array();
while ( $row = mysqli_fetch_assoc( $result ) ) {
$rset[] = $row;
}
return $rset;
}
}
function compareTables( $source, $test, $table ) {
global $link;
global $NoOfDiscrepancies;
$sQuery = "
SELECT column_name,ordinal_position,data_type,column_type FROM
(
SELECT
column_name,ordinal_position,
data_type,column_type,COUNT(1) rowcount
FROM information_schema.columns
WHERE
(
(table_schema='$source' AND table_name='$table') OR
(table_schema='$test' AND table_name='$table')
)
AND table_name IN ('$table')
GROUP BY
column_name,ordinal_position,
data_type,column_type
HAVING COUNT(1)=1
) A;
";
$result = query( $link, $sQuery );
$data = "";
if( is_array( $result ) && count( $result ) > 0 ) {
$NoOfDiscrepancies++;
$data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";
foreach( $result as $item ) {
$data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";
}
$data .= "</table>";
return $data;
}
else {
return "Checked but no discrepancies found!";
}
}
?>
Incrementing a variable inside a Bash loop
Incrementing a variable can be done like that:
_my_counter=$[$_my_counter + 1]
Counting the number of occurrence of a pattern in a column can be done with grep
grep -cE "^([^ ]* ){2}US"
-c
count
([^ ]* )
To detect a colonne
{2}
the colonne number
US
your pattern
disable a hyperlink using jQuery
Append a class containing pointer-events:non
.active a{ //css
text-decoration: underline;
background-color: #fff;
pointer-events: none;}
$(this).addClass('active');
Insert Multiple Rows Into Temp Table With SQL Server 2012
When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:
SQL Fiddle
MS SQL Server 2012 Schema Setup:
Query 1:
CREATE TABLE #Names
(
Name1 VARCHAR(100),
Name2 VARCHAR(100)
)
INSERT INTO #Names
(Name1, Name2)
VALUES
('Matt', 'Matthew'),
('Matt', 'Marshal'),
('Matt', 'Mattison')
SELECT * FROM #NAMES
Results:
| NAME1 | NAME2 |
--------------------
| Matt | Matthew |
| Matt | Marshal |
| Matt | Mattison |
Here a SSMS 2012 screenshot:
Convert from DateTime to INT
Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:
(DT_I8)FLOOR((DT_R8)systemDateTime)
But you'd have to test to doublecheck.
PHP form - on submit stay on same page
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action
to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
Create folder in Android
If you are trying to make more than just one folder on the root of the sdcard,
ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"
then instead of folder.mkdir()
you would use folder.mkdirs()
I've made this mistake in the past & I took forever to figure it out.
What are the various "Build action" settings in Visual Studio project properties and what do they do?
How about this page from Microsoft Connect (explaining the DesignData and DesignDataWithDesignTimeCreatableTypes) types. Quoting:
The following describes the two Build Actions for Sample Data files.
Sample data .xaml files must be assigned one of the below Build Actions:
DesignData: Sample data types will be created as faux types. Use this Build Action when the sample data types are not creatable or have read-only properties that you want to defined sample data values for.
DesignDataWithDesignTimeCreatableTypes: Sample data types will be created using the types defined in the sample data file. Use this Build Action when the sample data types are creatable using their default empty constructor.
Not so incredibly exhaustive, but it at least gives a hint. This MSDN walkthrough also gives some ideas. I don't know whether these Build Actions are applicable for non-Silverlight projects also.
How to Install pip for python 3.7 on Ubuntu 18?
To install all currently supported python versions (python 3.6 is already pre-installed) including pip for Ubuntu 18.04 do the following:
To install python3.5 and python3.7, use the deadsnakes ppa:
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.5
sudo apt-get install python3.7
Install python2.7 via distribution packages:
sudo apt install python-minimal # on Ubuntu 18.04 python-minimal maps to python2.7
To install pip use:
sudo apt install python-pip # on Ubuntu 18.04 this refers to pip for python2.7
sudo apt install python3-pip # on Ubuntu 18.04 this refers to pip for python3.6
python3.5 -m pip install pip # this will install pip only for the current user
python3.7 -m pip install pip
I used it for setting up a CI-chain for a python project with tox and Jenkins.
VBA Macro to compare all cells of two Excel files
A very simple check you can do with Cell formulas:
Sheet 1 (new - old)
=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")
Sheet 2 (old - new)
=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")
This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)
You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2.
Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".
Doe the same for Sheet two.
Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.
But two cases are not covered here:
- In the compared cell of New and Old is the same data (Resulting Cell will be empty)
- In the compared cell of New and Old is diffe data (Resulting Cell will be empty)
To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com
What is the difference between npm install and npm run build?
NPM in 2019
npm build
no longer exists. You must call npm run build
now. More info below.
TLDR;
npm install
: installs dependencies, then calls the install
from the package.json
scripts
field.
npm run build
: runs the build field from the package.json
scripts
field.
NPM Scripts Field
https://docs.npmjs.com/misc/scripts
There are many things you can put into the npm package.json
scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.
To Complicate Things
npm install
is not the same as npm run install
npm install
installs package.json
dependencies, then runs the package.json
scripts.install
- (Essentially calls
npm run install
after dependencies are installed.
npm run install
only runs the package.json
scripts.install
, it will not install dependencies.
npm build
used to be a valid command (used to be the same as npm run build
) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build?
You can read more on the documentation: https://docs.npmjs.com/cli/build
Extra Notes
There are still two top level commands that will run scripts, they are:
npm start
which is the same as npm run start
npm test
==> npm run test
Using OR & AND in COUNTIFS
There is probably a more efficient solution to your question, but following formula should do the trick:
=SUM(COUNTIFS(J1:J196,"agree",A1:A196,"yes"),COUNTIFS(J1:J196,"agree",A1:A196,"no"))
Singleton: How should it be used
I find them useful when I have a class that encapsulates a lot of memory. For example in a recent game I've been working on I have an influence map class that contains a collection of very large arrays of contiguous memory. I want that all allocated at startup, all freed at shutdown and I definitely want only one copy of it. I also have to access it from many places. I find the singleton pattern to be very useful in this case.
I'm sure there are other solutions but I find this one very useful and easy to implement.
Inserting into Oracle and retrieving the generated sequence ID
Expanding a bit on the answers from @Guru and @Ronnis, you can hide the sequence and make it look more like an auto-increment using a trigger, and have a procedure that does the insert for you and returns the generated ID as an out parameter.
create table batch(batchid number,
batchname varchar2(30),
batchtype char(1),
source char(1),
intarea number)
/
create sequence batch_seq start with 1
/
create trigger batch_bi
before insert on batch
for each row
begin
select batch_seq.nextval into :new.batchid from dual;
end;
/
create procedure insert_batch(v_batchname batch.batchname%TYPE,
v_batchtype batch.batchtype%TYPE,
v_source batch.source%TYPE,
v_intarea batch.intarea%TYPE,
v_batchid out batch.batchid%TYPE)
as
begin
insert into batch(batchname, batchtype, source, intarea)
values(v_batchname, v_batchtype, v_source, v_intarea)
returning batchid into v_batchid;
end;
/
You can then call the procedure instead of doing a plain insert, e.g. from an anoymous block:
declare
l_batchid batch.batchid%TYPE;
begin
insert_batch(v_batchname => 'Batch 1',
v_batchtype => 'A',
v_source => 'Z',
v_intarea => 1,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
insert_batch(v_batchname => 'Batch 99',
v_batchtype => 'B',
v_source => 'Y',
v_intarea => 9,
v_batchid => l_batchid);
dbms_output.put_line('Generated id: ' || l_batchid);
end;
/
Generated id: 1
Generated id: 2
You can make the call without an explicit anonymous block, e.g. from SQL*Plus:
variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);
... and use the bind variable :l_batchid
to refer to the generated value afterwards:
print l_batchid;
insert into some_table values(:l_batch_id, ...);
127 Return code from $?
A shell convention is that a successful executable should exit with the value 0. Anything else can be interpreted as a failure of some sort, on part of bash or the executable you that just ran. See also $PIPESTATUS and the EXIT STATUS section of the bash man page:
For the shell’s purposes, a command which exits with a zero exit status has succeeded. An exit status
of zero indicates success. A non-zero exit status indicates failure. When a command terminates on a
fatal signal N, bash uses the value of 128+N as the exit status.
If a command is not found, the child process created to execute it returns a status of 127. If a com-
mand is found but is not executable, the return status is 126.
If a command fails because of an error during expansion or redirection, the exit status is greater than
zero.
Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error
occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage.
Bash itself returns the exit status of the last command executed, unless a syntax error occurs, in
which case it exits with a non-zero value. See also the exit builtin command below.
cat, grep and cut - translated to python
you need to use os.system
module to execute shell command
import os
os.system('command')
if you want to save the output for later use, you need to use subprocess
module
import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
Convert .pfx to .cer
the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.
Is there a rule-of-thumb for how to divide a dataset into training and validation sets?
There are two competing concerns: with less training data, your parameter estimates have greater variance. With less testing data, your performance statistic will have greater variance. Broadly speaking you should be concerned with dividing data such that neither variance is too high, which is more to do with the absolute number of instances in each category rather than the percentage.
If you have a total of 100 instances, you're probably stuck with cross validation as no single split is going to give you satisfactory variance in your estimates. If you have 100,000 instances, it doesn't really matter whether you choose an 80:20 split or a 90:10 split (indeed you may choose to use less training data if your method is particularly computationally intensive).
Assuming you have enough data to do proper held-out test data (rather than cross-validation), the following is an instructive way to get a handle on variances:
- Split your data into training and testing (80/20 is indeed a good starting point)
- Split the training data into training and validation (again, 80/20 is a fair split).
- Subsample random selections of your training data, train the classifier with this, and record the performance on the validation set
- Try a series of runs with different amounts of training data: randomly sample 20% of it, say, 10 times and observe performance on the validation data, then do the same with 40%, 60%, 80%. You should see both greater performance with more data, but also lower variance across the different random samples
- To get a handle on variance due to the size of test data, perform the same procedure in reverse. Train on all of your training data, then randomly sample a percentage of your validation data a number of times, and observe performance. You should now find that the mean performance on small samples of your validation data is roughly the same as the performance on all the validation data, but the variance is much higher with smaller numbers of test samples
Set order of columns in pandas dataframe
You could also do something like df = df[['x', 'y', 'a', 'b']]
import pandas as pd
frame = pd.DataFrame({'one thing':[1,2,3,4],'second thing':[0.1,0.2,1,2],'other thing':['a','e','i','o']})
frame = frame[['second thing', 'other thing', 'one thing']]
print frame
second thing other thing one thing
0 0.1 a 1
1 0.2 e 2
2 1.0 i 3
3 2.0 o 4
Also, you can get the list of columns with:
cols = list(df.columns.values)
The output will produce something like this:
['x', 'y', 'a', 'b']
Which is then easy to rearrange manually.
"Repository does not have a release file" error
In my case the cause was Ubuntu version no longer supported by Canonical.
I was able to upgrade to still supported LTS with 2 steps:
1) Manually update repo links from "in.ubuntu" to "old-releases.ubuntu".
1.1) Installed all outstanding updates
2) do-release-upgrade
was able to take from this point and do actual upgrade
IMHO, this is safer method then just updating repositories to next supported ubuntu, since do-release-upgrade
have chance to prevent upgrade that could fail, and may be able to diagnose a problem for you.
Get month name from number
This Is What I Would Do:
from datetime import *
months = ["Unknown",
"January",
"Febuary",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
now = (datetime.now())
year = (now.year)
month = (months[now.month])
print(month)
It Outputs:
>>> September
(This Was The Real Date When I Wrote This)
Create component to specific module with Angular-CLI
1.- Create your feature module as usual.
ng generate module dirlevel1/module-name
2.- You can specify the ROOT PATH of your project in --module ( only in --module, (/) root points to your PROJECT ROOT and IS NOT THE SYSTEM ROOT!!!)
ng generate component dirlevel1/component-name --module /src/app/dirlevel1/module-name.module.ts
Real Example:
ng generate module stripe/payment-methods-list
ng generate component stripe/payment-methods-list --module=/src/app/stripe/payment-methods-list/payment-methods-list.module.ts
Output:
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.scss (0 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.html (39 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.spec.ts (768 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.ts (322 bytes)
UPDATE src/app/stripe/payment-methods-list/payment-methods-list.module.ts (311 bytes)
[OK] Generated component!
Tested with Angular CLI: 9.1.4
POST unchecked HTML checkboxes
function SubmitCheckBox(obj) {
obj.value = obj.checked ? "on" : "off";
obj.checked = true;
return obj.form.submit();
}
<input type=checkbox name="foo" onChange="return SubmitCheckBox(this);">
How to select a radio button by default?
XHTML solution:
<input type="radio" name="imgsel" value="" checked="checked" />
Please note, that the actual value of checked
attribute does not actually matter; it's just a convention to assign "checked"
. Most importantly, strings like "true"
or "false"
don't have any special meaning.
If you don't aim for XHTML conformance, you can simplify the code to:
<input type="radio" name="imgsel" value="" checked>
How to iterate through SparseArray?
The answer is no because SparseArray
doesn't provide it. As pst
put it, this thing doesn't provide any interfaces.
You could loop from 0 - size()
and skip values that return null
, but that is about it.
As I state in my comment, if you need to iterate use a Map
instead of a SparseArray
. For example, use a TreeMap
which iterates in order by the key.
TreeMap<Integer, MyType>
How can I list the scheduled jobs running in my database?
The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.
The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.
The privileges you need are defined in the Admin Guide. Find out more.
So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.
How to programmatically add controls to a form in VB.NET
Dim numberOfButtons As Integer
Dim buttons() as Button
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Redim buttons(numberOfbuttons)
for counter as integer = 0 to numberOfbuttons
With buttons(counter)
.Size = (10, 10)
.Visible = False
.Location = (55, 33 + counter*13)
.Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
'any other property
End With
'
next
End Sub
If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.
If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:
AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked
then create
Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub
when you call: objectYouCall.numberOfButtons = initial_value_from_main_program
response_yes_or_no_or_other = objectYouCall.ShowDialog()
For radio buttons, textboxes, same story, different ending.
Change arrow colors in Bootstraps carousel
I too had a similar problem, some images were very light and some dark, so the arrows didn't always show up clearly so I took a more simplistic approach.
In the modal-body section I just removed the following lines:
<!-- Left and right controls -->
<a class="carousel-control-prev" href="#id" data-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#id" data-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
and inserted the following into the modal-header section
<!-- Left and right controls -->
<a href="#gamespandp" data-slide="prev" class="btn btn-outline-secondary btn-sm">❮</a>
<a href="#gamespandp" data-slide="next" class="btn btn-outline-secondary btn-sm">❯</a>
The indicators can now be clearly seen, no adding extra icons or messing with style sheets, although you could style them however you wanted!
See this demo image:
[
Get all child elements
Here is a code to get the child elements (In java):
String childTag = childElement.getTagName();
if(childTag.equals("html"))
{
return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath(".."));
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++)
{
WebElement childrenElement = childrenElements.get(i);
String childrenElementTag = childrenElement.getTagName();
if(childTag.equals(childrenElementTag))
{
count++;
}
}
How to refer to Excel objects in Access VBA?
Inside a module
Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook
sub Initialize()
set objExcelApp = new Excel.Application
end sub
sub ProcessDataWorkbook()
dim ws as Worksheet
set wb = objExcelApp.Workbooks.Open("path to my workbook")
set ws = wb.Sheets(1)
ws.Cells(1,1).Value = "Hello"
ws.Cells(1,2).Value = "World"
'Close the workbook
wb.Close
set wb = Nothing
end sub
sub Release()
set objExcelApp = Nothing
end sub
angular 2 sort and filter
A pipe takes in data as input and transforms it to a desired output.
Add this pipe file:orderby.ts
inside your /app
folder .
orderby.ts
//The pipe class implements the PipeTransform interface's transform method that accepts an input value and an optional array of parameters and returns the transformed value.
import { Pipe,PipeTransform } from "angular2/core";
//We tell Angular that this is a pipe by applying the @Pipe decorator which we import from the core Angular library.
@Pipe({
//The @Pipe decorator takes an object with a name property whose value is the pipe name that we'll use within a template expression. It must be a valid JavaScript identifier. Our pipe's name is orderby.
name: "orderby"
})
export class OrderByPipe implements PipeTransform {
transform(array:Array<any>, args?) {
// Check if array exists, in this case array contains articles and args is an array that has 1 element : !id
if(array) {
// get the first element
let orderByValue = args[0]
let byVal = 1
// check if exclamation point
if(orderByValue.charAt(0) == "!") {
// reverse the array
byVal = -1
orderByValue = orderByValue.substring(1)
}
console.log("byVal",byVal);
console.log("orderByValue",orderByValue);
array.sort((a: any, b: any) => {
if(a[orderByValue] < b[orderByValue]) {
return -1*byVal;
} else if (a[orderByValue] > b[orderByValue]) {
return 1*byVal;
} else {
return 0;
}
});
return array;
}
//
}
}
In your component file (app.component.ts) import the pipe that you just added using: import {OrderByPipe} from './orderby';
Then, add *ngFor="#article of articles | orderby:'id'"
inside your template if you want to sort your articles by id in ascending order or orderby:'!id'"
in descending order.
We add parameters to a pipe by following the pipe name with a colon ( : ) and then the parameter value
We must list our pipe in the pipes array of the @Component decorator. pipes: [ OrderByPipe ]
.
app.component.ts
import {Component, OnInit} from 'angular2/core';
import {OrderByPipe} from './orderby';
@Component({
selector: 'my-app',
template: `
<h2>orderby-pipe by N2B</h2>
<p *ngFor="#article of articles | orderby:'id'">
Article title : {{article.title}}
</p>
`,
pipes: [ OrderByPipe ]
})
export class AppComponent{
articles:Array<any>
ngOnInit(){
this.articles = [
{
id: 1,
title: "title1"
},{
id: 2,
title: "title2",
}]
}
}
More info here on my github and this post on my website
When to use throws in a Java method declaration?
The code that you looked at is not ideal. You should either:
Catch the exception and handle it;
in which case the throws
is
unnecesary.
Remove the try/catch
; in which case
the Exception will be handled by a
calling method.
Catch the exception, possibly
perform some action and then rethrow
the exception (not just the message)
Formatting text in a TextBlock
a good site, with good explanations:
http://www.wpf-tutorial.com/basic-controls/the-textblock-control-inline-formatting/
here the author gives you good examples for what you are looking for! Overal the site is great for research material plus it covers a great deal of options you have in WPF
Edit
There are different methods to format the text. for a basic formatting (the easiest in my opinion):
<TextBlock Margin="10" TextWrapping="Wrap">
TextBlock with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> text.
</TextBlock>
Example 1 shows basic formatting with Bold Itallic and underscored text.
Following includes the SPAN method, with this you van highlight text:
<TextBlock Margin="10" TextWrapping="Wrap">
This <Span FontWeight="Bold">is</Span> a
<Span Background="Silver" Foreground="Maroon">TextBlock</Span>
with <Span TextDecorations="Underline">several</Span>
<Span FontStyle="Italic">Span</Span> elements,
<Span Foreground="Blue">
using a <Bold>variety</Bold> of <Italic>styles</Italic>
</Span>.
</TextBlock>
Example 2 shows the span function and the different possibilities with it.
For a detailed explanation check the site!
Examples
Import file size limit in PHPMyAdmin
I found that increasing the upload and post limit in php.ini did not affect the limit in phpmyadmin. This is because my server has a separate setting for cpanel upload limit. If you have access to WHM, you probably have this.
To adjust:
- login to your WHM panel: this is usually located at {your server ip}/whm and you will need your root login details here. If you don't have those, request them from your host.
- once logged in, in the top left search bar, search for "tweak settings"
- On the tweak setting pages, search for "cPanel PHP max upload size"
- Adjust the number and save
No need to restart apache or anything, changes are instant. This process increased the value of max upload file size in phpmyadmin. You can check this by going to phpmyadmin and selecting your database, then clicking "import" at the top. Beside the file selector you will see the upload limit. My server default was 100.
How generate unique Integers based on GUIDs
Because the GUID space is larger than the number of 32-bit integers, you're guaranteed to have collisions if you have enough GUIDs. Given that you understand that and are prepared to deal with collisions, however rare, GetHashCode() is designed for exactly this purpose and should be preferred.
apply drop shadow to border-top only?
Something like this?
_x000D_
_x000D_
div {_x000D_
border: 1px solid #202020;_x000D_
margin-top: 25px;_x000D_
margin-left: 25px;_x000D_
width: 158px;_x000D_
height: 158px;_x000D_
padding-top: 25px;_x000D_
-webkit-box-shadow: 0px -4px 3px rgba(50, 50, 50, 0.75);_x000D_
-moz-box-shadow: 0px -4px 3px rgba(50, 50, 50, 0.75);_x000D_
box-shadow: 0px -4px 3px rgba(50, 50, 50, 0.75);_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_
Pandas: rolling mean by time interval
In the meantime, a time-window capability was added. See this link.
In [1]: df = DataFrame({'B': range(5)})
In [2]: df.index = [Timestamp('20130101 09:00:00'),
...: Timestamp('20130101 09:00:02'),
...: Timestamp('20130101 09:00:03'),
...: Timestamp('20130101 09:00:05'),
...: Timestamp('20130101 09:00:06')]
In [3]: df
Out[3]:
B
2013-01-01 09:00:00 0
2013-01-01 09:00:02 1
2013-01-01 09:00:03 2
2013-01-01 09:00:05 3
2013-01-01 09:00:06 4
In [4]: df.rolling(2, min_periods=1).sum()
Out[4]:
B
2013-01-01 09:00:00 0.0
2013-01-01 09:00:02 1.0
2013-01-01 09:00:03 3.0
2013-01-01 09:00:05 5.0
2013-01-01 09:00:06 7.0
In [5]: df.rolling('2s', min_periods=1).sum()
Out[5]:
B
2013-01-01 09:00:00 0.0
2013-01-01 09:00:02 1.0
2013-01-01 09:00:03 3.0
2013-01-01 09:00:05 3.0
2013-01-01 09:00:06 7.0
How do I profile memory usage in Python?
maybe it help:
<see additional>
pip install gprof2dot
sudo apt-get install graphviz
gprof2dot -f pstats profile_for_func1_001 | dot -Tpng -o profile.png
def profileit(name):
"""
@profileit("profile_for_func1_001")
"""
def inner(func):
def wrapper(*args, **kwargs):
prof = cProfile.Profile()
retval = prof.runcall(func, *args, **kwargs)
# Note use of name from outer scope
prof.dump_stats(name)
return retval
return wrapper
return inner
@profileit("profile_for_func1_001")
def func1(...)
Get user profile picture by Id
Here, this api allows you to get fb, google and twitter profile pics easily
https://www.avatars.io/
It's an API that returns the profile image when given a username for a variety of social networks including Twitter, Facebook, Instagram, and gravatar. It has libraries for iOS, Android, Ruby, Node, PHP, Python, and JavaScript.
Get position/offset of element relative to a parent container?
Sure is easy with pure JS, just do this, work for fixed and animated HTML 5 panels too, i made and try this code and it works for any brower (include IE 8):
<script type="text/javascript">
function fGetCSSProperty(s, e) {
try { return s.currentStyle ? s.currentStyle[e] : window.getComputedStyle(s)[e]; }
catch (x) { return null; }
}
function fGetOffSetParent(s) {
var a = s.offsetParent || document.body;
while (a && a.tagName && a != document.body && fGetCSSProperty(a, 'position') == 'static')
a = a.offsetParent;
return a;
}
function GetPosition(s) {
var b = fGetOffSetParent(s);
return { Left: (b.offsetLeft + s.offsetLeft), Top: (b.offsetTop + s.offsetTop) };
}
</script>
How to install python3 version of package via pip on Ubuntu?
Another way to install python3 is using wget. Below are the steps for installation.
wget http://www.python.org/ftp/python/3.3.5/Python-3.3.5.tar.xz
tar xJf ./Python-3.3.5.tar.xz
cd ./Python-3.3.5
./configure --prefix=/opt/python3.3
make && sudo make install
Also,one can create an alias for the same using
echo 'alias py="/opt/python3.3/bin/python3.3"' >> ~/.bashrc
Now open a new terminal and type py and press Enter.
Removing duplicate characters from a string
If order is important,
seen = set()
result = []
for c in foo:
if c not in seen:
result.append(c)
seen.add(c)
result = ''.join(result)
Or to do it without sets:
result = []
for c in foo:
if c not in result:
result.append(c)
result = ''.join(result)
Builder Pattern in Effective Java
Make the builder a static
class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.
public class NutritionFacts {
public static class Builder {
}
}
Reference: Nested classes
Android Respond To URL in Intent
You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/
vs https/
, www.
vs no www.
, etc).
For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms
)
Note that path prefix is optional.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="www.docs.google.com" />
<data android:host="docs.google.com" />
<data android:pathPrefix="/forms" />
</intent-filter>
jQuery checkbox check/uncheck
$('mainCheckBox').click(function(){
if($(this).prop('checked')){
$('Id or Class of checkbox').prop('checked', true);
}else{
$('Id or Class of checkbox').prop('checked', false);
}
});
Where does Chrome store cookies?
On Windows the path is:
C:\Users\<current_user>\AppData\Local\Google\Chrome\User Data\<Profile 1>\Cookies(Type:File)
Chrome doesn't store each cookies in separate text file. It stores all of the cookies together in a single file in the profile folder. That file is not readable.
How to multiply a BigDecimal by an integer in Java
You have a lot of type-mismatches in your code such as trying to put an int
value where BigDecimal
is required. The corrected version of your code:
public class Payment
{
BigDecimal itemCost = BigDecimal.ZERO;
BigDecimal totalCost = BigDecimal.ZERO;
public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
{
itemCost = itemPrice.multiply(new BigDecimal(itemQuantity));
totalCost = totalCost.add(itemCost);
return totalCost;
}
}
Java - checking if parseInt throws exception
It would be something like this.
String text = textArea.getText();
Scanner reader = new Scanner(text).useDelimiter("\n");
while(reader.hasNext())
String line = reader.next();
try{
Integer.parseInt(line);
//it worked
}
catch(NumberFormatException e){
//it failed
}
}
Perform curl request in javascript?
You can use JavaScripts Fetch API (available in your browser) to make network requests.
If using node, you will need to install the node-fetch package.
const url = "https://api.wit.ai/message?v=20140826&q=";
const options = {
headers: {
Authorization: "Bearer 6Q************"
}
};
fetch(url, options)
.then( res => res.json() )
.then( data => console.log(data) );
How can I set a UITableView to grouped style
If i understand what you mean, you have to initialize your controller with that style. Something like:
myTVContoller = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
How to recursively list all the files in a directory in C#?
Some improved version with max lvl to go down in directory and option to exclude folders:
using System;
using System.IO;
class MainClass {
public static void Main (string[] args) {
var dir = @"C:\directory\to\print";
PrintDirectoryTree(dir, 2, new string[] {"folder3"});
}
public static void PrintDirectoryTree(string directory, int lvl, string[] excludedFolders = null, string lvlSeperator = "")
{
excludedFolders = excludedFolders ?? new string[0];
foreach (string f in Directory.GetFiles(directory))
{
Console.WriteLine(lvlSeperator+Path.GetFileName(f));
}
foreach (string d in Directory.GetDirectories(directory))
{
Console.WriteLine(lvlSeperator + "-" + Path.GetFileName(d));
if(lvl > 0 && Array.IndexOf(excludedFolders, Path.GetFileName(d)) < 0)
{
PrintDirectoryTree(d, lvl-1, excludedFolders, lvlSeperator+" ");
}
}
}
}
input directory:
-folder1
file1.txt
-folder2
file2.txt
-folder5
file6.txt
-folder3
file3.txt
-folder4
file4.txt
file5.txt
output of the function (content of folder5 is excluded due to lvl limit and content of folder3 is excluded because it is in excludedFolders array):
-folder1
file1.txt
-folder2
file2.txt
-folder5
-folder3
-folder4
file4.txt
file5.txt
Can not get a simple bootstrap modal to work
I had an issue with Modals as well. I should have declare jquery.min.js before bootstrap.min.js (in my layout page).
From official site : "all plugins depend on jQuery (this means jQuery must be included before the plugin files)"
Run all SQL files in a directory
I wrote an open source utility in C# that allows you to drag and drop many SQL files and start running them against a database.
The utility has the following features:
- Drag And Drop script files
- Run a directory of script files
- Sql Script out put messages during execution
- Script passed or failed that are colored green and red (yellow for running)
- Stop on error option
- Open script on error option
- Run report with time taken for each script
- Total duration time
- Test DB connection
- Asynchronus
- .Net 4 & tested with SQL 2008
- Single exe file
- Kill connection at anytime
What is an opaque response, and what purpose does it serve?
There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.
The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".
This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html
How can I get the external SD card path for Android 4.0+?
Here's how I get the list of SD-card paths (excluding the primary external storage) :
/**
* returns a list of all available sd cards paths, or null if not found.
*
* @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static List<String> getSdCardPaths(final Context context,final boolean includePrimaryExternalStorage)
{
final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
if(externalCacheDirs==null||externalCacheDirs.length==0)
return null;
if(externalCacheDirs.length==1)
{
if(externalCacheDirs[0]==null)
return null;
final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
if(!Environment.MEDIA_MOUNTED.equals(storageState))
return null;
if(!includePrimaryExternalStorage&&VERSION.SDK_INT>=VERSION_CODES.HONEYCOMB&&Environment.isExternalStorageEmulated())
return null;
}
final List<String> result=new ArrayList<>();
if(includePrimaryExternalStorage||externalCacheDirs.length==1)
result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
for(int i=1;i<externalCacheDirs.length;++i)
{
final File file=externalCacheDirs[i];
if(file==null)
continue;
final String storageState=EnvironmentCompat.getStorageState(file);
if(Environment.MEDIA_MOUNTED.equals(storageState))
result.add(getRootOfInnerSdCardFolder(externalCacheDirs[i]));
}
if(result.isEmpty())
return null;
return result;
}
/** Given any file/folder inside an sd card, this will return the path of the sd card */
private static String getRootOfInnerSdCardFolder(File file)
{
if(file==null)
return null;
final long totalSpace=file.getTotalSpace();
while(true)
{
final File parentFile=file.getParentFile();
if(parentFile==null||parentFile.getTotalSpace()!=totalSpace||!parentFile.canRead())
return file.getAbsolutePath();
file=parentFile;
}
}
How to tell PowerShell to wait for each command to end before starting the next?
Besides using Start-Process -Wait
, piping the output of an executable will make Powershell wait. Depending on the need, I will typically pipe to Out-Null
, Out-Default
, Out-String
or Out-String -Stream
. Here is a long list of some other output options.
# Saving output as a string to a variable.
$output = ping.exe example.com | Out-String
# Filtering the output.
ping stackoverflow.com | where { $_ -match '^reply' }
# Using Start-Process affords the most control.
Start-Process -Wait SomeExecutable.com
I do miss the CMD/Bash style operators that you referenced (&, &&, ||). It
seems we have to be more verbose with Powershell.
How to set default values for Angular 2 component properties?
Here is the best solution for this. (ANGULAR All Version)
Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.
I have provided solution for this kind of similar question. You can find the full solution from here
export class CarComponent implements OnInit {
private _defaultCar: car = {
// default isCar is true
isCar: true,
// default wheels will be 4
wheels: 4
};
@Input() newCar: car = {};
constructor() {}
ngOnInit(): void {
// this will concate both the objects and the object declared later (ie.. ...this.newCar )
// will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT
this.newCar = { ...this._defaultCar, ...this.newCar };
// console.log(this.newCar);
}
}
How to modify a specified commit?
If for some reason you don't like interactive editors, you can use git rebase --onto
.
Say you want to modify Commit1
. First, branch from before Commit1
:
git checkout -b amending [commit before Commit1]
Second, grab Commit1
with cherry-pick
:
git cherry-pick Commit1
Now, amend your changes, creating Commit1'
:
git add ...
git commit --amend -m "new message for Commit1"
And finally, after having stashed any other changes, transplant the rest of your commits up to master
on top of your
new commit:
git rebase --onto amending Commit1 master
Read: "rebase, onto the branch amending
, all commits between Commit1
(non-inclusive) and master
(inclusive)". That is, Commit2 and Commit3, cutting the old Commit1 out entirely. You could just cherry-pick them, but this way is easier.
Remember to clean up your branches!
git branch -d amending
Digital Certificate: How to import .cer file in to .truststore file using?
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
How to get text box value in JavaScript
If it is in a form then it would be:
<form name="jojo">
<input name="jobtitle">
</form>
Then you would say in javascript:
var val= document.jojo.jobtitle.value
document.formname.elementname
Make a UIButton programmatically in Swift
You're just missing the colon at the end of the selector name. Since pressed takes a parameter the colon must be there. Also your pressed function shouldn't be nested inside viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myFirstLabel = UILabel()
let myFirstButton = UIButton()
myFirstLabel.text = "I made a label on the screen #toogood4you"
myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
myFirstLabel.textColor = UIColor.redColor()
myFirstLabel.textAlignment = .Center
myFirstLabel.numberOfLines = 5
myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
myFirstButton.setTitle("?", forState: .Normal)
myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
myFirstButton.frame = CGRectMake(15, -50, 300, 500)
myFirstButton.addTarget(self, action: #selector(myClass.pressed(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(myFirstLabel)
self.view.addSubview(myFirstButton)
}
@objc func pressed(sender: UIButton!) {
var alertView = UIAlertView()
alertView.addButtonWithTitle("Ok")
alertView.title = "title"
alertView.message = "message"
alertView.show()
}
EDIT: Updated to reflect best practices in Swift 2.2. #selector() should be used rather than a literal string which is deprecated.
System.web.mvc missing
MVC 5
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Stack 5\Packages\ Microsoft.AspNet.Mvc.5.0.0\lib\net45\System.Web.Mvc.dll
MVC 4
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Web.Mvc.dll
MVC 3
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll
MVC 2
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dll
Where can I find System.Web.MVC dll in a system where MVC 3 is installed?
javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find
In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources"
For example:
_x000D_
_x000D_
<GlobalNamingResources>_x000D_
<!-- Editable user database that can also be used by_x000D_
UserDatabaseRealm to authenticate users_x000D_
-->_x000D_
<!-- Other previus resouces -->_x000D_
<Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
</GlobalNamingResources>
_x000D_
_x000D_
_x000D_
In your web application you need a link to that resource (ResourceLink):
_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
<ResourceLink name="jdbc/your_jndi"_x000D_
global="jdbc/your_jndi"_x000D_
auth="Container"_x000D_
type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
_x000D_
_x000D_
So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml
_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
<persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
<provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
<properties>_x000D_
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />_x000D_
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
_x000D_
<!-- <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
<property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
<property name="hibernate.show_sql" value="false" />_x000D_
<property name="hibernate.format_sql" value="true"/> _x000D_
</properties>_x000D_
</persistence-unit>_x000D_
</persistence>
_x000D_
_x000D_
_x000D_
So in your spring.xml you can do that:
_x000D_
_x000D_
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
</bean>_x000D_
_x000D_
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
<property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
<property name="dataSource" ref="postGresDataSource" />_x000D_
<property name="jpaVendorAdapter"> _x000D_
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
</property>_x000D_
</bean>
_x000D_
_x000D_
_x000D_
Look above that entityManagerFactory bean refers to your UNIT_NAME configured at persistence xml and the bean postGresDataSource has a property that points to your JNDI resource in Tomcat.
_x000D_
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
_x000D_
_x000D_
In this example I used spring with xml but you can do this programmaticaly if you prefer.
That's it, I hope helped.
Customizing Bootstrap CSS template
I recently wrote a post about how I've been doing it at Udacity for the last couple years. This method has meant we've been able to update Bootstrap whenever we wanted to without having merge conflicts, thrown out work, etc. etc.
The post goes more in depth with examples, but the basic idea is:
- Keep a pristine copy of bootstrap and overwrite it externally.
- Modify one file (bootstrap's variables.less) to include your own variables.
- Make your site file @include bootstrap.less and then your overrides.
This does mean using LESS, and compiling it down to CSS before shipping it to the client (client-side LESS if finicky, and I generally avoid it) but it is EXTREMELY good for maintainability/upgradability, and getting LESS compilation is really really easy. The linked github code has an example using grunt, but there are many ways to achieve this -- even GUIs if that's your thing.
Using this solution, your example problem would look like:
- Change the nav bar color with @navbar-inverse-bg in your variables.less (not bootstrap's)
- Add your own nav bar styles to your bootstrap_overrides.less, overwriting anything you need to as you go.
- Happiness.
When it comes time to upgrade your bootstrap, you just swap out the pristine bootstrap copy and everything will still work (if bootstrap makes breaking changes, you'll need to update your overrides, but you'd have to do that anyway)
Blog post with walk-through is here.
Code example on github is here.
Disable cross domain web security in Firefox
For anyone finding this question while using Nightwatch.js (1.3.4), there's an acceptInsecureCerts: true
setting in the config file:
_x000D_
_x000D_
firefox: {_x000D_
desiredCapabilities: {_x000D_
browserName: 'firefox',_x000D_
alwaysMatch: {_x000D_
// Enable this if you encounter unexpected SSL certificate errors in Firefox_x000D_
acceptInsecureCerts: true,_x000D_
'moz:firefoxOptions': {_x000D_
args: [_x000D_
// '-headless',_x000D_
// '-verbose'_x000D_
],_x000D_
}_x000D_
}_x000D_
}_x000D_
},
_x000D_
_x000D_
_x000D_
How do I delete files programmatically on Android?
Why don't you test this with this code:
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + uri.getPath());
} else {
System.out.println("file not Deleted :" + uri.getPath());
}
}
I think part of the problem is you never try to delete the file, you just keep creating a variable that has a method call.
So in your case you could try:
File file = new File(uri.getPath());
file.delete();
if(file.exists()){
file.getCanonicalFile().delete();
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
However I think that's a little overkill.
You added a comment that you are using an external directory rather than a uri. So instead you should add something like:
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/images/media/2918");
Then try to delete the file.
How to concatenate two layers in keras?
You can experiment with model.summary()
(notice the concatenate_XX (Concatenate) layer size)
# merge samples, two input must be same shape
inp1 = Input(shape=(10,32))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=0) # Merge data must same row column
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
# merge row must same column size
inp1 = Input(shape=(20,10))
inp2 = Input(shape=(32,10))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
# merge column must same row size
inp1 = Input(shape=(10,20))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()
You can view notebook here for detail:
https://nbviewer.jupyter.org/github/anhhh11/DeepLearning/blob/master/Concanate_two_layer_keras.ipynb
Handling warning for possible multiple enumeration of IEnumerable
If you only need to check the first element you can peek on it without iterating the whole collection:
public List<object> Foo(IEnumerable<object> objects)
{
object firstObject;
if (objects == null || !TryPeek(ref objects, out firstObject))
throw new ArgumentException();
var list = DoSomeThing(firstObject);
var secondList = DoSomeThingElse(objects);
list.AddRange(secondList);
return list;
}
public static bool TryPeek<T>(ref IEnumerable<T> source, out T first)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
IEnumerator<T> enumerator = source.GetEnumerator();
if (!enumerator.MoveNext())
{
first = default(T);
source = Enumerable.Empty<T>();
return false;
}
first = enumerator.Current;
T firstElement = first;
source = Iterate();
return true;
IEnumerable<T> Iterate()
{
yield return firstElement;
using (enumerator)
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
}
How to Save Console.WriteLine Output to Text File
Necromancing.
I usually just create a class, which I can wrap around main in an IDisposable.
So I can log the console output to a file without modifying the rest of the code.
That way, I have the output in both the console and for later reference in a text-file.
public class Program
{
public static async System.Threading.Tasks.Task Main(string[] args)
{
using (ConsoleOutputMultiplexer co = new ConsoleOutputMultiplexer())
{
// Do something here
System.Console.WriteLine("Hello Logfile and Console 1 !");
System.Console.WriteLine("Hello Logfile and Console 2 !");
System.Console.WriteLine("Hello Logfile and Console 3 !");
} // End Using co
System.Console.WriteLine(" --- Press any key to continue --- ");
System.Console.ReadKey();
await System.Threading.Tasks.Task.CompletedTask;
} // End Task Main
}
with
public class MultiTextWriter
: System.IO.TextWriter
{
protected System.Text.Encoding m_encoding;
protected System.Collections.Generic.IEnumerable<System.IO.TextWriter> m_writers;
public override System.Text.Encoding Encoding => this.m_encoding;
public override System.IFormatProvider FormatProvider
{
get
{
return base.FormatProvider;
}
}
public MultiTextWriter(System.Collections.Generic.IEnumerable<System.IO.TextWriter> textWriters, System.Text.Encoding encoding)
{
this.m_writers = textWriters;
this.m_encoding = encoding;
}
public MultiTextWriter(System.Collections.Generic.IEnumerable<System.IO.TextWriter> textWriters)
: this(textWriters, textWriters.GetEnumerator().Current.Encoding)
{ }
public MultiTextWriter(System.Text.Encoding enc, params System.IO.TextWriter[] textWriters)
: this((System.Collections.Generic.IEnumerable<System.IO.TextWriter>)textWriters, enc)
{ }
public MultiTextWriter(params System.IO.TextWriter[] textWriters)
: this((System.Collections.Generic.IEnumerable<System.IO.TextWriter>)textWriters)
{ }
public override void Flush()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Flush();
}
}
public async override System.Threading.Tasks.Task FlushAsync()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.FlushAsync();
}
await System.Threading.Tasks.Task.CompletedTask;
}
public override void Write(char[] buffer, int index, int count)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Write(buffer, index, count);
}
}
public override void Write(System.ReadOnlySpan<char> buffer)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Write(buffer);
}
}
public async override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.WriteAsync(buffer, index, count);
}
await System.Threading.Tasks.Task.CompletedTask;
}
public async override System.Threading.Tasks.Task WriteAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.WriteAsync(buffer, cancellationToken);
}
await System.Threading.Tasks.Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Dispose();
}
}
public async override System.Threading.Tasks.ValueTask DisposeAsync()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.DisposeAsync();
}
await System.Threading.Tasks.Task.CompletedTask;
}
public override void Close()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Close();
}
} // End Sub Close
} // End Class MultiTextWriter
public class ConsoleOutputMultiplexer
: System.IDisposable
{
protected System.IO.TextWriter m_oldOut;
protected System.IO.FileStream m_logStream;
protected System.IO.StreamWriter m_logWriter;
protected MultiTextWriter m_multiPlexer;
public ConsoleOutputMultiplexer()
{
this.m_oldOut = System.Console.Out;
try
{
this.m_logStream = new System.IO.FileStream("./Redirect.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
this.m_logWriter = new System.IO.StreamWriter(this.m_logStream);
this.m_multiPlexer = new MultiTextWriter(this.m_oldOut.Encoding, this.m_oldOut, this.m_logWriter);
System.Console.SetOut(this.m_multiPlexer);
}
catch (System.Exception e)
{
System.Console.WriteLine("Cannot open Redirect.txt for writing");
System.Console.WriteLine(e.Message);
return;
}
} // End Constructor
void System.IDisposable.Dispose()
{
System.Console.SetOut(this.m_oldOut);
if (this.m_multiPlexer != null)
{
this.m_multiPlexer.Flush();
if (this.m_logStream != null)
this.m_logStream.Flush();
this.m_multiPlexer.Close();
}
if(this.m_logStream != null)
this.m_logStream.Close();
} // End Sub Dispose
} // End Class ConsoleOutputMultiplexer
How do I use $scope.$watch and $scope.$apply in AngularJS?
Just finish reading ALL the above, boring and sleepy (sorry but is true). Very technical, in-depth, detailed, and dry.
Why am I writing? Because AngularJS is massive, lots of inter-connected concepts can turn anyone going nuts. I often asked myself, am I not smart enough to understand them? No! It's because so few can explain the tech in a for-dummie language w/o all the terminologies!
Okay, let me try:
1) They are all event-driven things. (I hear the laugh, but read on)
If you don't know what event-driven is Then
think you place a button
on the page, hook it up w/ a function using "on-click", waiting for
users to click on it to trigger the actions you plant inside the
function. Or think of "trigger" of SQL Server / Oracle.
2) $watch is "on-click".
What's special about is it takes 2 functions as parameters, first one
gives the value from the event, second one takes the value into
consideration...
3) $digest is the boss who checks around tirelessly,
bla-bla-bla but a good boss.
4) $apply gives you the way when you want to do it manually, like a fail-proof (in case on-click doesn't kick in, you force it to run.)
Now, let's make it visual. Picture this to make it even more easy to
grab the idea:
In a restaurant,
- WAITERS
are supposed to take orders from customers, this is
$watch(
function(){return orders;},
function(){Kitchen make it;}
);
- MANAGER running around to make sure all waiters are awake, responsive to any sign of changes from customers. This is $digest()
- OWNER has the ultimate power to drive everyone upon request, this is $apply()
In TensorFlow, what is the difference between Session.run() and Tensor.eval()?
Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0)
for the benefit of the community.
!pip install tensorflow==2.1
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default(): # or `with sess:` to close on exit
assert sess is tf.compat.v1.get_default_session()
assert t.eval() == sess.run(t)
#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:
t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
tu.eval() # runs one step
ut.eval() # runs one step
sess.run([tu, ut]) # evaluates both tensors in a single step
How to get the HTML's input element of "file" type to only accept pdf files?
The previous posters made a little mistake. The accept attribute is only a display filter. It will not validate your entry before submitting.
This attribute forces the file dialog to display the required mime type only.
But the user can override that filter. He can choose . and see all the files in the current directory. By doing so, he can select any file with any extension, and submit the form.
So, to answer to the original poster, NO. You cannot restrict the input file to one particular extension by using HTML.
But you can use javascript to test the filename that has been chosen, just before submitting. Just insert an onclick attribute on your submit button and call the code that will test the input file value. If the extension is forbidden, you'll have to return false to invalidate the form. You may even use a jQuery custom validator and so on, to validate the form.
Finally, you'll have to test the extension on the server side too.
Same problem about the maximum allowed file size.
Clear form after submission with jQuery
try this in your post methods callback function
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
for more info read this
how to convert a string to a bool
If you want to test if a string is a valid Boolean without any thrown exceptions you can try this :
string stringToBool1 = "true";
string stringToBool2 = "1";
bool value1;
if(bool.TryParse(stringToBool1, out value1))
{
MessageBox.Show(stringToBool1 + " is Boolean");
}
else
{
MessageBox.Show(stringToBool1 + " is not Boolean");
}
outputis Boolean
and the output for stringToBool2 is : 'is not Boolean'
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
Get the system date and split day, month and year
Without opening an IDE to check my brain works properly for syntax at this time of day...
If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.
So
DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");
would give you the date as a string in the format you request.
Catching exceptions from Guzzle
If the Exception is being thrown in that try
block then at worst case scenario Exception
should be catching anything uncaught.
Consider that the first part of the test is throwing the Exception and wrap that in the try
block as well.
Calling a phone number in swift
The above answers are partially correct, but with "tel://" there is only one issue. After the call has ended, it will return to the homescreen, not to our app. So better to use "telprompt://", it will return to the app.
var url:NSURL = NSURL(string: "telprompt://1234567891")!
UIApplication.sharedApplication().openURL(url)
How do you do a limit query in JPQL or HQL?
String hql = "select userName from AccountInfo order by points desc 5";
This worked for me without using setmaxResults();
Just provide the max value in the last (in this case 5) without using the keyword limit
.
:P
Python can't find module in the same folder
Your code is fine, I suspect your problem is how you are launching it.
You need to launch python from your '2014_07_13_test' directory.
Open up a command prompt and 'cd' into your '2014_07_13_test' directory.
For instance:
$ cd /path/to/2014_07_13_test
$ python test.py
If you cannot 'cd' into the directory like this you can add it to sys.path
In test.py:
import sys, os
sys.path.append('/path/to/2014_07_13_test')
Or set/edit the PYTHONPATH
And all should be well...
...well there is a slight mistake with your 'shebang' lines (the first line in both your files), there shouldn't be a space between the '#' and the '!'
There is a better shebang you should use.
Also you don't need the shebang line on every file... only the ones you intend to run from your shell as executable files.
Python Traceback (most recent call last)
In Python2, input
is evaluated, input()
is equivalent to eval(raw_input())
. When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.
Use raw_input
to get a string from the user in Python2.
Demo 1: klj
is not defined:
>>> input()
klj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined
Demo 2: klj
is defined:
>>> klj = 'hi'
>>> input()
klj
'hi'
Demo 3: getting a string with raw_input
:
>>> raw_input()
klj
'klj'
What is the JavaScript equivalent of var_dump or print_r in PHP?
I put this forward to help anyone needing something readily practical for giving you a nice, prettified (indented) picture of a JS Node
. None of the other solutions worked for me for a Node
("cyclical error" or whatever...). This walks you through the tree under the DOM Node
(without using recursion) and gives you the depth, tagName
(if applicable) and textContent
(if applicable).
Any other details from the nodes you encounter as you walk the tree under the head node can be added as per your interest...
function printRNode( node ){
// make sort of human-readable picture of the node... a bit like PHP print_r
if( node === undefined || node === null ){
throwError( 'node was ' + typeof node );
}
let s = '';
// NB walkDOM could be made into a utility function which you could
// call with one or more callback functions as parameters...
function walkDOM( headNode ){
const stack = [ headNode ];
const depthCountDowns = [ 1 ];
while (stack.length > 0) {
const node = stack.pop();
const depth = depthCountDowns.length - 1;
// TODO non-text, non-BR nodes could show more details (attributes, properties, etc.)
const stringRep = node.nodeType === 3? 'TEXT: |' + node.nodeValue + '|' : 'tag: ' + node.tagName;
s += ' '.repeat( depth ) + stringRep + '\n';
const lastIndex = depthCountDowns.length - 1;
depthCountDowns[ lastIndex ] = depthCountDowns[ lastIndex ] - 1;
if( node.childNodes.length ){
depthCountDowns.push( node.childNodes.length );
stack.push( ... Array.from( node.childNodes ).reverse() );
}
while( depthCountDowns[ depthCountDowns.length - 1 ] === 0 ){
depthCountDowns.splice( -1 );
}
}
}
walkDOM( node );
return s;
}
How to use JQuery with ReactJS
You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.
e.g.
class App extends React.Component {
componentDidMount() {
// Jquery here $(...)...
}
// ...
}
Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.
class Accordion extends React.Component {
constructor() {
super();
this._handleClick = this._handleClick.bind(this);
}
componentDidMount() {
this._handleClick();
}
_handleClick() {
const acc = this._acc.children;
for (let i = 0; i < acc.length; i++) {
let a = acc[i];
a.onclick = () => a.classList.toggle("active");
}
}
render() {
return (
<div
ref={a => this._acc = a}
onClick={this._handleClick}>
{this.props.children}
</div>
)
}
}
Then you can use it in any component like so:
class App extends React.Component {
render() {
return (
<div>
<Accordion>
<div className="accor">
<div className="head">Head 1</div>
<div className="body"></div>
</div>
</Accordion>
</div>
);
}
}
Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110
(I changed this link to https ^)
IIS 7, HttpHandler and HTTP Error 500.21
One solution that I've found is that you should have to change the .Net Framework back to v2.0 by Right Clicking on the site that you have manager under the Application Pools from the Advance Settings.
Difference between View and Request scope in managed beans
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
See also:
Postgres: How to do Composite keys?
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
Random number between 0 and 1 in python
My variation that I find to be more flexible.
str_Key = ""
str_FullKey = ""
str_CharacterPool = "01234ABCDEFfghij~-)"
for int_I in range(64):
str_Key = random.choice(str_CharacterPool)
str_FullKey = str_FullKey + str_Key
Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction
The return type of Html.RenderAction
is void
that means it directly renders the responses in View where the return type of Html.Action
is MvcHtmlString
You can catch its render view in controller and modify it by using following method
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
This will return the Html string of the View.
This is also applicable to Html.Partial
and Html.RenderPartial
How do I syntax check a Bash script without running it?
Time changes everything. Here is a web site which provide online syntax checking for shell script.
I found it is very powerful detecting common errors.
About ShellCheck
ShellCheck is a static analysis and linting tool for sh/bash scripts. It's mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.
Haskell source code is available on GitHub!
Best way to store time (hh:mm) in a database
The saving of time in UTC format can help better as Kristen suggested.
Make sure that you are using 24 hr clock because there is no meridian AM or PM be used in UTC.
Example:
- 4:12 AM - 0412
- 10:12 AM - 1012
- 2:28 PM - 1428
- 11:56 PM - 2356
Its still preferrable to use standard four digit format.
Tab separated values in awk
You need to set the OFS
variable (output field separator) to be a tab:
echo "$line" |
awk -v var="$mycol_new" -F $'\t' 'BEGIN {OFS = FS} {$3 = var; print}'
(make sure you quote the $line
variable in the echo statement)
What is the difference between functional and non-functional requirements?
I think functional requirement is from client to developer side that is regarding functionality to the user by the software and non-functional requirement is from developer to client i.e. the requirement is not given by client but it is provided by developer to run the system smoothly e.g. safety, security, flexibility, scalability, availability, etc.
Pip Install not installing into correct directory?
Make sure you pip version matches your python version.
to get your python version use:
python -V
then install the correct pip. You might already have intall in that case try to use:
pip-2.5 install ...
pip-2.7 install ...
or for those of you using macports make sure your version match using.
port select --list pip
then change to the same python version you are using.
sudo port select --set pip pip27
Hope this helps. It work on my end.
What is Inversion of Control?
Using IoC you are not new'ing up your objects. Your IoC container will do that and manage the lifetime of them.
It solves the problem of having to manually change every instantiation of one type of object to another.
It is appropriate when you have functionality that may change in the future or that may be different depending on the environment or configuration used in.
What are DDL and DML?
DDL stands for Data Definition Language. DDL is used for defining structure of the table such as create a table or adding a column to table and even drop and truncate table.
DML stands for Data Manipulation Language. As the name suggest DML used for manipulating the data of table. There are some commands in DML such as insert and delete.
Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab
I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
Same Navigation Drawer in different Activities
With @Kevin van Mierlo 's answer, you are also capable of implementing several drawers. For instance, the default menu located on the left side (start), and a further optional menu, located on the right side, which is only shown when determinate fragments are loaded.
I've been able to do that.
Convert from java.util.date to JodaTime
java.util.Date date = ...
DateTime dateTime = new DateTime(date);
Make sure date
isn't null
, though, otherwise it acts like new DateTime()
- I really don't like that.
Named placeholders in string formatting
StrSubstitutor of jakarta commons lang is a light weight way of doing this provided your values are already formatted correctly.
http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html
Map<String, String> values = new HashMap<String, String>();
values.put("value", x);
values.put("column", y);
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");
The above results in:
"There's an incorrect value '1' in column # 2"
When using Maven you can add this dependency to your pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
Fill Combobox from database
To use the Combobox
in the way you intend, you could pass in an object to the cmbTripName.Items.Add
method.
That object should have FleetID
and FleetName
properties:
while (drd.Read())
{
cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";
The Fleet
Class:
class Fleet
{
public Fleet(string fleetId, string fleetName)
{
FleetId = fleetId;
FleetName = fleetName
}
public string FleetId {get;set;}
public string FleetName {get;set;}
}
Or, You could probably do away with the need for a Fleet
class completely by using an anonymous type...
while (drd.Read())
{
cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";